Faster Way of Calculating Rolling Realized Volatility in R

旧街凉风 提交于 2019-12-04 09:25:20

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/12823445/faster-way-of-calculating-rolling-realized-volatility-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!