问题描述
解决方案
是的,可以使用 set_universe 预设股票池。
根据 JoinQuant API 文档,set_universe 函数的主要用途正是为了设定 history 函数的默认 security_list。
使用方法说明
- 设置: 在
initialize函数中调用set_universe(security_list)传入股票列表。 - 调用: 在后续调用
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))
注意事项
- 适用范围限制:
set_universe函数目前仅用于设定history函数的默认股票列表,对其他数据获取函数(如get_price、attribute_history等)无效。 - 参数覆盖:如果你在调用
history时显式传递了security_list参数,那么set_universe中预设的列表将被忽略,系统以你显式传递的列表为准。 - API 建议:
history和set_universe属于聚宽较早期的 API。在编写新策略时,通常建议使用功能更强大、更标准的get_bars或get_price接口,不过这两个新接口通常需要显式传递股票列表。
Q&A
Q: set_universe 会影响 get_price 函数的默认股票列表吗?
A: 不会。set_universe 仅对 history 函数生效。调用 get_price 时必须显式传入 security 参数(单个标的或列表)。
Q: 如果我在 handle_data 中动态修改了 set_universe,history 获取的数据会变吗?
A: 会变。history 在每次调用时都会读取当前的 context.universe。如果在盘中通过 set_universe 更新了列表,随后的 history 调用将返回新列表的数据。
Q: history 函数如果不传 security_list 且没有调用过 set_universe 会发生什么?
A: 如果没有设置过 set_universe,context.universe 默认为空或未定义,直接调用不带股票列表的 history 可能会报错或返回空数据。建议务必在 initialize 中进行设置。