首页 > 解决方案 > 在 R 中复制 ewm pandas 函数

问题描述

我正在尝试在 R 中复制 ewm python ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.ewm.html ) 函数但没有成功。

这是python代码:

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

我无法在 R 中得到相同(或相似)的结果。

标签: r

解决方案


我已经从使用 R 的指数加权移动标准差的矢量化实现中更改了代码?让它更胖:

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))

其中 df0 是具有一列或向量的 df。

结果与从 python 函数生成的结果相同(到小数点后 5 位)。


推荐阅读