一.python代码
#利用股票的金叉和死叉时间点进行买入卖出交易操作的代码
import datetime
import numpy as np
import pandas as pd
import tushare as ts
import matplotlib.pyplot as plt
#获取数据
pro=ts.pro_api()
df=pro.daily(ts_code='601318.SH')
df.to_csv('601318.csv')
df=pd.read_csv('601318.csv',index_col='trade_date',parse_dates=['trade_date'])[['open','close','high','low']].sort_values('trade_date',ascending=True)
#画均线方法二
df['ma5']=df['close'].rolling(5).mean()
df['ma30']=df['close'].rolling(30).mean()
#分析输出所有金叉死叉日期
golden_cross=[]
for i in range(1,len(df)):
if df['ma5'][i]>df['ma30'][i] and df['ma5'][i-1]<df['ma30'][i-1]:
golden_cross.append(df.index[i])
death_cross=[]
for i in range(1,len(df)):
if df['ma5'][i]<df['ma30'][i] and df['ma5'][i-1]>df['ma30'][i-1]:
death_cross.append(df.index[i])
print('golden_cross',golden_cross)
print('death_cross',death_cross)
#计算股票收益
df=df.dropna()
df=df['2010-01-01':]
money=100000
hold=0
sr1=pd.Series(1,index=golden_cross)
sr2=pd.Series(0,index=death_cross)
sr=sr1.append(sr2).sort_index()
for i in range(0,len(sr)):
a=sr.index[i]
p=df['open'][a]
if sr.iloc[i]==1:
integer=money//(100*p)
hold+=integer*100
money-=hold*p
else:
money+=hold*p
print(money)
二.问题描述
报错结果
Traceback (most recent call last):
File "pandas_libs\index.pyx", line 460, in pandas._libs.index.DatetimeEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 2131, in pandas._libs.hashtable.Int64HashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 2140, in pandas._libs.hashtable.Int64HashTable.get_item
KeyError: 1180915200000000000
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\10333\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas_libs\index.pyx", line 429, in pandas._libs.index.DatetimeEngine.get_loc
File "pandas_libs\index.pyx", line 462, in pandas._libs.index.DatetimeEngine.get_loc
KeyError: Timestamp('2007-06-04 00:00:00')