如何解决Python中的'KeyError

0 投票
2 回答
61 浏览
提问于 2025-04-13 15:34

我正在开发一个程序,目的是寻找相对强弱指数(RSI)的背离。可是当我运行这个程序时,它会崩溃。当时间间隔设置为60分钟时,程序可以正常工作。但一旦我把时间改成15分钟,程序就会出错。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
import ta

ticker=yf.Ticker("ADA-USD")

data=ticker.history(period="10d",interval='15m')
data.rename(columns={"Close":"close","High":"high","Low":"low","Open":"open"},inplace=True)
data.index=range(1,len(data)+1)

rsi_peroid=14
data["rsi"+str(rsi_peroid)]=ta.momentum.RSIIndicator(data["close"],rsi_peroid).rsi()
data.dropna(inplace=True)

divergence_point=[]
rsi_val=data["rsi14"]
loop=10
for i in range(loop,len(data)-1):
    recent_rsi=rsi_val[i-loop:i]
    recent_price=data["close"].iloc[i-loop:i]
    if (data["close"].iloc[i] < min(recent_price) and rsi_val[i] >= min((recent_rsi)+2) or data["close"].iloc[i] > max(recent_price) and rsi_val[i]<= max(recent_rsi)-2):
        divergence_point.append(i)
        
data["Divergence"]=False

data.loc[divergence_point,"Divergence"]=True

当我运行程序时,它出现了一个错误:

KeyError                                  Traceback (most recent call last)
File C:\ProgramData\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3653, in Index.get_loc(self, key)
   3652 try:
-> 3653     return self._engine.get_loc(casted_key)
   3654 except KeyError as err:

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\_libs\index.pyx:147, in pandas._libs.index.IndexEngine.get_loc()

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\_libs\index.pyx:176, in pandas._libs.index.IndexEngine.get_loc()

File pandas\_libs\hashtable_class_helper.pxi:2606, in pandas._libs.hashtable.Int64HashTable.get_item()

File pandas\_libs\hashtable_class_helper.pxi:2630, in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 11

The above exception was the direct cause of the following exception:

KeyError                                  Traceback (most recent call last)
Cell In[264], line 7
      5     recent_rsi=rsi_val[i-loop:i]
      6     recent_price=data["close"].iloc[i-loop:i]
----> 7     if (data["close"].iloc[i] < min(recent_price) and rsi_val[i] >= min((recent_rsi)+2) or data["close"].iloc[i] > max(recent_price) and rsi_val[i]<= max(recent_rsi)-2):
      8         divergence_point.append(i)
     10 data["Divergence"]=False

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\core\series.py:1007, in Series.__getitem__(self, key)
   1004     return self._values[key]
   1006 elif key_is_scalar:
-> 1007     return self._get_value(key)
   1009 if is_hashable(key):
   1010     # Otherwise index.get_value will raise InvalidIndexError
   1011     try:
   1012         # For labels that don't resolve as scalars like tuples and frozensets

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\core\series.py:1116, in Series._get_value(self, label, takeable)
   1113     return self._values[label]
   1115 # Similar to Index.get_value, but we do not fall back to positional
-> 1116 loc = self.index.get_loc(label)
   1118 if is_integer(loc):
   1119     return self._values[loc]

File C:\ProgramData\anaconda3\Lib\site-packages\pandas\core\indexes\base.py:3655, in Index.get_loc(self, key)
   3653     return self._engine.get_loc(casted_key)
   3654 except KeyError as err:
-> 3655     raise KeyError(key) from err
   3656 except TypeError:
   3657     # If we have a listlike key, _check_indexing_error will raise
   3658     #  InvalidIndexError. Otherwise we fall through and re-raise
   3659     #  the TypeError.
   3660     self._check_indexing_error(key)

KeyError: 11

当时间间隔是60分钟时,程序可以正常运行。但当我把时间改为15分钟时,程序就会出错。

2 个回答

0
hsh = {"123": "Res"}
key = "123"
if key in hsh:
  print(hsh[key])
if "close" in data:
      # You code

在你的情况下,你应该检查一下 data["close"]。

1

你正在尝试访问一个不存在的索引(11),这个索引在

pd.Series

(也就是rsi_val)里找不到。
你的循环从i=10开始,每次循环i都会加1。但是rsi_val[11]找不到,因为你用data.dropna(inplace=True)去掉了空值,导致序列的索引是从14开始的。
我猜在第一次循环(i=10)的时候并没有出错,因为data["close"].iloc[i] < min(recent_price)这个条件的结果是False,所以第二个比较就被跳过了。

撰写回答