[英]Trying to calculate EMA using python and i cant figure out why my code is always producing the same result
I am trying to calculate an exponential moving average of bitcoin in python2.7 but my result is always the same value and I have no idea why. 我正在尝试计算python2.7中比特币的指数移动平均值,但我的结果始终是相同的值,我不知道为什么。
def calcSMA(data,counter,timeframe):
closesum = 0
for i in range(timeframe):
closesum = float(closesum) + float(data[counter-i])
return float(closesum / timeframe)
def calcEMA(price,timeframe,prevema):
multiplier = float(2/(timeframe+1))
ema = ((float(price) - float(prevema))*multiplier) + float(prevema)
return float(ema)
counter = 0
closeprice = [7242.4,7240,7242.8,7253.8,7250.6,7255.7,7254.9,7251.4,7234.3,7237.4
,7240.7,7232,7230.2,7232.2,7236.1,7230.5,7230.5,7230.4,7236.4]
while counter < len(closeprice):
if counter == 3:
movingaverage = calcSMA(closeprice,counter,3)
print movingaverage
if counter > 3:
movingaverage = calcEMA(closeprice[counter],3,movingaverage)
print movingaverage
counter +=1
This is how to calculate the EMA: {Close - EMA(previous day)} x multiplier + EMA(previous day) you seed the formula with a simple moving average. 这是计算EMA的方法:{Close-EMA(前一天)} x乘数+ EMA(前一天)为您使用简单的移动平均数播种公式。
Doing this in Excel works so might it be my use of variables? 在Excel中做到这一点,是否可能是我对变量的使用?
I would be really glad if someone could tell me what I am doing wrong because I have failed on this simple problem for hours and can't figure it out I've tried storing my previous ema in a separate variable and I even stored all of them in a list but I am always getting the same values at every timestep. 如果有人可以告诉我我做错了什么,我将非常高兴,因为我在这个简单的问题上已经失败了几个小时,并且无法弄清楚,我已经尝试将以前的ema存储在一个单独的变量中,甚至将所有它们在列表中,但我总是在每个时间步上获得相同的值。
The expression 2/(timeframe+1)
is always zero, because the components are all integers and therefore Python 2 uses integer division. 表达式2/(timeframe+1)
始终为零,因为组件都是整数,因此Python 2使用整数除法。 Wrapping that result in float()
does no good; 包装导致float()
结果没有好处; you just get 0.0
instead of 0
. 您只得到0.0
而不是0
。
Try 2.0/(timeframe+1)
instead. 尝试改为2.0/(timeframe+1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.