2015-09-07 157 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)' –