问题如下:
三均线策略是一个非常经典的趋势追踪策略。它的具体表述如下,快速均线往上穿过中速均线时就买进,而当快速均线往下穿过慢速均线时就卖出。假设我们使用3日均线作为快速均线,6日均线作为中速均线,9日均线作为慢速均线。请自选一支股票,找出2019年1月1日至今所有的买入日期和卖出日期。
我使用的代码如下:
def BuySold(stockID,startDate,endDate) -> list:
'''
参考资料:https://blog.csdn.net/weixin_30553837/article/details/102140580
'''
hist_data=ts.get_hist_data(stockID,start=startDate,end=endDate)
hist_data.index=pd.to_datetime(hist_data.index)
hist_data=hist_data.rename(columns={"open":"Open", "close":"Close","high":"High","low":"Low","volume":"Volume"}).sort_index()
pd.set_option('display.max_columns',None)
pd.set_option('display.max_rows',None)
avthree=hist_data.rolling(3).mean()
avsix=hist_data.rolling(6).mean()
avnine=hist_data.rolling(9).mean()
result=pd.merge(avthree['Close'],avsix['Close'],on='date')
result=pd.merge(result,avnine['Close'],on='date')
result.colums=['Close_3','Close_6','Close_9']
result3diff6=result.sub(result['Close_6'],axis=0),round(3)
result3diff9=result.sub(result['Close_9'],axis=0),round(3)
result3diff6['Close_3diff6_yesterday']=result3diff6['Close_3'].shift(1)
result3diff9['Close_3diff9_yesterday']=result3diff9['Close_3'].shift(1)
result3diff6.columns=['Close_3diff6','Close_6diff6','Close_9diff6','Close_3diff6_yesterday']
result3diff9.columns=['Close_3diff9','Close_6diff9','Close_9diff9','Close_3diff9_yesterday']
buy=result3diff6[(result3diff6.Close_3diff6_yesterday0)]
sold=result3diff9[(result3diff9.Close_3diff9_yesterday>0)&(result3diff9.Close_3diff9<0)]
print("First, the date of purchase [",stockID,"] is as follows:")
print(buy.index)
print("Second, the date of sold [",stockID,"] is as follows:")
print(sold.index)
BuySold(stockID="600021",startDate="2019-01-01",endDate="2020-06-21")
结果运行之后报错显示KeyError: 'Close_6'但代码那边显示又正常我找不出错来,如果可以希望有大佬能指点我一下
https://blog.csdn.net/xingbuxing_py/article/details/78536041