3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 JoinQuant(聚宽)平台上,编写自定义因子主要通过继承 Factor 类并实现 calc 方法来完成。通过自定义因子,你可以方便地在研究、回测及单因子分析中进行因子计算与选股。
编写自定义因子需要定义四个核心属性/方法:
name:因子的唯一标识名称(字符串)。max_window:因子计算所需的最大历史时间窗口(以天为单位)。dependencies:因子计算依赖的基础数据字段(如行情数据、财务数据、风险因子等)。calc(self, data):计算因子的核心逻辑函数,必须返回一个以股票代码为索引(Index)的 pandas.Series。import pandas as pd
from jqfactor import Factor, calc_factors
class MA5(Factor):
# 1. 定义因子名称
name = 'ma5_custom'
# 2. 设置需要获取过去5天的数据
max_window = 5
# 3. 依赖的基础数据字段(收盘价)
dependencies = ['close']
def calc(self, data):
# data['close'] 为 DataFrame,列是股票代码,行是日期(长度为 max_window)
close = data['close']
# 计算过去5天的收盘价均值,返回 pd.Series
return close.mean()
from jqfactor import Factor, calc_factors
class GrossProfitability(Factor):
name = 'gross_profitability_custom'
max_window = 1
# 依赖单季度财务数据字段
dependencies = ['total_operating_revenue', 'total_operating_cost', 'total_assets']
def calc(self, data):
# 当 max_window=1 时,获取的是 1行 N列 的 DataFrame
rev = data['total_operating_revenue']
cost = data['total_operating_cost']
assets = data['total_assets']
# 计算毛利率:(营业总收入 - 营业总成本) / 总资产
gp = (rev - cost) / assets
# 使用 .iloc[0] 或 .mean() 将 1行N列 的 DataFrame 转为 Series
return gp.iloc[0]
定义好因子类后,可以使用 jqfactor 模块中的 calc_factors 函数进行调用计算:
from jqdata import get_index_stocks
# 1. 获取股票池
securities = get_index_stocks('000300.XSHG')[:5]
# 2. 调用 calc_factors 批量计算
factors_result = calc_factors(
securities=securities,
factors=[MA5(), GrossProfitability()],
start_date='2023-01-01',
end_date='2023-01-10'
)
# 3. 查看计算结果(返回 dict,key 为因子 name,value 为 DataFrame)
print(factors_result['ma5_custom'].head())
dependencies 字段支持类型:
open, close, high, low, volume, moneyoperating_revenue(最新季)、operating_revenue_1(上前一季)等size, beta, OperatingCycle 等calc 返回格式:必须保证 calc 函数返回的是一个 pandas.Series,索引为股票代码(如 '000001.XSHE')。若计算结果是单行 DataFrame,必须通过 .iloc[0] 或 .mean() 降维为 Series。dependencies 提供的财务字段时,系统已自动按策略运行日可获取的最新披露财报填充,无需手动防范未来函数。