使用FinanceDataReader开发Telegram告警机器人时遇IndexingError求助
解决IndexingError及相关日期匹配问题
核心错误原因
df['Close']是单级索引的Series(shape为(19,)),但你用.loc[code, prev_date]传入了两个索引参数,违反单级索引调用规则,直接触发Too many indexers错误。结合场景看,KR11是指数数据,数据中不存在code字段,完全不需要传入code作为索引。
分步修复方案
1. 修正索引调用逻辑
直接去掉多余的code参数,改为针对日期索引的单参数调用,先确保DataFrame用日期作为索引:
# 读取KR11数据后,将Date设为索引(如果之前重置过索引,重新设置) df = df.reset_index().set_index('Date') # 后续直接通过日期索引获取收盘价 prev_price = df['Close'].loc[prev_date]
2. 统一日期格式
你的prev_date/now_date带时分秒(2022-08-01 00:00:00),但DataFrame的日期是纯日期格式(2022-08-12),格式不匹配会导致无法找到对应数据。统一转成date类型:
# 把DataFrame的索引转成date类型(去掉时分秒) df.index = df.index.date # 把你的日期变量也转成date类型 prev_date = prev_date.date() now_date = now_date.date()
3. 处理date_list中不存在的日期
提前检查日期是否在数据索引中,避免KeyError:
if prev_date in df.index: prev_price = df['Close'].loc[prev_date] else: # 可选方案1:跳过该日期 print(f"警告:日期 {prev_date} 不在KR11数据中,跳过") # 可选方案2:取该日期之前最近的有效数据 closest_date = df.index[df.index <= prev_date].max() prev_price = df['Close'].loc[closest_date] print(f"使用最近有效日期 {closest_date} 的价格")
完整修改示例
import FinanceDataReader as fdr import pandas as pd # 读取KR11数据 df = fdr.DataReader('KR11', '2022-07-01', '2022-08-12') # 设置日期为索引并统一格式 df = df.reset_index().set_index('Date') df.index = df.index.date # 计算均线 df['MA3'] = df['Close'].rolling(window=3).mean() df['MA5'] = df['Close'].rolling(window=5).mean() df['MA10'] = df['Close'].rolling(window=10).mean() # 假设你的日期变量是带时分秒的datetime对象 prev_date = pd.to_datetime('2022-08-01 00:00:00').date() now_date = pd.to_datetime('2022-08-12 00:00:00').date() # 安全获取价格 if prev_date in df.index: prev_price = df['Close'].loc[prev_date] now_price = df['Close'].loc[now_date] # 后续计算均线突破逻辑 # ... else: print(f"日期 {prev_date} 无效,跳过本轮检测")
内容的提问来源于stack exchange,提问作者Joshua Chung
相关产品推荐
相关产品推荐

