Skip to content

Instantly share code, notes, and snippets.

@assuncaolfi
Created May 4, 2019 17:52
Show Gist options
  • Save assuncaolfi/5581528021ac75247a4a1f1c0c3fe12f to your computer and use it in GitHub Desktop.
Save assuncaolfi/5581528021ac75247a4a1f1c0c3fe12f to your computer and use it in GitHub Desktop.
Vectorized R implementation of exponentially weighted moving average and standard deviation. Outputs the same as Python's default pandas.Series.ewm().
ewma <- function(x, alpha) {
n <- length(x)
sapply(
1:n,
function(i, x, alpha) {
y <- x[1:i]
m <- length(y)
weights <- (1 - alpha)^((m - 1):0)
ewma <- sum(weights * y) / sum(weights)
},
x = x,
alpha = alpha
)
}
ewmsd <- function(x, alpha) {
n <- length(x)
sapply(
1:n,
function(i, x, alpha) {
y <- x[1:i]
m <- length(y)
weights <- (1 - alpha)^((m - 1):0)
ewma <- sum(weights * y) / sum(weights)
bias <- sum(weights)^2 / (sum(weights)^2 - sum(weights^2))
ewmsd <- sqrt(bias * sum(weights * (y - ewma)^2) / sum(weights))
},
x = x,
alpha = alpha
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment