【模板案例】盘前撤单再委托

策略分享
meetup
标签: #<Tag:0x00007f8c5e5d32d8> #<Tag:0x00007f8c5e5d3198>

(iQuant) #1

10月29日Meetup案例:盘前撤单再委托

克隆策略

    {"Description":"实验创建于2020/10/29","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-152:instruments","SourceOutputPortId":"-140:data"}],"ModuleNodes":[{"Id":"-140","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2016-06-28","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2016-07-18","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"600000.SHA\n000002.SZA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":0,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"-140"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-140","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-152","ModuleId":"BigQuantSpace.trade.trade-v4","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"initialize","Value":"# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n pass","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n \n dt = data.current_dt.strftime('%Y-%m-%d')\n k = context.instruments[0] # 标的为字符串格式\n sid = context.symbol(k) # 将标的转化为equity格式\n \n if dt == '2016-07-13':\n order(sid, 100)\n print(dt,'生成一个买入100股的虚拟订单')\n ","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n \n dt = data.current_dt.strftime('%Y-%m-%d')\n \n k = context.instruments[0] # 标的为字符串格式\n \n sid = context.symbol(k) # 将标的转化为equity格式\n \n print('撤单之前的委托:', context.get_open_orders().values())\n \n for open_orders in context.get_open_orders().values():\n\n \n for order in open_orders:\n \n sid = order.sid\n today_open = data.current(sid, 'open')\n \n if True: \n context.cancel_order(order)\n print(dt,'在before_trading_start取消订单:',sid)\n print('撤单之后的委托:',context.get_open_orders().values())\n \n # 买入另外一只\n from zipline.finance.order import Order\n from zipline.finance.execution import MarketOrder\n \n order = Order(\n dt = order['dt'],\n asset=context.symbol(context.instruments[1]),\n amount=100,\n stop=None,\n limit=None,\n price_field='open')\n \n try:\n context.blotter.open_orders[order.asset].append(order)\n except Exception:\n context.blotter.open_orders[order.asset] = [order]\n\n context.blotter.orders[order.id] = order\n context.blotter.new_orders.append(order)\n continue\n \n print('新提交订单后的委托:',context.get_open_orders().values())\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":0.025,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_buy","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"order_price_field_sell","Value":"open","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"capital_base","Value":1000000,"ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"daily","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"price_type","Value":"真实价格","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"product_type","Value":"股票","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"plot_charts","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"backtest_only","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"benchmark","Value":"","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-152"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-152"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-152"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-152"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-152"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-152","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true}],"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions><NodePosition Node='-140' Position='225,157,200,200'/><NodePosition Node='-152' Position='185,341,200,200'/></NodePositions><NodeGroups /></DataV1>"},"IsDraft":true,"ParentExperimentId":null,"WebService":{"IsWebServiceExperiment":false,"Inputs":[],"Outputs":[],"Parameters":[{"Name":"交易日期","Value":"","ParameterDefinition":{"Name":"交易日期","FriendlyName":"交易日期","DefaultValue":"","ParameterType":"String","HasDefaultValue":true,"IsOptional":true,"ParameterRules":[],"HasRules":false,"MarkupType":0,"CredentialDescriptor":null}}],"WebServiceGroupId":null,"SerializedClientData":"<?xml version='1.0' encoding='utf-16'?><DataV1 xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><Meta /><NodePositions></NodePositions><NodeGroups /></DataV1>"},"DisableNodesUpdate":false,"Category":"user","Tags":[],"IsPartialRun":false}
    In [11]:
    # 本代码由可视化策略环境自动生成 2020年10月29日 16:28
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m2_initialize_bigquant_run(context):
        pass
    # 回测引擎:每日数据处理函数,每天执行一次
    def m2_handle_data_bigquant_run(context, data):
        
        dt = data.current_dt.strftime('%Y-%m-%d')
        k = context.instruments[0] # 标的为字符串格式
        sid = context.symbol(k) # 将标的转化为equity格式
        
        if dt == '2016-07-13':
            order(sid, 100)
            print(dt,'生成一个买入100股的虚拟订单')
        
    # 回测引擎:准备数据,只执行一次
    def m2_prepare_bigquant_run(context):
        pass
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m2_before_trading_start_bigquant_run(context, data):
        
        dt = data.current_dt.strftime('%Y-%m-%d')
        
        k = context.instruments[0] # 标的为字符串格式
        
        sid = context.symbol(k) # 将标的转化为equity格式
        
        print('撤单之前的委托:', context.get_open_orders().values())
        
        for open_orders in context.get_open_orders().values():
    
            
            for order in open_orders:
            
                sid = order.sid
                today_open = data.current(sid, 'open')
               
                if True:   
                    context.cancel_order(order)
                    print(dt,'在before_trading_start取消订单:',sid)
                    print('撤单之后的委托:',context.get_open_orders().values())
                    
                    # 买入另外一只
                    from zipline.finance.order import Order
                    from zipline.finance.execution import MarketOrder
                    
                    order = Order(
                        dt = order['dt'],
                        asset=context.symbol(context.instruments[1]),
                        amount=100,
                        stop=None,
                        limit=None,
                        price_field='open')
                  
                    try:
                        context.blotter.open_orders[order.asset].append(order)
                    except Exception:
                        context.blotter.open_orders[order.asset] = [order]
    
                    context.blotter.orders[order.id] = order
                    context.blotter.new_orders.append(order)
                    continue
                    
        print('新提交订单后的委托:',context.get_open_orders().values())
    
    
    m1 = M.instruments.v2(
        start_date='2016-06-28',
        end_date='2016-07-18',
        market='CN_STOCK_A',
        instrument_list="""600000.SHA
    000002.SZA""",
        max_count=0
    )
    
    m2 = M.trade.v4(
        instruments=m1.data,
        start_date='',
        end_date='',
        initialize=m2_initialize_bigquant_run,
        handle_data=m2_handle_data_bigquant_run,
        prepare=m2_prepare_bigquant_run,
        before_trading_start=m2_before_trading_start_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    2016-07-13 生成一个买入100股的虚拟订单
    撤单之前的委托: dict_values([[Event({'id': '1824d1a975074419ba6df66a859a3fbe', 'dt': Timestamp('2016-07-14 09:30:00+0000', tz='UTC'), 'reason': None, 'created': Timestamp('2016-07-14 09:30:00+0000', tz='UTC'), 'amount': 100, 'last_filled': 0, 'filled': 0, 'commission': 0, 'stop': None, 'limit': None, 'stop_reached': False, 'price_field': 'open', 'limit_reached': False, 'position_effect': None, 'sid': Equity(135 [000002.SZA]), 'status': 0})]])
    2016-07-14 在before_trading_start取消订单: Equity(135 [000002.SZA])
    撤单之后的委托: dict_values([])
    新提交订单后的委托: dict_values([[Event({'id': 'afdf348aa0344a3fb3506de402e059cc', 'dt': Timestamp('2016-07-14 09:30:00+0000', tz='UTC'), 'reason': None, 'created': Timestamp('2016-07-14 09:30:00+0000', tz='UTC'), 'amount': 100, 'last_filled': 0, 'filled': 0, 'commission': 0, 'stop': None, 'limit': None, 'stop_reached': False, 'price_field': 'open', 'limit_reached': False, 'position_effect': None, 'sid': Equity(103 [600000.SHA]), 'status': 0})]])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    撤单之前的委托: dict_values([])
    新提交订单后的委托: dict_values([])
    
    • 收益率-0.0%
    • 年化收益率-0.01%
    • 基准收益率4.53%
    • 阿尔法-0.03
    • 贝塔0.0
    • 夏普比率-521.75
    • 胜率0.0
    • 盈亏比0.0
    • 收益波动率0.01%
    • 信息比率-0.41
    • 最大回撤0.0%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-49b78c8e884342afa60e2d9b39cf9b6b"}/bigcharts-data-end

    BigQuant AI量化专家Meetup(更新至11月19日)