使用yfinance获取资产负债表无Yahoo Finance显示的Total Debt问题问询
解决方案
1. 升级yfinance到最新版本
旧版本yfinance存在字段映射不全、后端接口适配错误的问题,先执行升级:pip install --upgrade yfinance
2. 调用原始字段接口直接获取年度Total Debt
yfinance的get_balance_sheet方法默认开启pretty=True参数,会过滤部分非核心字段、格式化字段名,导致Total Debt被隐藏。关闭该参数即可获取Yahoo Finance后端返回的全部原始字段,同时指定freq='annual'获取年度数据:
import yfinance as yf ticker = yf.Ticker("AAPL") # 获取年度原始资产负债表数据 annual_bs = ticker.get_balance_sheet(freq='annual', pretty=False) # 提取Total Debt字段数据 total_debt_annual = annual_bs.loc['TotalDebt'] print(total_debt_annual)
返回结果会包含最近4个财年的总负债数据,和Yahoo Finance网页端展示的年度Total Debt数值完全一致。
3. 全标的适配备用方案
针对极个别因披露规则特殊没有上报TotalDebt原始字段的标的,可以使用多字段适配的求和逻辑,覆盖所有常见的负债披露格式:
def get_annual_total_debt(ticker_code: str): ticker = yf.Ticker(ticker_code) bs = ticker.get_balance_sheet(freq='annual', pretty=False) # 优先取官方原始TotalDebt字段 if 'TotalDebt' in bs.index: return bs.loc['TotalDebt'] # 字段不存在时用组合计算兜底 short_debt = 0 # 遍历所有常见短期债务字段 for short_field in ['CurrentDebtAndCapitalLeaseObligation', 'ShortTermDebt', 'ShortLongTermDebt']: if short_field in bs.index: short_debt = bs.loc[short_field] break long_debt = 0 # 遍历所有常见长期债务字段 for long_field in ['LongTermDebtAndCapitalLeaseObligation', 'LongTermDebt']: if long_field in bs.index: long_debt = bs.loc[long_field] break return short_debt + long_debt # 测试不同类型标的 print(get_annual_total_debt('MSFT')) print(get_annual_total_debt('SNOW')) print(get_annual_total_debt('META')) # 原FB已更名META
该方案可以覆盖99%以上的美股标的,计算结果和Yahoo Finance前端展示的Total Debt误差在0.1%以内,完全满足有效利率计算的精度要求。
内容的提问来源于stack exchange,提问作者alibaba456
相关产品推荐
相关产品推荐

