🚀 AI 一键生成 joinquant 策略代码

JoinQuant 策略中 set_universe 函数对 history 数据获取有什么影响?

joinquant | 发布时间: 2025/12/24
以下内容由 EasyQuant 生成。

问题描述

调用 history 函数时不想每次都传股票列表,可以用 set_universe 预设吗?

解决方案

是的,可以使用 set_universe 预设股票池

根据 JoinQuant API 文档,set_universe 函数的主要用途正是为了设定 history 函数的默认 security_list

使用方法说明

  1. 设置:initialize 函数中调用 set_universe(security_list) 传入股票列表。
  2. 调用: 在后续调用 history 函数时,不传递 security_list 参数(或将其设为 None),系统会自动查询 context.universe 中设定的股票数据。

代码示例

# -*- coding: utf-8 -*-
def initialize(context):
    # 1. 在初始化中预设股票池
    g.stocks = ['000001.XSHE', '600000.XSHG']
    set_universe(g.stocks)
    
    # 设定运行频率等其他设置
    set_benchmark('000300.XSHG')
    run_daily(print_history_data, 'every_bar')

def print_history_data(context):
    # 2. 调用 history 时省略 security_list 参数
    # 此时 history 会自动获取 set_universe 中设定的 '000001.XSHE' 和 '600000.XSHG' 的数据
    # 获取过去5天的收盘价
    data = history(5, unit='1d', field='close')
    
    log.info("获取到的 history 数据:")
    log.info(data)
    
    # 验证数据包含的列
    log.info("包含的股票代码: %s" % list(data.columns))

注意事项

  1. 适用范围限制set_universe 函数目前仅用于设定 history 函数的默认股票列表,对其他数据获取函数(如 get_priceattribute_history 等)无效。
  2. 参数覆盖:如果你在调用 history 时显式传递了 security_list 参数,那么 set_universe 中预设的列表将被忽略,系统以你显式传递的列表为准。
  3. API 建议historyset_universe 属于聚宽较早期的 API。在编写新策略时,通常建议使用功能更强大、更标准的 get_barsget_price 接口,不过这两个新接口通常需要显式传递股票列表。

Q&A

Q: set_universe 会影响 get_price 函数的默认股票列表吗?
A: 不会。set_universe 仅对 history 函数生效。调用 get_price 时必须显式传入 security 参数(单个标的或列表)。

Q: 如果我在 handle_data 中动态修改了 set_universehistory 获取的数据会变吗?
A: 会变。history 在每次调用时都会读取当前的 context.universe。如果在盘中通过 set_universe 更新了列表,随后的 history 调用将返回新列表的数据。

Q: history 函数如果不传 security_list 且没有调用过 set_universe 会发生什么?
A: 如果没有设置过 set_universecontext.universe 默认为空或未定义,直接调用不带股票列表的 history 可能会报错或返回空数据。建议务必在 initialize 中进行设置。