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

使用Python的yahoo_fin库调用接口时为何出现TypeError错误?

问题分析与解决

问题原因

报错TypeError: string indices must be integers说明_parse_json(income_site)返回的是字符串而非预期的字典,代码试图用字符串索引(如["incomeStatementHistory"])访问字符串,导致错误。大概率是Yahoo Finance的页面/API结构更新,当前使用的yahoo_fin版本未适配新结构,或者请求被反爬机制拦截返回了非JSON内容。

解决步骤

1. 更新yahoo_fin到最新版本

Yahoo Finance经常调整接口,旧版本库可能失效,先执行升级:

pip install --upgrade yahoo-fin

升级后重新运行代码,多数情况下能解决问题。

2. 排查解析结果(可选)

如果升级后仍报错,临时修改代码查看json_info的实际内容,确认问题:

import yahoo_fin.stock_info as si

# 先获取页面内容并解析
income_site = si.get_data("aapl", end_date=None, start_date=None, index_as_date=True, interval="1d")
json_info = si._parse_json(income_site)
print(json_info)  # 打印返回内容,看是否是有效JSON或反爬提示

如果输出是反爬相关的HTML/文本,说明需要处理请求头或改用其他库。

3. 替代方案:使用yfinance库

yahoo_fin维护频率较低,推荐使用更稳定的yfinance:

import yfinance as yf

# 获取AAPL的利润表
aapl = yf.Ticker("AAPL")
# 年度利润表
yearly_income = aapl.income_stmt
# 季度利润表
quarterly_income = aapl.quarterly_income_stmt

print(yearly_income)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 23:00:55