Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster Way of Calculating Rolling Realized Volatility in R

Tags:

r

xts

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.

like image 694
mchangun Avatar asked Oct 10 '12 15:10

mchangun


1 Answers

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)
like image 112
Joshua Ulrich Avatar answered Oct 26 '22 01:10

Joshua Ulrich