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

使用Yfinance遍历股票代码列表获取多类财务数据时Pandas报错求助

修复后可运行代码

import pandas as pd
import numpy as np
import yfinance as yf

tickers = ['AAPL', 'GOOGL', 'META'] # 注意FB已在2022年更名为META,若需查询原FB数据请使用META代码
# 存储所有标的的全量财务数据
data = []
for t in tickers:
    # 每个标的仅调用1次info接口,避免重复请求触发限流
    ticker_info = yf.Ticker(t).info
    ebitda = ticker_info.get('ebitda', np.nan)
    enterprise_value = ticker_info.get('enterpriseValue', np.nan)
    total_assets = ticker_info.get('totalAssets', np.nan)
    data.append([t, ebitda, enterprise_value, total_assets])

pd.set_option("display.max_rows", None)
# 按预期结构生成DataFrame
df = pd.DataFrame(data, columns=['Ticker', 'Ebitda', 'EnterpriseValue', 'TotalAssets'])
# 若需要将Ticker设为行索引,可取消注释下一行
# df = df.set_index('Ticker')
print(df)

修改说明

  • 新增data列表存储所有标的的完整字段数据,解决原循环中重复覆盖a/b/c变量,导致最终仅保留最后一个标的数据的问题
  • 修正了pd.DataFrame的传参格式:传入符合要求的二维列表作为数据源,匹配对应列名,符合Pandas初始化规则
  • 优化了接口调用逻辑,每个标的仅请求一次接口,降低限流风险

可选简洁写法(列表推导式)

import pandas as pd
import yfinance as yf

tickers = ['AAPL', 'GOOGL', 'META']
fields = ['ebitda', 'enterpriseValue', 'totalAssets']
col_names = ['Ticker', 'Ebitda', 'EnterpriseValue', 'TotalAssets']

data = [[t] + [yf.Ticker(t).info.get(f, pd.NA) for f in fields] for t in tickers]
df = pd.DataFrame(data, columns=col_names)
print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:24:03