简体   繁体   中英

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.

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.

Doing this in Excel works so might it be my use of variables?

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.

The expression 2/(timeframe+1) is always zero, because the components are all integers and therefore Python 2 uses integer division. Wrapping that result in float() does no good; you just get 0.0 instead of 0 .

Try 2.0/(timeframe+1) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM