Pandas index.get_loc处理时间序列数据时抛出KeyError问题求助
index.get_loc() After Switching to nsepy Let's break down why you're hitting this KeyError and how to fix it. The issue almost always boils down to date mismatches, incorrect column/index names, or missing trading days when switching from the IEX API to nsepy.
First, Let's Correct Your nsepy Code (Common Pitfalls)
nsepy uses different column names and requires explicit start/end dates compared to the IEX API. Here's a cleaned-up version of your code aligned with nsepy's output structure:
import pandas as pd import matplotlib.pyplot as plt from IPython import get_ipython from nsepy import get_history from datetime import datetime get_ipython().run_line_magic('matplotlib', 'inline') # Note: SPY is a US ETF—nsepy is for Indian NSE stocks. Use a valid NSE symbol like 'RELIANCE' or 'TCS' sym = 'RELIANCE' # Define date range for 5 years of historical data start_date = datetime(2019, 1, 1) end_date = datetime(2024, 1, 1) # Fetch data using nsepy df_temp = get_history(symbol=sym, start=start_date, end=end_date) # nsepy uses 'Date' (uppercase) for the date column, not the lowercase 'date' from IEX df_temp.set_index('Date', inplace=True) # nsepy uses 'Close' (uppercase) for closing price, not the lowercase 'close' from IEX df_close = df_temp['Close']
Why the KeyError Happens (and Fixes)
1. Target Date Is Outside Your Data Range
If your start_date is later than 2015-08-17, that date won't exist in your index. First, verify your data's date bounds:
print(f"Earliest date in dataset: {df_close.index.min()}") print(f"Latest date in dataset: {df_close.index.max()}")
Fix: Adjust your start_date to be before 2015-08-17, e.g., start_date = datetime(2015, 1, 1).
2. Date Format Mismatch (String vs. Datetime)
nsepy returns a datetime64[ns] index, while you're passing a string date. While pandas usually handles this conversion automatically, explicit conversion avoids edge cases:
target_date = pd.Timestamp('2015-08-17') loc = df_close.index.get_loc(target_date)
3. The Date Is a Non-Trading Day (NSE Holiday/Weekend)
Indian stock exchanges have unique holidays and weekend schedules. 2015-08-17 might be a non-trading day for NSE, so no data exists for that date.
Fix: Use the method parameter in get_loc to fetch the nearest valid trading day:
# Get the closest previous trading day (forward fill) loc = df_close.index.get_loc(target_date, method='ffill') # Or get the closest next trading day (backward fill) loc = df_close.index.get_loc(target_date, method='bfill')
4. Wrong Column/Index Names
nsepy uses uppercase column names (Date, Close) unlike the lowercase ones from the IEX API. If you forgot to update these references, df_close might be empty or have an invalid index. Double-check with print(df_temp.columns) to confirm column names.
Quick Debugging Tip
If you're still stuck, print a sample of your index to verify which dates are present:
print(df_close.index[:10]) # Show the first 10 dates in your dataset
内容的提问来源于stack exchange,提问作者Arun Kamath

