2013-05-18 23 views
1

我想用历史方法计算一个月末的VaR。我的时间序列将从2000年初开始到现在。计算应该在2005年开始让我们说有足够的数据。有一个类似的帖子rolling computations in xts by month,我试图修改我的案例的代码。每个月末的VaR应该使用过去的数据。按月份xts滚动计算第2部分

这里是我的代码(在这里它开始于2012年,因为否则它会采取长):

所有的
library(quantmod) 
getSymbols("^GSPC",return.class = "zoo",from = "2012-01-01",to = Sys.Date()) 
sp500 <- Ad(GSPC) 
ldr_sp500 <- Return.calculate(sp500, method = "log") 
ldr_sp500 <- na.omit(ldr_sp500) 
idx <- index(ldr_sp500)[endpoints(ldr_sp500, 'months')] 
out <- lapply(idx, function(i) { 
    as.xts(rollapplyr(as.zoo(ldr_sp500), 30, VaR)) 
}) 
sapply(out, NROW) 

首先出现的是我的代码中存在较大的误差。宽度应该是多少?是否也可以将输出作为动物园对象? IAM与这种功能的初学者...当我不想使用历史的方法,而是高斯方法,我会用:

apply.monthly(as.xts(ldr_sp500), VaR, method="gaussian") 

看来这正常工作与非重叠的时期...

回答

1

在您的代码中,lapply中的函数没有使用它的参数i: 您正在计算同样的事情(期间中每天的风险价值) 一遍又一遍。

此外,VaR的默认方法是modified: 你需要指定method="historical"

如果要计算从当前月份的日收益风险值, 您的建议,使用使用apply.monthly实际工作:

apply.monthly(ldr_sp500, VaR, method="historical") 

如果你想扩大的窗口,而不是:

library(quantmod) 
library(PerformanceAnalytics) 
getSymbols("^GSPC", from = "2012-01-01") 
x <- Return.calculate(Ad(GSPC), method = "log") 
idx <- index(x)[endpoints(x, 'months')] 
result <- sapply(idx, 
    function(i) VaR(x[paste0("/",i)], method = "historical") 
) 
xts(result, idx)