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

joinquant 平台如何继承 Factor 类编写自定义因子?(附 Python 代码示例)

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

问题描述

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

Title: joinquant 自定义因子编写:继承 Factor 类与实现 calc 方法

Question: 在 joinquant 中如何继承 Factor 类编写自定义因子并实现 calc 计算逻辑?

解决方案

在 JoinQuant 中继承 Factor 类编写自定义因子指南

在 JoinQuant(聚宽)平台上,编写自定义因子主要通过继承 Factor 类并实现 calc 方法来完成。通过自定义因子,你可以方便地在研究、回测及单因子分析中进行因子计算与选股。


一、自定义因子的基本结构

编写自定义因子需要定义四个核心属性/方法:

  1. name:因子的唯一标识名称(字符串)。
  2. max_window:因子计算所需的最大历史时间窗口(以天为单位)。
  3. dependencies:因子计算依赖的基础数据字段(如行情数据、财务数据、风险因子等)。
  4. calc(self, data):计算因子的核心逻辑函数,必须返回一个以股票代码为索引(Index)的 pandas.Series

二、代码实现示例

示例 1:基于价量数据的技术指标因子(均线 MA5)

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()

示例 2:基于财务数据的基本面因子(毛利率 Gross Profitability)

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())

四、注意事项与最佳实践

  1. dependencies 字段支持类型
    • 价量数据open, close, high, low, volume, money
    • 单季度财务数据:例如 operating_revenue(最新季)、operating_revenue_1(上前一季)等
    • 聚宽因子库/风格因子:如 size, beta, OperatingCycle
  2. calc 返回格式:必须保证 calc 函数返回的是一个 pandas.Series,索引为股票代码(如 '000001.XSHE')。若计算结果是单行 DataFrame,必须通过 .iloc[0].mean() 降维为 Series
  3. 避免未来函数:使用 dependencies 提供的财务字段时,系统已自动按策略运行日可获取的最新披露财报填充,无需手动防范未来函数。