克隆策略

    {"Description":"实验创建于2018/10/16","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-1442:instruments","SourceOutputPortId":"-25:data"},{"DestinationInputPortId":"-56:input_1","SourceOutputPortId":"-25:data"},{"DestinationInputPortId":"-1473:features","SourceOutputPortId":"-1468:data"},{"DestinationInputPortId":"-61:input_data","SourceOutputPortId":"-1473:data"},{"DestinationInputPortId":"-1442:options_data","SourceOutputPortId":"-61:data"},{"DestinationInputPortId":"-1473:input_data","SourceOutputPortId":"-56:data"},{"DestinationInputPortId":"-1442:history_ds","SourceOutputPortId":"-56:data"}],"ModuleNodes":[{"Id":"-25","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2020-01-20 09:01:00","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"2020-02-20 15:15:00","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"600010.SHA\n000001.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":"-25"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-25","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1442","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 # 设置是否是结算模式\n context.set_need_settle(False)\n context.set_commission(PerOrder(buy_cost=0.0013, sell_cost=0.0023, min_cost=5))\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n instruments = context.instruments\n \n # 获取当前分钟的买卖信号\n today_date=data.current_dt.strftime('%Y-%m-%d %H:%M:%S')\n time = data.current_dt.strftime('%H:%M')\n if context.index < 6: # 日内分钟计数器超过计算窗口后才开始交易\n context.index += 1\n return\n \n conditions = context.condition[context.condition.date==today_date] # 获取最新信号\n \n for instrument in instruments:\n instrument_symbol = context.symbol(instrument) # 交易标的\n curr_position = context.portfolio.positions[instrument_symbol].amount # 持仓数量\n \n try:\n buy_condition = conditions[conditions.instrument==instrument]['buy_condition'].values[0]\n except:\n buy_condition = 0\n \n try:\n daily_close_1 = conditions[conditions.instrument==instrument]['daily_close_1'].values[0]\n new_price = data.current(instrument_symbol, ['price'])\n sell_condition = 1 if new_price['price'] > daily_close_1*1.04 else 0\n except:\n sell_condition = 0 \n \n # 如果当前没有仓位且满足买入条件,执行开仓\n if curr_position == 0 and buy_condition>0 and time<\"14:56\":\n context.order_target(instrument_symbol, 100)\n elif curr_position >= 0 and (sell_condition>0 or time=='14:57'):\n context.order_target(instrument_symbol, 0)","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n df = context.options['data'].read_df()\n df['date']=df['date'].apply(lambda x:x.strftime('%Y-%m-%d %H:%M:%S'))\n context.condition=df\n\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n # 当日分钟K线数量记录变量初始化\n context.index = 1\n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"volume_limit","Value":"0","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":"500001","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"auto_cancel_non_tradable_orders","Value":"True","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"data_frequency","Value":"minute","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":"000300.HIX","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-1442"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-1442"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-1442","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1468","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"\n# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where(close>=ts_max(close,5),1,0)\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"-1468"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1468","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-1473","ModuleId":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","ModuleParameters":[{"Name":"date_col","Value":"date","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_col","Value":"instrument","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"drop_na","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"remove_extra_columns","Value":"False","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"user_functions","Value":"{}","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-1473"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-1473"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-1473","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":6,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-61","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-61"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-61"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-61","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-56","ModuleId":"BigQuantSpace.extract_minute_daily.extract_minute_daily-v3","ModuleParameters":[{"Name":"features","Value":"[\"daily_close_1=close_1/adjust_factor_1\", \"adjust_factor=adjust_factor_0\"]","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_days","Value":10,"ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_1","NodeId":"-56"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-56","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"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='-25' Position='9,22,200,200'/><NodePosition Node='-1442' Position='158,434.9627685546875,200,200'/><NodePosition Node='-1468' Position='395,20,200,200'/><NodePosition Node='-1473' Position='398,232,200,200'/><NodePosition Node='-61' Position='397,313,200,200'/><NodePosition Node='-56' Position='116.61395263671875,130.03721618652344,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":true}
    In [2]:
    # 本代码由可视化策略环境自动生成 2021年1月14日 16:32
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m3_initialize_bigquant_run(context):
       # 设置是否是结算模式
        context.set_need_settle(False)
        context.set_commission(PerOrder(buy_cost=0.0013, sell_cost=0.0023, min_cost=5))
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m3_handle_data_bigquant_run(context, data):
        instruments = context.instruments
        
        # 获取当前分钟的买卖信号
        today_date=data.current_dt.strftime('%Y-%m-%d %H:%M:%S')
        time = data.current_dt.strftime('%H:%M')
        if context.index < 6:  # 日内分钟计数器超过计算窗口后才开始交易
            context.index += 1
            return
        
        conditions = context.condition[context.condition.date==today_date] # 获取最新信号
        
        for instrument in instruments:
            instrument_symbol = context.symbol(instrument) # 交易标的
            curr_position = context.portfolio.positions[instrument_symbol].amount # 持仓数量
            
            try:
                buy_condition = conditions[conditions.instrument==instrument]['buy_condition'].values[0]
            except:
                buy_condition = 0
        
            try:
                daily_close_1 = conditions[conditions.instrument==instrument]['daily_close_1'].values[0]
                new_price = data.current(instrument_symbol, ['price'])
                sell_condition = 1 if new_price['price'] > daily_close_1*1.04 else 0
            except:
                sell_condition = 0   
                
            # 如果当前没有仓位且满足买入条件,执行开仓
            if curr_position == 0 and buy_condition>0 and time<"14:56":
                context.order_target(instrument_symbol, 100)
            elif curr_position >= 0 and (sell_condition>0 or time=='14:57'):
                context.order_target(instrument_symbol, 0)
    # 回测引擎:准备数据,只执行一次
    def m3_prepare_bigquant_run(context):
        df = context.options['data'].read_df()
        df['date']=df['date'].apply(lambda x:x.strftime('%Y-%m-%d %H:%M:%S'))
        context.condition=df
    
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m3_before_trading_start_bigquant_run(context, data):
        # 当日分钟K线数量记录变量初始化
        context.index = 1
    
    
    m2 = M.instruments.v2(
        start_date='2020-01-20 09:01:00',
        end_date='2020-02-20 15:15:00',
        market='CN_STOCK_A',
        instrument_list="""600010.SHA
    000001.SZA""",
        max_count=0,
        m_cached=False
    )
    
    m7 = M.extract_minute_daily.v3(
        input_1=m2.data,
        features=["daily_close_1=close_1/adjust_factor_1", "adjust_factor=adjust_factor_0"],
        before_days=10
    )
    
    m5 = M.input_features.v1(
        features="""
    # #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    buy_condition=where(close>=ts_max(close,5),1,0)
    """
    )
    
    m6 = M.derived_feature_extractor.v3(
        input_data=m7.data,
        features=m5.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m1 = M.dropnan.v2(
        input_data=m6.data
    )
    
    m3 = M.trade.v4(
        instruments=m2.data,
        options_data=m1.data,
        history_ds=m7.data,
        start_date='',
        end_date='',
        initialize=m3_initialize_bigquant_run,
        handle_data=m3_handle_data_bigquant_run,
        prepare=m3_prepare_bigquant_run,
        before_trading_start=m3_before_trading_start_bigquant_run,
        volume_limit=0,
        order_price_field_buy='open',
        order_price_field_sell='open',
        capital_base=500001,
        auto_cancel_non_tradable_orders=True,
        data_frequency='minute',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark='000300.HIX'
    )
    
    • 收益率-0.02%
    • 年化收益率-0.25%
    • 基准收益率-0.25%
    • 阿尔法-0.03
    • 贝塔0.0
    • 夏普比率-34.44
    • 胜率0.56
    • 盈亏比1.15
    • 收益波动率0.09%
    • 信息比率-0.01
    • 最大回撤0.03%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-2e62720ee0cd4468b58896df13a1b7bb"}/bigcharts-data-end
    In [7]:
    dd = m7.data.read()
    
    In [9]:
    dd[dd["date"] == "2020-01-20 09:31:00"]
    
    Out[9]:
    date instrument volume low close open high daily_close_1 adjust_factor
    0 2020-01-20 09:31:00 000001.SZA 1231528 16.42 16.48 16.43 16.51 16.389999 109.169426
    4320 2020-01-20 09:31:00 600010.SHA 2878960 1.30 1.30 1.30 1.31 1.300000 8.332732