2013-07-30 99 views
4

我想使用熊貓來計算EWMA,但結果並不是我所期望的。我認爲第四元素應該是13.179,而熊貓則是13.121。我通過documentation中指定的公式將衰減因子(a)轉換爲質量中心。我誤解任何東西嗎?熊貓EWMA不按預期工作

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 

回答

3

由於文檔說

a = com/(1 + com) 

它遵循

com = a/(1.0-a) 

(0 < =一個< 1)。


而且,存在於在開始週期"to account for imbalance in relative weightings"計算出的值作了調整。 爲了確認式

enter image description here

讓我們關閉該調整:

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, nan, 13.109292, 12.623850, 12.150520]) 
a = 0.8408964152537145 
z = pd.ewma(x, com=a/(1.0-a), 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) 
+0

它看起來像有一個錯字。在我的鏈接提供的文檔中,它表示a = 1 /(c + 1)。謝謝。 – ezbentley

+0

這是建議的文檔修復(從一段時間回來).....如果這看起來是正確的,你可以評論一個人嗎?感謝:https://github.com/pydata/pandas/pull/4321 – Jeff

+0

@Jeff:我還沒有研究定義ewma的C代碼,所以上面的代碼可能不完全複製ewma,但它似乎表明至少在一些簡單情況下,yt = a * yt1 +(1-a)* xt'是正確的公式。我已經在[在github頁面上](https://github.com/pydata/pandas/pull/4321)留下了一條評論。 – unutbu