我想知道如何编写一个函数或循环来计算基于两种资产的历史投资组合波动率。波动率应在 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")
为什么该功能不起作用?