使用pandas_datareader获取Yahoo数据时遇TypeError错误求助
解决pandas web.DataReader获取Yahoo BTC-USD数据的TypeError问题
问题根源在于Yahoo财经API接口结构已变更,导致web.DataReader内置的Yahoo数据源解析逻辑失效,返回内容为字符串而非预期的JSON格式,因此触发string indices must be integers错误。以下是具体解决办法:
推荐方案:改用yfinance库
yfinance是专门适配Yahoo财经数据的第三方库,维护及时、兼容性强,可完全替代web.DataReader的Yahoo数据源功能:
- 安装yfinance:
pip install yfinance --upgrade - 示例代码:
import yfinance as yf # 获取BTC-USD历史数据,可自定义起止日期 btc_data = yf.download("BTC-USD", start="2023-01-01", end="2023-12-31") # 查看数据结构 print(btc_data.head())
返回的btc_data是标准pandas DataFrame,与web.DataReader返回格式一致,无需额外处理。
临时方案:修复web.DataReader的Yahoo解析逻辑(不推荐)
若坚持使用web.DataReader,可手动修改其源码适配新接口,但该方法不稳定(Yahoo可能再次变更接口,且版本更新会覆盖修改):
- 找到pandas_datareader的Yahoo模块文件,路径通常为
Lib/site-packages/pandas_datareader/yahoo/daily.py - 修改
_get_crumb_and_cookie和_read_one_data方法,确保响应内容正确解析为JSON格式
备选方案:使用CoinGecko API
若Yahoo相关方案均失效,可改用CoinGecko的免费API获取加密货币数据:
import requests import pandas as pd # 调用CoinGecko API获取BTC历史价格 url = "https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range" params = { "vs_currency": "usd", "from": 1672531200, # 对应2023-01-01的时间戳 "to": 1703980800 # 对应2023-12-31的时间戳 } response = requests.get(url, params=params) raw_data = response.json() # 转换为DataFrame格式 btc_data = pd.DataFrame(raw_data['prices'], columns=['时间戳', '价格']) btc_data['时间戳'] = pd.to_datetime(btc_data['时间戳'], unit='ms') btc_data.set_index('时间戳', inplace=True) print(btc_data.head())
内容的提问来源于stack exchange,提问作者Vondoe79
相关产品推荐
相关产品推荐

