python实现MACD策略背离点的判断
MACD策略python实现背离点的判断
话不多说直接贴代码和运⾏结果!!
****运⾏环境:**PyCharm2017.1
import baostock as bs
老门东import pandas as pd
import talib as ta
import matplotlib.pyplot as plt
def computeMACD(code,startdate,enddate):
login_result = bs.login(ur_id='anonymous', password='123456')
print(login_result)
###获取股票⽇K线数据###
rs = bs.query_history_k_data(code,
"date,code,clo,tradeStatus",
start_date=startdate, end_date=enddate,
frequency="d", adjustflag="3")
#### 打印结果集 ####
result_list =[]
_code =='0')& rs.next():
# 获取⼀条记录,将记录合并在⼀起
呐喊摘抄
result_list._row_data())
df = pd.DataFrame(result_list, columns=rs.fields)
#剔除停盘数据
#print(df)
df2 = df[df['tradeStatus']=='1']#交易⽇
#获取dif,dea,hist,它们的数据类似是tuple,且跟df2的date⽇期⼀⼀对应
#记住了dif,dea,hist前33个为Nan,所以推荐⽤于计算的数据量⼀般为你所求⽇期之间数据量的3倍
#这⾥计算的hist就是dif-dea,⽽很多证券商计算的MACD=hist*2=(dif-dea)*2
dif, dea, hist= ta.MACD(df2['clo'].astype(float).values, fastperiod=12, slowperiod=26, signalperiod=9)
df3 = pd.DataFrame({'dif':dif[33:],'dea':dea[33:],'hist':hist[33:]},
index=df2['date'][33:],columns=['dif','dea','hist'])
df4 = pd.merge(df3, df2, on='date', how='left')
#print(df)
print(df2)
print(df3)
print(df4)
<_csv("./out_df4.csv", index=Fal)未来小七
<_csv("./out_df2.csv", index=Fal)
hist=2*(df4['dif']-df4['dea'])
df3.plot(title='MACD')
plt.show()
#寻找MACD⾦叉和死叉
datenumber =int(df3.shape[0])
lastdif=None
lastclo =None
#tlist = []
print(df3.iloc[0,0])
for i in range(datenumber-1):早期
if(df4.iloc[i,1]<=df4.iloc[i,2])&\
(df4.iloc[i+1,1]>=df4.iloc[i+1,2])&\
马援greaterThan(lastdif, df4.iloc[i+1,1])&\
greaterThan(df4['clo'][i+1],lastclo):#上⼀次下穿时间的收盘价⼩于当⽇收盘价
lastdif = df4.iloc[i ,1]
lastclo = df4['clo'][i]
#tlist.append(df3.index[i+1])
时间改变了我们
print("期货代码:{},顶背离时间:{}, 价格:{}".format(code,df4['date'][i +1], df4['clo'][i+1]))
if((df4.iloc[i,1]>=df4.iloc[i,2])&(df4.iloc[i+1,1]<=df4.iloc[i+1,2])&greaterThan(df4.iloc[i+1,1],lastdif)&greaterThan(lastclo,df4['clo'][i+1])): lastdif = df4['dif'][i]
lastclo = df4['clo'][i]
#tlist.append(df4['date'][i+1])
print("期货代码:{},底背离时间:{}, 价格:{}".format(code, df4['date'][i +1], df4['clo'][i+1]))
bs.logout()
杨幂的身高return(dif,dea,hist)
def greaterThan(a, b):
if(not a )|(not b):
return True
elif(a > b):
return True
el:
关于中国传统文化的作文return Fal
if __name__ =='__main__':
code ='sh.600000'#浦发银⾏股票代码
startdate ='2019-06-08'
enddate ='2020-01-08'
(dif,dea,hist)= computeMACD(code,startdate,enddate)![在这⾥插⼊图⽚描述](img-blog.csdnimg/20200110140633281.png?x-oss-process=ima ge/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNDIwOTI5,size_16,color_FFFFFF,t_70)
引⽤到的包链接