Skip to content

Moving volatility

4 messages · ehxpieterse, Shane Conway, Gabor Grothendieck +1 more

#
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")
#
There is also rollapply in the zoo package:

set.seed(123)
library(zoo)
x <- zoo(rnorm(25))
z1 <- rollapply(x, 5, sd)

or using rollmean (which is faster)

z2 <- sqrt(5/4 * (rollmean(x*x,5) - rollmean(x,5)^2))

all.equal(z1, z2) # TRUE

On Tue, Aug 4, 2009 at 8:41 AM,
ehxpieterse<eduard.pieterse at macquarie.com> wrote:
#
Eduard,

Please read the documentation.  ?addVolatility notes that it uses the
volatility function in TTR.

TTR's moving window functions (see ?runFun) call compiled code, so
they are very fast.  They also use xts internally, so they accept and
return a variety of time series classes (ts, zoo, timeSeries, etc.).

Best,
Josh
--
http://www.fosstrading.com
On Tue, Aug 4, 2009 at 8:08 AM, Shane Conway<shane.conway at gmail.com> wrote: