def cal_MACD(df,short=12,lon=26,dea=9):
df["EMA_short"]=df['real_price'].ewm(span=short,adjust=False).mean()
df["EMA_long"]=df['real_price'].ewm(span=lon,adjust=False).mean()
df['DIF']=df["EMA_short"]-df["EMA_long"]
df['DEA']= df['DIF'].ewm(span=dea,adjust=False).mean()
df['MACD']=(df['DIF']-df['DEA'])*2
del df["EMA_short"],df["EMA_long"]
return df
sdate="1900-01-15"
edate="2021-11-23"
#日线数据
df1 = DataSource("bar1d_CN_STOCK_A").read(start_date=sdate, end_date=edate,fields=["date","instrument","close","adjust_factor","turn","amount"])
df1["real_price"]=df1["close"]/df1["adjust_factor"]
df2=df1[df1.instrument=="000002.SZA"]
#print(df2)
df3=df2.reset_index(drop = True)
#print(df3)
df=cal_MACD(df3,short=12,lon=26,dea=9)
#print(df)
#print(df.items)
#寻找MACD金叉和死叉
datenumber = int(df.shape[0])
print(datenumber)
for i in range(datenumber-1):
if (df.loc[i,"DIF"]<=df.loc[i,"DEA"] and df.loc[i+1,"DIF"]>=df.loc[i+1,"DEA"] and df.loc[i+1,"DEA"]!=0 and df.loc[i+1,"DIF"]!=0 ):
#print("MACD金叉的日期:"+str(df.index[i+1]))
df.loc[i,"SIGNAL"]=1
if ((df.loc[i,"DIF"]>=df.loc[i,"DEA"]) and (df.loc[i+1,"DIF"]<=df.loc[i+1,"DEA"]) and df.loc[i+1,"DEA"]!=0 and df.loc[i+1,"DIF"]!=0):
#print("MACD死叉的日期:"+str(df.index[i+1]))
df.loc[i,"SIGNAL"]=0
print(df)