加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 熊猫EWMA没有按预期工作

发布时间:2020-12-20 13:36:14 所属栏目:Python 来源:网络整理
导读:我正在尝试使用熊猫计算EWMA,但结果并不是我的预期.我认为第4个元素应该是13.179但是熊猫给出13.121.我通过 documentation中指定的公式将衰减因子(a)转换为质心.我是否误解了什么? In[222]: yOut[222]: 0 NaN1 NaN2 13.1921613 13.1092924 12.6238505 12.15
我正在尝试使用熊猫计算EWMA,但结果并不是我的预期.我认为第4个元素应该是13.179但是熊猫给出13.121.我通过 documentation中指定的公式将衰减因子(a)转换为质心.我是否误解了什么?

In[222]: y
Out[222]: 
0          NaN
1          NaN
2    13.192161
3    13.109292
4    12.623850
5    12.150520
Name: data,dtype: float64

In[223]: pd.ewma(y,com = 1.0 / a - 1)
Out[223]: 
0          NaN
1          NaN
2    13.192161
3    13.120667
4    12.701206
5    12.237839
dtype: float64

In[224]: a
Out[224]: 0.8408964152537145

In[225]: a * 13.192161 + (1 - a) * 13.109292
Out[225]: 13.17897624503566

解决方法

自从文档说

a = com/(1 + com)

它遵循

com = a/(1.0-a)

(对于0 <= a <1). 此外,还对在开始时段“to account for imbalance in relative weightings”期间计算的值进行了调整.
确认公式

让我们关闭那个调整:

z = pd.ewma(x,com=a/(1.0-a),adjust=False)
print(z)

然后打印

0         NaN
1         NaN
2    2.098920
3    3.850710
4    5.246548
5    6.344995

这个结果可以通过计算来模仿

import pandas as pd
import numpy as np
import numpy.testing.utils as NTU

nan = np.nan
x = pd.Series([nan,nan,13.109292,12.623850,12.150520])
a = 0.8408964152537145
z = pd.ewma(x,adjust=False)

def nanzero(x):
    return 0 if np.isnan(x) else x

x.ffill(inplace=True)
y = [x[0]]
for xt in x[1:]:
    yt1 = y[-1]
    if np.isnan(yt1) and np.isnan(xt):
        yt = nan
    else:
        yt1 = nanzero(yt1)
        xt = nanzero(xt)
        yt = a*yt1 + (1-a)*xt
        # yt = (1-a)*yt1 + a*xt
    y.append(yt)
y = pd.Series(y)

NTU.assert_allclose(y,z)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读