iseenoevil 2021-11-11 18:54 采纳率: 100%
浏览 564
已结题

python问题:KeyError: Timestamp('2007-03-01 00:00:00')

一.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')

  • 写回答

1条回答 默认 最新

  • CSDN专家-黄老师 2021-11-11 18:59
    关注

    python中keyerror指的是你在使用字典里不存在的key产生的错误,能够使用字典的dict.get方法来解决,该方法主要是实现让取不到对应key的value返回默认值,从而避免出错。
    你可以输出你的数据看看有哪些key

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月27日
  • 已采纳回答 11月19日
  • 创建了问题 11月11日

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法