复制链接
克隆策略

日内网格交易策略-分钟

策略思想

  • 第一步:确定价格中枢、压力位和阻力位
  • 第二步:确定网格的数量和间隔
  • 第三步:当价格触碰到网格线时,若高于买入价,则每上升一格卖出m手;若低于买入价,则每下跌一格买入m手。

策略构建步骤

确定股票池和回测时间

  • 通过证券代码列表输入回测的起止日期

确定买卖原则

  • 当价格触碰到网格线时,若高于买入价,则每上升一格卖出m手;若低于买入价,则每下跌一格买入m手。

回测

  • 通过 trade 模块中的初始化函数定义交易手续费和滑点;

  • 通过 trade 模块中的主函数(handle函数)查看每日的买卖交易信号,按照买卖原则执行相应的买入/卖出/调仓操作。

策略详情

    {"description":"实验创建于2021/12/6","graph":{"edges":[{"to_node_id":"-227:instruments","from_node_id":"-216:data"}],"nodes":[{"node_id":"-216","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2020-12-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-06-01","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_FUTURE","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"RU2109.SHF","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-216"}],"output_ports":[{"name":"data","node_id":"-216"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-227","module_id":"BigQuantSpace.hftrade.hftrade-v2","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"initialize","value":"# 交易引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n print(\"initialize\") \n context.ins = context.instruments[0]#从传入参数中获取需要交易的合约\n context.order_num = 1#下单手数\n context.set_universe(context.ins)#设置需要处理的合约\n context.last_grid = 0 # 储存前一个网格所处区间,用来和最新网格所处区间作比较\n context.closetime_day = \"14:58\"#日内策略白盘平仓时间,一般14:58\n context.closetime_night = \"22:58\"#日内策略夜盘平仓时间,一般22:58,注意有些商品夜盘收盘时间不一样","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 交易引擎:每个单位时间开盘前调用一次。\ndef bigquant_run(context, data):\n context.subscribe(context.ins) #注册合约\n\n # 记录上一次交易时网格范围的变化情况(例如从4区到5区,记为4,5)\n context.grid_change_last = [0,0]\n # 以前一日的收盘价为中枢价格\n context.center = data.history(context.ins,[\"close\"],1,\"1d\").iat[0,0]","type":"Literal","bound_global_parameter":null},{"name":"handle_tick","value":"# 交易引擎:tick数据处理函数,每个tick执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"def bigquant_run(context, data):\n from datetime import datetime,timedelta\n cur_date = data.current_dt\n cur_hm = cur_date.strftime('%H:%M') #time \n \n # 分别获取多头持仓和空头持仓\n position_long = context.get_position(context.ins, Direction.LONG)\n position_short = context.get_position(context.ins, Direction.SHORT)\n # 获取当前价格\n price = data.current(context.ins, \"close\")\n \n #部分品种夜盘收盘时间不一样,此时间表示指定的尾盘平仓时间往后偏移30分钟,这段时间内不能开新仓,只能平仓。给30分钟是为了足够的冗余\n closetime_nightshift = (datetime.strptime(context.closetime_night,'%H:%M') + timedelta(minutes = 30)).strftime('%H:%M') \n #尾盘平仓\n if((cur_hm>=context.closetime_day and cur_hm<=\"15:00\") or (cur_hm>=context.closetime_night and cur_hm<=closetime_nightshift)):\n if(position_long.current_qty != 0):\n rv = context.sell_close(context.ins, position_long.avail_qty, price, order_type=OrderType.MARKET)\n msg = \"{} 尾盘平多 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n if(position_short.current_qty != 0):\n rv = context.buy_close(context.ins, position_short.avail_qty, price, order_type=OrderType.MARKET)\n msg = \"{} 尾盘平空 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n #尾盘不开新仓,直接返回\n return\n \n # 设置网格和当前价格所处的网格区域\n band = np.array([0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09]) * context.center\n grid = pd.cut([price], band, labels=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])[0]\n # 如果价格超出网格设置范围,则提示调节网格宽度和数量\n if np.isnan(grid):\n context.write_log(\"价格波动超过网格范围,可适当调节网格宽度和数量\", stdout=1) #输出关键日志\n # 如果新的价格所处网格区间和前一个价格所处的网格区间不同,说明触碰到了网格线,需要进行交易\n # 如果新网格大于前一天的网格,做空或平多\n if context.last_grid < grid:\n # 记录新旧格子范围(按照大小排序)\n grid_change_new = [context.last_grid,grid]\n # 几种例外:\n # 当last_grid = 0 时是初始阶段,不构成信号\n # 如果此时grid = 3,说明当前价格仅在开盘价之下的3区域中,没有突破网格线\n # 如果此时grid = 4,说明当前价格仅在开盘价之上的4区域中,没有突破网格线\n if context.last_grid == 0:\n context.last_grid = grid\n return\n if context.last_grid != 0:\n # 如果前一次开仓是4-5,这一次是5-4,算是没有突破,不成交\n if grid_change_new != context.grid_change_last:\n # 更新前一次的数据\n context.last_grid = grid\n context.grid_change_last = grid_change_new\n # 如果有多仓,平多\n if position_long.current_qty != 0:\n rv = context.sell_close(context.ins,context.order_num, price, order_type=OrderType.MARKET)\n msg = \"{} 平多 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n # 否则,做空\n if not position_long.current_qty != 0:\n rv = context.sell_open(context.ins, context.order_num, price, order_type=OrderType.MARKET)\n msg = \"{} 开空 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n \n # 如果新网格小于前一天的网格,做多或平空\n if context.last_grid > grid:\n # 记录新旧格子范围(按照大小排序)\n grid_change_new = [grid,context.last_grid]\n # 几种例外:\n # 当last_grid = 0 时是初始阶段,不构成信号\n # 如果此时grid = 3,说明当前价格仅在开盘价之下的3区域中,没有突破网格线\n # 如果此时grid = 4,说明当前价格仅在开盘价之上的4区域中,没有突破网格线\n if context.last_grid == 0:\n context.last_grid = grid\n return\n if context.last_grid != 0:\n # 如果前一次开仓是4-5,这一次是5-4,算是没有突破,不成交\n if grid_change_new != context.grid_change_last:\n # 更新前一次的数据\n context.last_grid = grid\n context.grid_change_last = grid_change_new\n # 如果有空仓,平空\n if position_short.current_qty != 0:\n rv = context.buy_close(context.ins, context.order_num, price, order_type=OrderType.MARKET)\n msg = \"{} 平空 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n # 否则,做多\n if not position_short:\n rv = context.buy_open(context.ins, context.order_num, price, order_type=OrderType.MARKET)\n msg = \"{} 开多 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n \n # 设计一个止损条件:当持仓量达到10手,全部平仓\n if position_long.current_qty == 10 or position_long.current_qty == 10:\n context.write_log('触发止损,全部平仓', stdout=1) #输出关键日志\n if(position_long.current_qty != 0):\n rv = context.sell_close(context.ins, position_long.avail_qty, price, order_type=OrderType.MARKET)\n msg = \"{} 止损平多 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n if(position_short.current_qty != 0):\n rv = context.buy_close(context.ins, position_short.avail_qty, price, order_type=OrderType.MARKET)\n msg = \"{} 止损平空 for {} 最新价={} 下单函数返回={}\".format(str(data.current_dt),context.ins,str(price),str(rv))\n context.write_log(msg, stdout=1) #输出关键日志\n","type":"Literal","bound_global_parameter":null},{"name":"handle_trade","value":"# 交易引擎:成交回报处理函数,每个成交发生时执行一次\ndef bigquant_run(context, data):\n msg = \"handle_trade data:{}\".format(data.log_str())\n context.write_log(msg, stdout=1) \n # 分别获取最新的多头持仓和空头持仓\n position_long = context.get_position(data.symbol, Direction.LONG)\n position_short = context.get_position(data.symbol, Direction.SHORT)\n msg = \"当前多头持仓:{} 当前空头持仓:{}\".format(str(position_long),str(position_short))\n context.write_log(msg, stdout=1)\n","type":"Literal","bound_global_parameter":null},{"name":"handle_order","value":"# 交易引擎:委托回报处理函数,每个委托变化时执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"after_trading","value":"# 交易引擎:盘后处理函数,每日盘后执行一次\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":"50000","type":"Literal","bound_global_parameter":null},{"name":"frequency","value":"minute","type":"Literal","bound_global_parameter":null},{"name":"price_type","value":"真实价格","type":"Literal","bound_global_parameter":null},{"name":"product_type","value":"期货","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"0","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_buy","value":"open","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_sell","value":"close","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"000300.HIX","type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"disable_cache","value":"False","type":"Literal","bound_global_parameter":null},{"name":"replay_bdb","value":"False","type":"Literal","bound_global_parameter":null},{"name":"show_debug_info","value":"False","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-227"},{"name":"options_data","node_id":"-227"},{"name":"history_ds","node_id":"-227"},{"name":"benchmark_ds","node_id":"-227"}],"output_ports":[{"name":"raw_perf","node_id":"-227"}],"cacheable":false,"seq_num":2,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-216' Position='-78,22,200,200'/><node_position Node='-227' Position='-78,132,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [ ]:
    # 本代码由可视化策略环境自动生成 2022年6月5日 22:36
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 交易引擎:初始化函数,只执行一次
    def m2_initialize_bigquant_run(context):
        # 加载预测数据
        print("initialize")  
        context.ins = context.instruments[0]#从传入参数中获取需要交易的合约
        context.order_num = 1#下单手数
        context.set_universe(context.ins)#设置需要处理的合约
        context.last_grid = 0 # 储存前一个网格所处区间,用来和最新网格所处区间作比较
        context.closetime_day = "14:58"#日内策略白盘平仓时间,一般14:58
        context.closetime_night = "22:58"#日内策略夜盘平仓时间,一般22:58,注意有些商品夜盘收盘时间不一样
    # 交易引擎:每个单位时间开盘前调用一次。
    def m2_before_trading_start_bigquant_run(context, data):
        context.subscribe(context.ins) #注册合约
    
        # 记录上一次交易时网格范围的变化情况(例如从4区到5区,记为4,5)
        context.grid_change_last = [0,0]
        # 以前一日的收盘价为中枢价格
        context.center = data.history(context.ins,["close"],1,"1d").iat[0,0]
    # 交易引擎:tick数据处理函数,每个tick执行一次
    def m2_handle_tick_bigquant_run(context, data):
        pass
    
    def m2_handle_data_bigquant_run(context, data):
        from datetime import datetime,timedelta
        cur_date =  data.current_dt
        cur_hm = cur_date.strftime('%H:%M') #time  
        
        # 分别获取多头持仓和空头持仓
        position_long = context.get_position(context.ins, Direction.LONG)
        position_short = context.get_position(context.ins, Direction.SHORT)
        # 获取当前价格
        price = data.current(context.ins, "close")
        
        #部分品种夜盘收盘时间不一样,此时间表示指定的尾盘平仓时间往后偏移30分钟,这段时间内不能开新仓,只能平仓。给30分钟是为了足够的冗余
        closetime_nightshift = (datetime.strptime(context.closetime_night,'%H:%M') + timedelta(minutes = 30)).strftime('%H:%M')  
        #尾盘平仓
        if((cur_hm>=context.closetime_day and cur_hm<="15:00") or (cur_hm>=context.closetime_night and cur_hm<=closetime_nightshift)):
            if(position_long.current_qty != 0):
                rv = context.sell_close(context.ins, position_long.avail_qty, price, order_type=OrderType.MARKET)
                msg = "{} 尾盘平多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                context.write_log(msg, stdout=1) #输出关键日志
            if(position_short.current_qty != 0):
                rv = context.buy_close(context.ins, position_short.avail_qty, price, order_type=OrderType.MARKET)
                msg = "{} 尾盘平空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                context.write_log(msg, stdout=1) #输出关键日志
            #尾盘不开新仓,直接返回
            return
            
        # 设置网格和当前价格所处的网格区域
        band = np.array([0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 1, 1.01, 1.02, 1.03, 1.04, 1.05, 1.06, 1.07, 1.08, 1.09]) * context.center
        grid = pd.cut([price], band, labels=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])[0]
        # 如果价格超出网格设置范围,则提示调节网格宽度和数量
        if np.isnan(grid):
            context.write_log("价格波动超过网格范围,可适当调节网格宽度和数量", stdout=1) #输出关键日志
        # 如果新的价格所处网格区间和前一个价格所处的网格区间不同,说明触碰到了网格线,需要进行交易
        # 如果新网格大于前一天的网格,做空或平多
        if context.last_grid < grid:
            # 记录新旧格子范围(按照大小排序)
            grid_change_new = [context.last_grid,grid]
            # 几种例外:
            # 当last_grid = 0 时是初始阶段,不构成信号
            # 如果此时grid = 3,说明当前价格仅在开盘价之下的3区域中,没有突破网格线
            # 如果此时grid = 4,说明当前价格仅在开盘价之上的4区域中,没有突破网格线
            if context.last_grid == 0:
                context.last_grid = grid
                return
            if context.last_grid != 0:
                # 如果前一次开仓是4-5,这一次是5-4,算是没有突破,不成交
                if grid_change_new != context.grid_change_last:
                    # 更新前一次的数据
                    context.last_grid = grid
                    context.grid_change_last = grid_change_new
                    # 如果有多仓,平多
                    if position_long.current_qty != 0:
                        rv = context.sell_close(context.ins,context.order_num, price, order_type=OrderType.MARKET)
                        msg = "{} 平多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                        context.write_log(msg, stdout=1) #输出关键日志
                    # 否则,做空
                    if not position_long.current_qty != 0:
                        rv = context.sell_open(context.ins, context.order_num, price, order_type=OrderType.MARKET)
                        msg = "{} 开空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                        context.write_log(msg, stdout=1) #输出关键日志
                        
        # 如果新网格小于前一天的网格,做多或平空
        if context.last_grid > grid:
            # 记录新旧格子范围(按照大小排序)
            grid_change_new = [grid,context.last_grid]
            # 几种例外:
            # 当last_grid = 0 时是初始阶段,不构成信号
            # 如果此时grid = 3,说明当前价格仅在开盘价之下的3区域中,没有突破网格线
            # 如果此时grid = 4,说明当前价格仅在开盘价之上的4区域中,没有突破网格线
            if context.last_grid == 0:
                context.last_grid = grid
                return
            if context.last_grid != 0:
                # 如果前一次开仓是4-5,这一次是5-4,算是没有突破,不成交
                if grid_change_new != context.grid_change_last:
                    # 更新前一次的数据
                    context.last_grid = grid
                    context.grid_change_last = grid_change_new
                    # 如果有空仓,平空
                    if position_short.current_qty != 0:
                        rv = context.buy_close(context.ins, context.order_num, price, order_type=OrderType.MARKET)
                        msg = "{} 平空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                        context.write_log(msg, stdout=1) #输出关键日志
                    # 否则,做多
                    if not position_short:
                        rv = context.buy_open(context.ins, context.order_num, price, order_type=OrderType.MARKET)
                        msg = "{} 开多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                        context.write_log(msg, stdout=1) #输出关键日志
                            
        # 设计一个止损条件:当持仓量达到10手,全部平仓
        if position_long.current_qty == 10 or position_long.current_qty == 10:
            context.write_log('触发止损,全部平仓', stdout=1) #输出关键日志
            if(position_long.current_qty != 0):
                rv = context.sell_close(context.ins, position_long.avail_qty, price, order_type=OrderType.MARKET)
                msg = "{} 止损平多 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                context.write_log(msg, stdout=1) #输出关键日志
            if(position_short.current_qty != 0):
                rv = context.buy_close(context.ins, position_short.avail_qty, price, order_type=OrderType.MARKET)
                msg = "{} 止损平空 for {}  最新价={} 下单函数返回={}".format(str(data.current_dt),context.ins,str(price),str(rv))
                context.write_log(msg, stdout=1) #输出关键日志
    
    # 交易引擎:成交回报处理函数,每个成交发生时执行一次
    def m2_handle_trade_bigquant_run(context, data):
        msg = "handle_trade data:{}".format(data.log_str())
        context.write_log(msg, stdout=1) 
        # 分别获取最新的多头持仓和空头持仓
        position_long = context.get_position(data.symbol, Direction.LONG)
        position_short = context.get_position(data.symbol, Direction.SHORT)
        msg = "当前多头持仓:{} 当前空头持仓:{}".format(str(position_long),str(position_short))
        context.write_log(msg, stdout=1)
    
    # 交易引擎:委托回报处理函数,每个委托变化时执行一次
    def m2_handle_order_bigquant_run(context, data):
        pass
    
    # 交易引擎:盘后处理函数,每日盘后执行一次
    def m2_after_trading_bigquant_run(context, data):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2020-12-01',
        end_date='2021-06-01',
        market='CN_FUTURE',
        instrument_list='RU2109.SHF',
        max_count=0
    )
    
    m2 = M.hftrade.v2(
        instruments=m1.data,
        start_date='',
        end_date='',
        initialize=m2_initialize_bigquant_run,
        before_trading_start=m2_before_trading_start_bigquant_run,
        handle_tick=m2_handle_tick_bigquant_run,
        handle_data=m2_handle_data_bigquant_run,
        handle_trade=m2_handle_trade_bigquant_run,
        handle_order=m2_handle_order_bigquant_run,
        after_trading=m2_after_trading_bigquant_run,
        capital_base=50000,
        frequency='minute',
        price_type='真实价格',
        product_type='期货',
        before_start_days='0',
        order_price_field_buy='open',
        order_price_field_sell='close',
        benchmark='000300.HIX',
        plot_charts=True,
        disable_cache=False,
        replay_bdb=False,
        show_debug_info=False,
        backtest_only=False
    )