Skip to content
Prev 4702 / 15274 Next

Moving volatility

Hi,

I have found a function online to calculate moving volatility. I am aware of
addVolatility in the quantmod package, but that only adds the vol to a
graph. Does any one know if there exists a better function to use than the
one shown below? I find the current one quite slow when working with large
data sets.

movsd <- function(series,lag) 
{ 
movingsd <- vector(mode="numeric") 
for (i in lag:length(series))

	{
	movingsd[i] <- sd(series[(i-lag+1):i])
	}

assign("movingsd",movingsd,.GlobalEnv) 
}

to.dat <- as.Date(Sys.Date(), format="%m/%d/%y")
getSymbols("^GSPC", src="yahoo", from = "2000-01-01", to = to.dat)
CloseData <- Cl(GSPC)

x <- movsd(Delt(CloseData),40)
xx <- x*100
plot(xx, type="l")