1

I am trying to replicate ewm python (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html) function in R but without success.

Here is the python code:

import pandas as pd
df = pd.DataFrame({'B': [0:100]})
df.ewm(span=100).std()

I can't get same (or similar) results in R.

Mislav Sagovac
  • 185
  • 1
  • 8
  • What is it you have tried in R that doesn't work? – matt_jay Jan 17 '21 at 12:58
  • I tried this solution: https://stackoverflow.com/questions/54585015/vectorized-implementation-of-exponentially-weighted-moving-standard-deviation-us but is extremely slow. – Mislav Sagovac Jan 17 '21 at 13:23
  • And I have also tried `frollapply(as.vector(df0), n = 100, FUN = function(x) sqrt(Hmisc::wtd.var(x)))` – Mislav Sagovac Jan 17 '21 at 13:31
  • here's R code for doing so: https://gist.github.com/assuncaolfi/5581528021ac75247a4a1f1c0c3fe12f – tester Jan 17 '21 at 21:28
  • Does this answer your question? [Vectorized implementation of exponentially weighted moving standard deviation using R?](https://stackoverflow.com/questions/54585015/vectorized-implementation-of-exponentially-weighted-moving-standard-deviation-us) – tester Jan 17 '21 at 21:28
  • @tester, I tried this code but it is so slow that I didn't even wait it to finish. Python code takes only one or 2 seconds. ANd I am not even sure it is the same. – Mislav Sagovac Jan 18 '21 at 07:54

1 Answers1

1

I have change the code from Vectorized implementation of exponentially weighted moving standard deviation using R? to make it much fater:

f <- function(y, m, alpha) {
  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))
  ewmsd
} 
test <- frollapply(df0, 1000, function(x) f(x, 1000, alpha))

where df0 is df with one column or vector.

Results are the same (to 5 decimal place) as reults generated from python function.

Mislav Sagovac
  • 185
  • 1
  • 8