Skip to content

Instantly share code, notes, and snippets.

@wilsonfreitas
Last active February 13, 2021 14:42
Show Gist options
  • Save wilsonfreitas/6279978 to your computer and use it in GitHub Desktop.
Save wilsonfreitas/6279978 to your computer and use it in GitHub Desktop.
Computing EWMA in R using two different approaches: loop and functional. Clearly functional approach is more efficient.
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)) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment