如何将yahoofinancials输出的多维字典转换为Pandas DataFrame
多维财报字典转目标DataFrame实现方法
yahoofinancials返回的财报结果为三层嵌套结构:外层key为incomeStatementHistoryQuarterly,第二层key为查询的股票代码,第三层是多期财报组成的列表,每一期财报为单key字典,key为报告期日期,value为当期所有财务指标的键值对,按照以下代码即可完成转换:
import pandas as pd from yahoofinancials import YahooFinancials ticker = 'RELIANCE.NS' yahoo_financials = YahooFinancials(ticker) income_statement_data_qt = yahoo_financials.get_financial_stmts('quarterly', 'income') # 提取对应股票的季度财报列表 stmt_list = income_statement_data_qt['incomeStatementHistoryQuarterly'][ticker] # 整理财报结构 formatted_list = [] for period_stmt in stmt_list: # 取出当期报告日期和对应指标字典 report_date, indicator_dict = next(iter(period_stmt.items())) # 合并日期到指标字典中 indicator_dict['report_date'] = report_date formatted_list.append(indicator_dict) # 转换为DataFrame并调整为目标格式 df = pd.DataFrame(formatted_list) # 转置后第一列为财务指标,其余列为各报告期数值,匹配需求格式 df = df.set_index('report_date').T.reset_index(names='financial_indicator')
补充说明
- 运行上述代码得到的
df就是你期望的输出格式,第一列为财务指标名称,后续每列对应一个季度的指标值 - 如果需要批量处理多只股票,只需在外层新增股票代码遍历逻辑,在
indicator_dict中新增ticker字段存储对应股票代码即可
内容的提问来源于stack exchange,提问作者g_sanghavi
相关产品推荐
相关产品推荐

