You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas_datareader调用get_data_yahoo报TypeError: string indices must be integers

解决TypeError: string indices must be integers错误(Yahoo Finance数据获取问题)

错误原因

Yahoo Finance的页面结构和数据接口已更新,你使用的pandas_datareader的Yahoo数据源模块未同步适配,导致解析返回内容时,原本应转换为字典的j变成了字符串,无法通过键名(如"context")索引,从而触发该错误。

解决方案

推荐使用yfinance库替代,这是目前维护活跃、专门对接Yahoo Finance的工具,兼容性更好:

  1. 安装yfinance

    pip install yfinance
    
  2. 替换原有代码

    import yfinance as yf
    
    # 定义要获取的股票代码列表
    tickers = ['AAPL', 'IBM', 'MSFT', 'GOOG']
    # 批量获取历史数据,存储为字典
    all_data = {ticker: yf.Ticker(ticker).history(period="max") for ticker in tickers}
    

    说明:history(period="max")会获取该股票的全部历史数据,和你原代码中web.get_data_yahoo(ticker)的默认行为一致;你也可以通过start和end参数指定时间范围,例如:

    all_data = {ticker: yf.Ticker(ticker).history(start="2020-01-01", end="2024-01-01") for ticker in tickers}
    

备选方案(不推荐)

如果坚持使用pandas_datareader,可以尝试安装第三方维护的适配版本,但稳定性不如yfinance:

pip install git+https://github.com/ranaroussi/pandas_datareader.git

但后续仍可能因Yahoo接口更新再次出问题,所以优先推荐yfinance。

内容的提问来源于stack exchange,提问作者JEON MINHO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 13:30:11