[英]How would I calculate the Exponential Moving Average?
I came across a useful snippet from thread .我从thread中发现了一个有用的片段。 The post is over a decade old and there hasn't been much discussion.
这个帖子已经有十多年的历史了,没有太多的讨论。 Yet it continues to garner substantial views - it will no doubt be useful for future readers.
然而,它继续获得大量观点——它无疑对未来的读者有用。
def ema(s, n):
"""
returns an n period exponential moving average for
the time series s
s is a list ordered from oldest (index 0) to most
recent (index -1)
n is an integer
returns a numeric array of the exponential
moving average
"""
ema = []
j = 1
#get n sma first and calculate the next n period ema
sma = sum(s[:n]) / n
multiplier = 2 / float(1 + n)
ema.append(sma)
#EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
ema.append(( (s[n] - sma) * multiplier) + sma)
#now calculate the rest of the values
for i in s[n+1:]:
tmp = ( (i - ema[j]) * multiplier) + ema[j]
j = j + 1
ema.append(tmp)
return ema
The issue is EMA values are actually SMA figures being appended.问题是 EMA 值实际上是附加的 SMA 数字。 How should we proceed to fix the function?
我们应该如何着手修复 function?
Use a temporary array for ema
calculations and and different one for returning,使用一个临时数组进行
ema
计算,并使用不同的数组返回,
def ema(s, n):
"""
returns an n period exponential moving average for
the time series s
s is a list ordered from oldest (index 0) to most
recent (index -1)
n is an integer
returns a numeric array of the exponential
moving average
"""
ema1 = []
ema2 = []
j = 1
#get n sma first and calculate the next n period ema
sma = sum(s[:n]) / n
multiplier = 2 / float(1 + n)
ema1.append(sma)
#EMA(current) = ( (Price(current) - EMA(prev) ) x Multiplier) + EMA(prev)
ema1.append(( (s[n] - sma) * multiplier) + sma)
ema2.append(( (s[n] - sma) * multiplier) + sma)
#now calculate the rest of the values
for i in s[n+1:]:
tmp = ( (i - ema1[j]) * multiplier) + ema1[j]
j = j + 1
ema1.append(tmp)
ema2.append(tmp)
return ema2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.