🚀 AI 一键生成 joinquant 策略代码
立即体验

joinquant 财务数据获取:get_history_fundamentals 结合 Pandas 分组分析

joinquant | 发布时间: 2026/7/29
以下内容由 EasyQuant 生成。

问题描述

请根据以下 SEO 主题生成完整页面内容:

Title: joinquant 财务数据获取:get_history_fundamentals 结合 Pandas 分组分析

Question: 如何在 joinquant 中批量获取多只股票的多期财务数据并使用 groupby 进行截面计算?

解决方案

joinquant 财务数据获取:get_history_fundamentals 结合 Pandas 分组分析

在 JoinQuant 聚宽量化交易平台中,若需要一次性获取多只股票在多个历史报告期(季度或年度)的财务报表与财务指标数据,建议使用 get_history_fundamentals API。相比传统的 get_fundamentals,该函数能够轻松按时间跨度批量拉取历史财务数据,配合 Pandas 的 groupby 功能,可高效实现标的分组与截面计算。


1. API 语法与核心参数

get_history_fundamentals(
    security,
    fields,
    watch_date=None,
    stat_date=None,
    count=1,
    interval='1q',
    stat_by_year=False
)

参数解析:

  • security: 标的代码或标的列表,例如 ['000001.XSHE', '600000.XSHG']
  • fields: 查询的财务字段列表,支持 balance(资产负债表)、cash_flow(现金流量表)、income(利润表)、indicator(财务指标表)等中的列。
  • watch_date: 观察日期。若指定,则返回在该日期前(含当日)已发布的最新报表数据(有效避免未来函数)。
  • stat_date: 统计报告期(如 '2021q1''2020')。注意:watch_datestat_date 必须二选一。
  • count: 查询历史报告期的数量。
  • interval: 报告期间隔,可选 '1q'(按季度)或 '1y'(按年度)。
  • stat_by_year: 布尔值,是否返回年度数据。若为 Trueinterval 必须为 '1y'

2. 批量获取财务数据并结合 Pandas 分组计算示例

下面的示例展示了如何获取多只股票过去 5 个季度的货币资金、存款净增加额及营业总收入,并使用 Pandas 的 groupby 计算每只股票的均值。

from jqdata import *

# 1. 定义股票池与查询字段
securities = ['000001.XSHE', '600000.XSHG', '000002.XSHE']
fields_list = [
    balance.cash_equivalents,                           # 货币资金
    cash_flow.net_deposit_increase,                    # 客户存款和同业存放款项净增加额
    income.total_operating_revenue                      # 营业总收入
]

# 2. 调用 API 获取过去 5 个季度的财务数据
df = get_history_fundamentals(
    security=securities,
    fields=fields_list,
    watch_date=None,
    stat_date='2023q1',
    count=5,
    interval='1q',
    stat_by_year=False
)

# 查看返回的 DataFrame
print("原始财务数据:")
print(df.head())

# 3. 使用 Pandas groupby 按股票代码分组并计算均值
mean_df = df.groupby('code').mean()

print("\n按股票代码分组求均值结果:")
print(mean_df)

3. 注意事项

  1. 最大返回限制:单次调用 get_history_fundamentals 最多返回 5000 条数据。若获取的股票数量过多或历史期数过长,建议分批次调用。
  2. 表限制:该 API 不支持市值表(valuation)的查询。如需市值数据,请使用 get_valuation API。
  3. 防范未来函数:推荐使用 watch_date 参数指定观察日期,获取该日期当时已披露的财报,确保回测的真实性。