Faster Way of Calculating Rolling Realized Volatility in R

r xts
mchangun picture mchangun · Oct 10, 2012 · Viewed 11.6k times · Source

I want to calculate the rolling 20 day realized volatility for a collection of indices. Here is the code I use to download the index prices, calculate the daily returns and the 20 day realized volatility.

library(quantmod)
library(PerformanceAnalytics)

tickers = c("^RUT","^STOXX50E","^HSI", "^N225", "^KS11")
myEnv <- new.env()
getSymbols(tickers, src='yahoo', from = "2003-01-01", env = myEnv)
index <- do.call(merge, c(eapply(myEnv, Ad), all=FALSE))

#Calculate daily returns for all indices and convert to arithmetic returns
index.ret <- exp(CalculateReturns(index,method="compound")) - 1
index.ret[1,] <- 0

#Calculate realized volatility
realizedvol <- rollapply(index.ret, width = 20, FUN=sd.annualized)

Everything works pretty quick until the final line. I haven't timed it but it is on the scale of minutes whereas I would expect it to take only seconds. Is there a faster way to calculate the realized volatility?

Thank you.

Answer

Joshua Ulrich picture Joshua Ulrich · Oct 10, 2012

You can use runSD in the TTR package (which is loaded by quantmod), but you will need to apply runSD to each column, convert the result of apply back to an xts object, and manually annualize the result.

realized.vol <- xts(apply(index.ret,2,runSD,n=20), index(index.ret))*sqrt(252)