2015-09-07 197 views
1

我正在瀏覽本網站以瞭解有關指數平滑平均值的更多信息,但不確定關於代碼的1部分。指數平滑平均值

import pandas, numpy as np 
ewma = pandas.stats.moments.ewma 

# make a hat function, and add noise 
x = np.linspace(0,1,100) 
x = np.hstack((x,x[::-1])) 
x += np.random.normal(loc=0, scale=0.1, size=200) 
plot(x, alpha=0.4, label='Raw') 

# take EWMA in both directions with a smaller span term 
fwd = ewma(x, span=15) # take EWMA in fwd direction 
bwd = ewma(x[::-1], span=15) # take EWMA in bwd direction 
c = np.vstack((fwd, bwd[::-1])) # lump fwd and bwd together 
c = np.mean(c, axis=0) # average 

# regular EWMA, with bias against trend 
plot(ewma(x, span=20), 'b', label='EWMA, span=20') 

# "corrected" (?) EWMA 
plot(c, 'r', label='Reversed-Recombined') 

我不明白的是本節

# take EWMA in both directions with a smaller span term 
fwd = ewma(x, span=15) # take EWMA in fwd direction 
bwd = ewma(x[::-1], span=15) # take EWMA in bwd direction 
c = np.vstack((fwd, bwd[::-1])) # lump fwd and bwd together 
c = np.mean(c, axis=0) # average 

可能有人請您解釋一下這到底是怎麼回事呢?

該網站的完整的源代碼是:http://connor-johnson.com/2014/02/01/smoothing-with-exponentially-weighted-moving-averages/

回答

1

我想這裏的主要問題是什麼bwd[::-1]手段?查看添加的其他評論。

# take EWMA in both directions with a smaller span term 

fwd = ewma(x, span=15) # take EWMA in fwd direction 
## This part should not be a problem, right? 

bwd = ewma(x[::-1], span=15) # take EWMA in bwd direction 
## x[::-1] means to go thr x, from end to beginning(!), with a step of -1 
## (hence it is going from the back to the front) 

c = np.vstack((fwd, bwd[::-1])) # lump fwd and bwd together 
c = np.mean(c, axis=0) # average 
## Then we reverse ewma into a beginning-to-end order 
## and take the average of fwd and bwd 
## IMO, better written just as: 

#c = 0.5*(fwd + bwd[::-1]) 

這個想法是,在前向EWMA中,當前值受早期值影響,但越來越少。另一方面,後向EWMA受後面的值影響。最後,通過取前向和後向EWMA的平均值,可以創建一些受周圍值影響的東西(如果我們稱之爲),但越來越少,因爲當您離開當前位置時。

+0

謝謝!是的,我遇到了'bwd [:: - 1]'的問題'但是很好的解釋! –

+0

我還有一個問題。如果我想複製這個,我的下面的代碼fwd和bwd是否正確? 'fwd = pd.ewma(df ['Close'],span = 20) bwd = pd.ewma(df ['Close'] [:: - 1],span = 20)' –