使用python实现ema(指数移动平均的计算)

ema其公式为:(或直接参考百度百科
EMAtoday=α * Pricetoday + ( 1 - α ) * EMAyesterday;
其中,α为平滑指数,一般取作2/(N+1)。在计算MACD指标时,EMA计算中的N一般选取12和26天,因此α相应为2/13和2/27。
当公式不断递归,直至EMA1出现,EMA1是没有定义的。EMA1 的取值有几种不同的方法,通常情况下取EMA1为Price1,另外有的技术是将EMA1取值为开头4到5个数值的均值。
在计算机递推计算时,可以写作:
EMAtoday=α * ( Pricetoday - EMAyesterday ) + EMAyesterday;

在使用过程中Price不是一次性给出,而是通过循环,比如今天提供一个Price明天提供新的Price

调用形式最好是:ema(N,Price)

使用方式如下:
import random

i=0
while 1<30:

a=random()

此处计算a的移动平均值ema

print(ema)
 a = 2/13
Prices = [0.0] #prices of everyday
EMAs = [0.0] # ems of everyday
def ema ( N , Price) :
    Prices.append(Price)
    if N<=1:
        EMAs.append(Price)
    else :
        EMAs.append((1-a)*EMAs[N-1] + a*Price)
ema(1,1)
ema(2,3)
print (EMAs[1])
print (EMAs[2])

注意领会思想

 import random
a = 2/13
Prices = [0.0] #prices of everyday
EMAs = [0.0] # ems of everyday
def ema ( N , Price) :
    Prices.append(Price)
    if N<=1:
        EMAs.append(Price)
    else :
        EMAs.append((1-a)*EMAs[N-1] + a*Price)

for i in range(1,13) :
    price = random.randint(12,20)
    ema(i,price)
    print('Day-'+str(i)+' : price is '+str(price)+' , ems is '+ str(EMAs[i]))

import random

i=0
while 1<30:

a=random()

此处计算a的移动平均值ema

print(ema)

作为参考

 a = 2/13
Prices = [0,1,2,3,4,5,6,7,8,9,10,11,12,13] #prices
def ema ( N , Price) :
    if N<=1:
        return Price[1]
    return (1-a)*ema(N-1,Price) + a*Price[N]

print (ema(1,Prices))
print (ema(2,Prices))