Created
May 4, 2019 17:52
-
-
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().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://stackoverflow.com/questions/54585015/vectorized-implementation-of-exponentially-weighted-moving-standard-deviation-us