计算滚动历史投资组合波动率

时间:2015-08-19 19:15:29

标签: r portfolio volatility

我想知道如何编写一个可以根据两个资产计算历史投资组合波动率的函数或循环。波动率应在36个月的滚动期内计算。

我从以下随机样本数据开始:

require(PerformanceAnalytics)
require(zoo)
data(edhec)
R <-edhec[, 1:1]

# sample monthly returns 
r1<-runif(152,-1,2)
r2<-runif(152,-2,3)
returns1<-data.frame(R,r1,r2)
returns1<-returns1[,-(1), drop=FALSE]

# sample monthly weights
W <-edhec[, 1:1]
w1<-runif(152,0,1)
w2<-runif(152,0,1)
weights1<-data.frame(W,w1,w2)
weights1<-weights1[,-(1), drop=FALSE]
sums<-apply(weights1,1,sum)
weights1<-sweep(weights1,1,sums,'/')

### the following obviously doesn't work
### calculate portfolio volatility - does not work ###
portVol1 <- sqrt(t(weights1) %*% cov(returns1) %*% weights1)

### so I make the weights static to show what im looking for
### this gives portfolio volatility over the whole dataset
### portfolio volatility with fixed weight###
weights2<-c(0.9,0.1)
portVol2 <- sqrt(t(weights2) %*% cov(returns1) %*% weights2)
print(portVol2)

理想情况下,我需要一些函数或循环,以便计算portvol1 滚动期为36个月(从前36个月开始),数据为returns1

此功能需要读取该特定月份的资产weights1

我的问题是,我可以对每个向量进行滚动波动,但不能对由多个向量(资产)组成的投资组合进行滚动波动。

首先,退一步,为什么以下var3没有考虑权重:

var2<-rollapply(returns1, width=12,FUN=function(returns1) VaR(R=returns1, p=.95, method="historical"), by.column=TRUE)

var3<-rollapply(returns1, width=12,FUN=function(returns1) VaR(R=returns1, p=.95, method="historical"), weights=weights1, by.column=TRUE)

其次,为了计算一个函数中滚动权重的滚动投资组合波动率,我首先尝试让权重工作:

VaRF<- function(x) {VaR(returns1, p=.95, method="historical", 
                        portfolio_method="historical", weights = weights1)
}

rollingVaRF = rollapply(returns1,width=12,
                        FUN=VaRF, align="right")

为什么功能不起作用?

0 个答案:

没有答案