Skip to content

Instantly share code, notes, and snippets.

@wilsonfreitas
Created April 4, 2014 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilsonfreitas/9972408 to your computer and use it in GitHub Desktop.
Save wilsonfreitas/9972408 to your computer and use it in GitHub Desktop.
ewma.filter <- function(rets, lambda) {
r2 <- (1 - lambda)*rets^2
sqrt(filter(r2, lambda, "recursive", init=0))
}
ewma.func <- function(rets, lambda) {
sig.p <- 0
sig.s <- vapply(rets, function(r) sig.p <<- sig.p*lambda + (r^2)*(1 - lambda), 0)
return(sqrt(sig.s))
}
ewma.loop <- function(rets, lambda) {
n <- length(rets)+1
sig.s <- rep(0, n)
for (i in 2:n) {
sig.s[i] <- sig.s[i-1]*lambda + (rets[i-1]^2)*(1 - lambda)
}
return(sqrt(tail(sig.s, n-1)))
}
lambda <- 0.94
rets <- 0.02*rnorm(100)
system.time( replicate(10000, ewma.loop(rets, lambda)) )
system.time( replicate(10000, ewma.func(rets, lambda)) )
system.time( replicate(10000, ewma.filter(rets, lambda)) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment