0

I'm wondering how to write a function or loop that can calculate historical portfolio volatility based on two assets. The volatility should be calculated over a rolling period of 36 months.

I start with the following random sample data:

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)

Ideally I need some function or loop so that portvol1 is calculated over a rolling period of 36 months (starting after first 36 months) with returns1 data.

This function needs to read the asset weights1 for that particular month.

My problem here is that I can do a rolling volatility per vector, but not of a portfolio which consists of multiple vectors (assets).

First, one step back, why does var3 in the following below not take into account of the weights:

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)

Second, in order to calculate a rolling portfolio volatility with rolling weights in a function, I first try to get weights to work after all:

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

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

Why does the function not work?

M_Sunny
  • 47
  • 1
  • 7
  • See `zoo::rollapply` – Vlo Aug 19 '15 at 19:43
  • thanks! I looked into it. rolling calculations of 1 vector is not an issue. My problem starts when I need to roll two variables (as in portfolio volatility, namely returns and weights). I updated my question with some code. – M_Sunny Aug 21 '15 at 11:59

0 Answers0