3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 JoinQuant (聚宽) 平台的 jqfactor 框架中,编写自定义因子类(继承自 Factor)时,可以通过设置 dependencies 属性来声明因子计算所依赖的基础财务指标。
在 Factor 类中,直接使用财务指标名称代表当前可看到的最新单季度数据。若需要获取历史季度或年度的财务数据,可在指标名称后添加后缀:
前 N 季度的单季度财务数据:
operating_revenue: 当前最新单季度营业收入(如 2023Q3)operating_revenue_1: 上一单季度营业收入(如 2023Q2)operating_revenue_2: 上上单季度营业收入(如 2023Q1)operating_revenue_3: 前第 3 个单季度营业收入(如 2022Q4)过去 N 年的年度财务数据:
operating_revenue_y: 当前最新年度营业收入operating_revenue_y1: 前 1 年的年度营业收入operating_revenue_y2: 前 2 年的年度营业收入以计算**营业收入 TTM(滚动12个月营业收入)**为例,TTM 需要将最近 4 个单季度的营业收入相加:
from jqfactor import Factor, calc_factors
import pandas as pd
class OperatingRevenueTTM(Factor):
# 设置因子名称
name = 'custom_operating_revenue_ttm'
# 单季度财务数据只需要看最新一天(max_window=1 即可获取最新截面数据)
max_window = 1
# 声明依赖的前 4 个单季度营业收入
dependencies = [
'operating_revenue', # 最新季度
'operating_revenue_1', # 前1季度
'operating_revenue_2', # 前2季度
'operating_revenue_3' # 前3季度
]
def calc(self, data):
# calc 中的 data 为字典,对应的 value 为 DataFrame (index为日期, column为股票代码)
# 4个单季度相加得到 TTM
ttm = (
data['operating_revenue'] +
data['operating_revenue_1'] +
data['operating_revenue_2'] +
data['operating_revenue_3']
)
# 由于 max_window=1,返回的是 1 行 N 列的 DataFrame,需转为 Series (index为股票代码)
return ttm.iloc[0]
定义好因子类后,可以使用 calc_factors 函数对指定的股票池和时间范围计算因子值:
# 设置测试股票池与日期
securities = ['000001.XSHE', '600000.XSHG']
start_date = '2023-01-01'
end_date = '2023-01-10'
# 调用 calc_factors 计算自定义因子
factors_result = calc_factors(
securities=securities,
factors=[OperatingRevenueTTM()],
start_date=start_date,
end_date=end_date
)
# 获取计算结果 (返回一个 dict,key 为因子 name)
df_ttm = factors_result['custom_operating_revenue_ttm']
print(df_ttm.head())
calc 计算时获取到的都是当天历史截面上“已披露”的最新数据及其历史对应期,不会带入未来数据。max_window = 1 时,data['field'] 返回的是 1 行 N 列的 DataFrame,在 calc 返回时需要使用 .iloc[0] 或 .mean() 转换为以股票代码为索引的 pandas.Series。