3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
在 JoinQuant(聚宽)量化平台上,handle_data 函数的运行时间是系统默认设定的,不能直接自定义修改。
handle_data 的默认运行机制:handle_data 函数。如果您希望在特定的时间点(例如每天的 10:00 或 14:50)执行交易逻辑,官方强烈建议放弃使用 handle_data,转而使用定时运行函数 run_daily、run_weekly 或 run_monthly。
注意: 一个策略中尽量不要同时使用 run_daily 和 handle_data,更不能写成 run_daily(handle_data, "10:00")。
run_daily 设定运行时间的示例:您可以将原本写在 handle_data 中的逻辑提取到一个自定义函数中,然后在 initialize 中使用 run_daily 指定其运行时间。
# 导入聚宽函数库
import jqdata
def initialize(context):
# 设定要操作的股票
g.security = '000001.XSHE'
# 取消所有默认的定时运行(可选,确保环境干净)
unschedule_all()
# 设定自定义函数 my_trade_logic 在每天的 10:00 运行
run_daily(my_trade_logic, time='10:00')
# 设定自定义函数 my_trade_logic 在每天的 14:50 运行
run_daily(my_trade_logic, time='14:50')
# 自定义交易逻辑函数(注意:参数只能有 context,不能有 data)
def my_trade_logic(context):
# 获取当前时间
current_time = context.current_dt
log.info("当前运行时间: %s" % current_time)
# 获取数据(替代 handle_data 中的 data 参数)
# 使用 get_price 或 attribute_history 获取所需数据
current_data = get_current_data()
current_price = current_data[g.security].last_price
# 执行下单逻辑
if current_price > 10.0:
order(g.security, 100)
log.info("买入 %s" % g.security)
handle_data 的时间,它是平台固定的基础回调函数。run_daily(自定义函数, time='HH:MM') 是实现特定时间调仓、运行策略的标准且最灵活的方法。run_daily 指定的函数中,由于没有 data 参数,您需要使用 get_current_data()、history() 或 get_price() 等 API 来主动获取行情数据。