python - pandas ewm.std 计算

标签 python pandas dataframe

我正在尝试验证 pandas 的 ewm.std 计算,以便我可以对我的代码实现一步更新。这是代码问题的完整描述。

mrt = pd.Series(np.random.randn(1000))
N = 100
a = 2/(1+N)
bias = (2-a)/2/(1-a)
x = mrt.iloc[-2]
ma = mrt.ewm(span=N).mean().iloc[-3]
var = mrt.ewm(span=N).var().iloc[-3]
ans = mrt.ewm(span=N).std().iloc[-2]
print(np.sqrt( bias*(1-a) * (var + a * (x- ma)**2)), ans)

(1.1352524643949702, 1.1436193844674576)

我使用的是标准公式。有人能告诉我为什么这两个值不应该相同吗?即 pandas 如何计算指数加权标准差?

编辑:在 Julien 的回答之后 - 让我再给出一个用例。我正在绘制由 pandas 计算的 var 的比率,并使用我从 pandas ewm-covariance 的 Cython 代码推断的公式。这个比率应该是 1。(我猜我的公式有问题,如果有人能指出的话)。

mrt = pd.Series(np.random.randn(1000))

N = 100
a = 2./(1+N)
bias = (2-a)/2./(1-a)
mewma = mrt.ewm(span=N).mean()

var_pandas = mrt.ewm(span=N).var()
var_calculated = bias * (1-a) * (var_pandas.shift(1) + a * (mrt-mewma.shift(1))**2)

(var_calculated/var_pandas).plot()

情节清楚地说明了问题。

plot of the ratio after the initial values are removed

编辑 2:通过反复试验,我找到了正确的公式:

var_calculated = (1-a) * (var_pandas.shift(1) + bias * a * (mrt-mewma.shift(1))**2)

但我不相信它应该是正确的!有人可以阐明这一点吗?

最佳答案

你的问题实际上实际上减少了 pandas 如何计算 ewm.var()

In [1]:
(np.sqrt(mrt.ewm(span=span).var()) == mrt.ewm(span=span).std())[1:].value_counts()

Out[1]:
True    999
dtype: int64

因此在您上面的示例中:ans == np.sqrt(mrt.ewm(span=N).var().iloc[-2])

为了研究它是如何计算 ewmvar() 的,它通过调用 emcov 来实现。使用 input_x=input_y=mrt


如果我们检查第一个元素:

mrt.ewm(span=span).var()[:2].values
> array([nan,  0.00555309])

现在,使用 emcov 例程,并将其应用到我们的具体案例中:

x0 = mrt.iloc[0]
x1 = mrt.iloc[1]
x2 = mrt.iloc[2]

# mean_x and mean_y are both the same, here we call it y
# This is the same as mrt.ewm(span=span).mean(), I verified that too
y0 = x0
# y1 = mrt.ewm(span=span).mean().iloc[1]
y1 = ((1-alpha)*y0 + x1)/(1+(1-alpha))
#y2 = (((1-alpha)**2+(1-alpha))*y1 + x2) / (1 + (1-alpha) + (1-alpha)**2) 

cov0 = 0

cov1 = (((1-alpha) * (cov0 + ((y0 - y1)**2))) +
                (1 * ((x1 - y1)**2))) / (1 + (1-alpha))

# new_wt = 1, sum_wt0 = (1-alpha), sum_wt2 = (1-alpha)**2
sum_wt = 1+(1-alpha)
sum_wt2 =1+(1-alpha)**2


numerator = sum_wt * sum_wt # (1+(1-alpha))^2 = 1 + 2(1-alpha) + (1-alpha)^2
denominator = numerator - sum_wt2 # # 2*(1-alpha)


print(np.nan,cov1*(numerator / denominator))

>(nan, 0.0055530905712123432)

关于python - pandas ewm.std 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40754262/

相关文章:

python - matplotlib 多列条形图,x 轴上有日期

python - 如何更新基于其他 Pandas 数据框的系列

database - 德尔塔湖 : How to Time Travel infinitely across Datasets?

python - Pandas 过滤不止一个 "contains"不是一个单元格而是整列

python - 基于两个不同的数组创建一个二维数组

python - 如何在 Python 中访问类成员变量?

python - 将数据框保存为 Pandas 中的 csv/文本文件,无需行号

python - 以列表形式检索 numpy 记录数组的字段格式

python - Windows 10 上的 Spark。 'Files\Spark\bin\..\jars"“\”未被识别为内部或外部命令

python-2.7 - Pandas:如何获得一个新的数据框,其中填充了 2 个或 3 个或 X 个其他数据框的并集?