使用Morning Star获取股票数据时遇Key Error: 'Adj Close'问题求助
Hey there! Let's work through that KeyError you're hitting when trying to access ['Adj Close'] from your Morning Star stock data. Here's a breakdown of the most likely issues and fixes:
1. Morning Star uses different column naming conventions
The biggest culprit here is that Morning Star doesn't use 'Adj Close' (that's a Yahoo Finance standard). Instead, it typically labels adjusted closing prices as 'Adjusted Close' (spelled out fully).
First, let's confirm exactly what columns are coming back from the API. Add these lines right after you fetch your data:
# Right after df = web.DataReader(...) print("Available columns in your DataFrame:", df.columns) print(df.head()) # Shows the first few rows to inspect the data structure
This will tell you the exact column names you should be using.
2. Fix the column reference
If the output shows 'Adjusted Close' as the column name, just update your code to use that instead:
# Replace this: # df['Adj Close'] # With this: df['Adjusted Close']
3. Handle multi-indexed data (common with Morning Star)
Morning Star often returns a DataFrame with a multi-index (e.g., first level is the stock symbol, second is the date). If that's the case, you'll need to flatten the index first or reference the column correctly:
# Option 1: Reset the index to make date/symbol regular columns df = df.reset_index() # Now you can access Adjusted Close directly df['Adjusted Close'] # Option 2: Access through the multi-index (replace 'AAPL' with your ticker) df['AAPL']['Adjusted Close']
4. Verify your pandas-datareader version
Outdated versions of pandas-datareader can cause API compatibility issues with data sources like Morning Star. Try upgrading to the latest version:
pip install --upgrade pandas-datareader
Here's a full corrected example to reference:
import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web style.use('ggplot') start = dt.datetime(2018, 3, 1) end = dt.datetime(2024, 3, 1) # Fetch data for a sample stock (replace with your ticker) df = web.DataReader('AAPL', 'morningstar', start, end) # Inspect and clean up the data structure print("Columns:", df.columns) df = df.reset_index() # Flatten multi-index if needed # Plot the adjusted close df['Adjusted Close'].plot(figsize=(10,6)) plt.title('Adjusted Close Price (2018-2024)') plt.ylabel('Price ($)') plt.show()
内容的提问来源于stack exchange,提问作者Ludi

