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

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日

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog