话不多说直接贴代码和运行结果!!
****运行环境:**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(user_id='anonymous', password='123456')
print(login_result)
###获取股票日K线数据###
rs = bs.query_history_k_data(code,
"date,code,close,tradeStatus",
start_date=startdate, end_date=enddate,
frequency="d", adjustflag="3")
#### 打印结果集 ####
result_list = []
while (rs.error_code == '0') & rs.next():
# 获取一条记录,将记录合并在一起
result_list.append(rs.get_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['close'].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)
df4.to_csv("./out_df4.csv", index=False)
df2.to_csv("./out_df2.csv", index=False)
hist=2*(df4['dif']-df4['dea'])
df3.plot(title='MACD')
plt.show()
#寻找MACD金叉和死叉
datenumber = int(df3.shape[0])
lastdif=None
lastclose = 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['close'][i+1],lastclose):#上一次下穿时间的收盘价小于当日收盘价
lastdif = df4.iloc[i , 1]
lastclose = df4['close'][i]
#tlist.append(df3.index[i+1])
print("期货代码:{},顶背离时间:{}, 价格:{}".format(code,df4['date'][i + 1], df4['close'][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(lastclose,df4['close'][i+1])):
lastdif = df4['dif'][i]
lastclose = df4['close'][i]
#tlist.append(df4['date'][i+1])
print("期货代码:{},底背离时间:{}, 价格:{}".format(code, df4['date'][i + 1], df4['close'][i+1]))
bs.logout()
return(dif,dea,hist)
def greaterThan(a, b):
if(not a )|( not b):
return True
elif(a > b):
return True
else:
return False
if __name__ == '__main__':
code = 'sh.600000' #浦发银行股票代码
startdate = '2019-06-08'
enddate = '2020-01-08'
(dif,dea,hist) = computeMACD(code,startdate,enddate)![在这里插入图片描述](https://img-blog.csdnimg.cn/20200110140633281.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQwNDIwOTI5,size_16,color_FFFFFF,t_70)