3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在聚宽(JoinQuant)平台中,没有直接对应优矿 refresh_rate 的参数来直接控制 handle_data 的触发间隔。聚宽的 handle_data 默认是根据你设置的回测频率(按天或按分钟)每个单位时间触发一次。
但是,聚宽提供了非常灵活的定时运行函数以及全局变量机制,你可以通过以下两种主要方式完美实现 refresh_rate(自定义调仓间隔)的功能:
聚宽推荐使用 run_daily、run_weekly、run_monthly 来替代 handle_data 进行周期性调仓。这是最符合聚宽 API 风格的做法。
def initialize(context):
# 设定每周的第一个交易日开盘时运行调仓函数
run_weekly(rebalance, weekday=1, time='09:30')
def rebalance(context):
# 在这里编写你的调仓逻辑
log.info("执行每周调仓")
pass
def initialize(context):
# 设定每月的第一个交易日开盘时运行调仓函数
run_monthly(rebalance, monthday=1, time='09:30')
def rebalance(context):
# 在这里编写你的调仓逻辑
log.info("执行每月调仓")
pass
handle_data 中自定义计数器(实现任意 N 天调仓)如果你确实需要严格的“每隔 N 个交易日”调仓(比如每隔 3 天,每隔 10 天),你可以利用全局变量 g 在 handle_data 中自己维护一个计数器。
def initialize(context):
# 设置调仓间隔天数 (类似 refresh_rate = N)
g.refresh_rate = 5
# 初始化计数器
g.days_count = 0
def handle_data(context, data):
# 每次触发 handle_data 时,计数器加 1
g.days_count += 1
# 判断是否达到了调仓间隔
if g.days_count % g.refresh_rate == 0:
log.info(f"达到调仓周期,当前天数:{g.days_count},执行调仓")
rebalance(context, data)
def rebalance(context, data):
# 具体的买卖逻辑写在这里
pass
run_weekly 或 run_monthly,代码更简洁且易于维护。