MACD部分 转载自云金杞:https://blog.csdn.net/qq_26948675/article/details/72636590
数据获取于聚宽平台
import pandas as pd
df=get_price('000001.XSHG',end_date='2019-02-15',count=300)
#df.head()
def get_EMA(df,N):
for i in range(len(df)):
if i==0:
df.ix[i,'ema']=df.ix[i,'close']
if i>0:
df.ix[i,'ema']=(2*df.ix[i,'close']+(N-1)*df.ix[i-1,'ema'])/(N+1)
ema=list(df['ema'])
return ema
def get_MACD(df,short=12,long=26,M=9):
a=get_EMA(df,short)
b=get_EMA(df,long)
df['diff']=np.array(a)-np.array(b)
for i in range(len(df)):
if i==0:
df.ix[i,'dea']=df.ix[i,'diff']
if i>0:
df.ix[i,'dea']=(2*df.ix[i,'diff']+(M-1)*df.ix[i-1,'dea'])/(M+1)
df['macd']=2*(df['diff']-df['dea'])
return df
#获取 dif 、def线和 MACD
get_MACD(df,12,26,9)
def ma(n,data):
ma=[]
for i in range(len(data)-2-n):
ma.append(np.mean(data[i:i+n]))
ma=[np.nan]*(len(data)-len(ma))+ma
print(ma)
return ma
#获取ma5 和 ma10
df['ma5']=ma(5,df['close'])
df['ma10']=ma(10,df['close'])
df