Jupyter中使用Morningstar获取股票收盘价遇NaN问题求助
Hey there! Let's figure out why only your first stock is pulling valid data while the rest return NaNs when using Morningstar in Jupyter. Here are the most likely issues and fixes:
1. Batch Request Limitations with Morningstar
Many financial data sources (including Morningstar) don't handle multiple ticker symbols well in a single request. The API might only process the first ticker and ignore the rest, leading to NaNs for subsequent stocks.
Fix: Fetch data for each ticker individually in a loop, then combine the results:
import pandas as pd import pandas_datareader.data as data # Your list of tickers tickers = ["AAPL", "MSFT", "AMZN"] start = "2023-01-01" end = "2023-12-31" # Initialize an empty DataFrame to store all closing prices closing_prices = pd.DataFrame() for ticker in tickers: try: # Pull data for one ticker at a time stock_data = data.DataReader(ticker, "morningstar", start, end) # Extract the Close column and rename it to the ticker ticker_close = stock_data["Close"].rename(ticker) # Merge with the main DataFrame closing_prices = pd.concat([closing_prices, ticker_close], axis=1) except Exception as e: print(f"Failed to fetch data for {ticker}: {str(e)}") # Check the results print(closing_prices.head())
2. Incorrect Ticker Format for Morningstar
Morningstar requires specific ticker formats (sometimes including exchange suffixes) depending on the stock's listing exchange. If your first ticker uses the right format but others don't, the API can't find matching data and returns NaNs.
Fix:
- Verify each ticker's correct format on the Morningstar website (search for the stock and copy the exact ticker used there).
- For example, some international stocks might need suffixes like
.NYSEor.NASDAQ, while others use the plain ticker.
3. Outdated pandas-datareader Version
Older versions of pandas-datareader can have compatibility issues with the Morningstar API, leading to inconsistent data pulls.
Fix: Upgrade to the latest version using this command in your terminal or Jupyter cell:
pip install --upgrade pandas-datareader
4. Date Range Mismatches
If some of your stocks were not trading during the specified date range (e.g., newly listed stocks), their data will show as NaNs.
Fix:
- Double-check the listing date of each stock to ensure your
startdate falls after the stock began trading. - Adjust your date range to include valid trading periods for all tickers.
After trying these steps, you should see valid closing prices for all your stocks instead of NaNs!
内容的提问来源于stack exchange,提问作者OmieiOS

