克隆策略

配对交易策略

    {"Description":"实验创建于2017/8/26","Summary":"","Graph":{"EdgesInternal":[{"DestinationInputPortId":"-836:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-3301:features","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"DestinationInputPortId":"-836:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-3041:instruments","SourceOutputPortId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"DestinationInputPortId":"-3301:input_data","SourceOutputPortId":"-836:data"},{"DestinationInputPortId":"-399:input_data","SourceOutputPortId":"-3301:data"},{"DestinationInputPortId":"-3041:options_data","SourceOutputPortId":"-399:data"}],"ModuleNodes":[{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","ModuleId":"BigQuantSpace.input_features.input_features-v1","ModuleParameters":[{"Name":"features","Value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nclose_0\n","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features_ds","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":1,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","ModuleId":"BigQuantSpace.instruments.instruments-v2","ModuleParameters":[{"Name":"start_date","Value":"2015-01-01","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"end_date","Value":"2018-10-28","ValueType":"Literal","LinkedGlobalParameter":"交易日期"},{"Name":"market","Value":"CN_STOCK_A","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"instrument_list","Value":"601328.SHA\n601998.SHA","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"max_count","Value":"0","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"rolling_conf","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"OutputPortsInternal":[{"Name":"data","NodeId":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":2,"IsPartOfPartialRun":null,"Comment":"预测数据,用于回测和模拟","CommentCollapsed":false},{"Id":"-836","ModuleId":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","ModuleParameters":[{"Name":"start_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"end_date","Value":"","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_start_days","Value":"300","ValueType":"Literal","LinkedGlobalParameter":null}],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"instruments","NodeId":"-836"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-836"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-836","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":7,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-3041","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_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"handle_data","Value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n today = data.current_dt.strftime('%Y-%m-%d')\n zscore_today =context.zscore.ix[today]\n #获取股票的列表\n stocklist=context.instruments\n # 转换成回测引擎所需要的symbol格式\n symbol_1 = context.symbol(stocklist[0]) \n symbol_2 = context.symbol(stocklist[1]) \n\n # 持仓\n cur_position_1 = context.portfolio.positions[symbol_1].amount\n cur_position_2 = context.portfolio.positions[symbol_2].amount\n \n # 交易逻辑\n # 如果zscore大于上轨(>1),则价差会向下回归均值,因此需要买入股票x,卖出股票y\n if zscore_today > 1 and cur_position_1 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2): \n context.order_target_percent(symbol_2, 0)\n context.order_target_percent(symbol_1, 1)\n print(today, '全仓买入:',stocklist[0])\n \n # 如果zscore小于下轨(<-1),则价差会向上回归均值,因此需要买入股票y,卖出股票x\n elif zscore_today < -1 and cur_position_2 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2): \n context.order_target_percent(symbol_1, 0) \n context.order_target_percent(symbol_2, 1)\n print(today, '全仓买入:',stocklist[1])\n \n \n","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"prepare","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass","ValueType":"Literal","LinkedGlobalParameter":null},{"Name":"before_trading_start","Value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context,data):\n # 加载股票历史数据\n df = context.options['data'].read_df()\n df['date'] = df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n today = data.current_dt.strftime('%Y-%m-%d')\n # 获取前240个自然日的数据\n start_date = (pd.to_datetime(data.current_dt)-datetime.timedelta(days=240)).strftime('%Y-%m-%d')\n stock_data = df[df.date <= today]\n # 由于可能上市天数不同,对缺失值填充处理\n prices_df=pd.pivot_table(stock_data, values='close_0', index=['date'], columns=['instrument'])\n prices_df.fillna(method='ffill',inplace=True)\n \n x = prices_df[context.instruments[0]] # 股票1\n y = prices_df[context.instruments[1]] # 股票2\n \n # 线性回归两个股票的股价 y=ax+b\n from pyfinance import ols\n model = ols.OLS(y=y, x=x)\n \n def zscore(series):\n return (series - series.mean()) / np.std(series)\n \n # 计算 y-a*x 序列的zscore值序列\n zscore_calcu = zscore(y-model.beta*x)\n context.zscore=zscore_calcu","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":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"options_data","NodeId":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"history_ds","NodeId":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"benchmark_ds","NodeId":"-3041"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"trading_calendar","NodeId":"-3041"}],"OutputPortsInternal":[{"Name":"raw_perf","NodeId":"-3041","OutputType":null}],"UsePreviousResults":false,"moduleIdForCode":3,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-3301","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":"-3301"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-3301"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-3301","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":4,"IsPartOfPartialRun":null,"Comment":"","CommentCollapsed":true},{"Id":"-399","ModuleId":"BigQuantSpace.dropnan.dropnan-v2","ModuleParameters":[],"InputPortsInternal":[{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"input_data","NodeId":"-399"},{"DataSourceId":null,"TrainedModelId":null,"TransformModuleId":null,"Name":"features","NodeId":"-399"}],"OutputPortsInternal":[{"Name":"data","NodeId":"-399","OutputType":null}],"UsePreviousResults":true,"moduleIdForCode":5,"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='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='1306,105,200,200'/><NodePosition Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='812,113,200,200'/><NodePosition Node='-836' Position='1079,236,200,200'/><NodePosition Node='-3041' Position='999,558,200,200'/><NodePosition Node='-3301' Position='1088,305,200,200'/><NodePosition Node='-399' Position='1079,397,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 [7]:
    # 本代码由可视化策略环境自动生成 2020年9月23日 14:42
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m3_initialize_bigquant_run(context):
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    # 回测引擎:每日数据处理函数,每天执行一次
    def m3_handle_data_bigquant_run(context, data):
        today = data.current_dt.strftime('%Y-%m-%d')
        zscore_today =context.zscore.ix[today]
        #获取股票的列表
        stocklist=context.instruments
        # 转换成回测引擎所需要的symbol格式
        symbol_1 = context.symbol(stocklist[0]) 
        symbol_2 = context.symbol(stocklist[1])  
    
        # 持仓
        cur_position_1 = context.portfolio.positions[symbol_1].amount
        cur_position_2 = context.portfolio.positions[symbol_2].amount
           
        # 交易逻辑
        # 如果zscore大于上轨(>1),则价差会向下回归均值,因此需要买入股票x,卖出股票y
        if zscore_today > 1 and cur_position_1 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2):  
            context.order_target_percent(symbol_2, 0)
            context.order_target_percent(symbol_1, 1)
            print(today, '全仓买入:',stocklist[0])
            
        # 如果zscore小于下轨(<-1),则价差会向上回归均值,因此需要买入股票y,卖出股票x
        elif zscore_today < -1 and cur_position_2 == 0 and data.can_trade(symbol_1) and data.can_trade(symbol_2):  
            context.order_target_percent(symbol_1, 0)  
            context.order_target_percent(symbol_2, 1)
            print(today, '全仓买入:',stocklist[1])
     
              
    
    # 回测引擎:准备数据,只执行一次
    def m3_prepare_bigquant_run(context):
        pass
    # 回测引擎:准备数据,只执行一次
    def m3_before_trading_start_bigquant_run(context,data):
        # 加载股票历史数据
        df = context.options['data'].read_df()
        df['date'] = df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
        today = data.current_dt.strftime('%Y-%m-%d')
        # 获取前240个自然日的数据
        start_date = (pd.to_datetime(data.current_dt)-datetime.timedelta(days=240)).strftime('%Y-%m-%d')
        stock_data = df[df.date <= today]
        # 由于可能上市天数不同,对缺失值填充处理
        prices_df=pd.pivot_table(stock_data, values='close_0', index=['date'], columns=['instrument'])
        prices_df.fillna(method='ffill',inplace=True)
        
        x = prices_df[context.instruments[0]] # 股票1
        y = prices_df[context.instruments[1]] # 股票2
        
        # 线性回归两个股票的股价 y=ax+b
        from pyfinance import ols
        model = ols.OLS(y=y, x=x)
     
        def zscore(series):
            return (series - series.mean()) / np.std(series)
        
        # 计算 y-a*x 序列的zscore值序列
        zscore_calcu = zscore(y-model.beta*x)
        context.zscore=zscore_calcu
    
    m1 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    close_0
    """
    )
    
    m2 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2015-01-01'),
        end_date=T.live_run_param('trading_date', '2018-10-28'),
        market='CN_STOCK_A',
        instrument_list="""601328.SHA
    601998.SHA""",
        max_count=0
    )
    
    m7 = M.general_feature_extractor.v7(
        instruments=m2.data,
        features=m1.data,
        start_date='',
        end_date='',
        before_start_days=300
    )
    
    m4 = M.derived_feature_extractor.v3(
        input_data=m7.data,
        features=m1.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m5 = M.dropnan.v2(
        input_data=m4.data
    )
    
    m3 = M.trade.v4(
        instruments=m2.data,
        options_data=m5.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.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=''
    )
    
    2015-01-05 全仓买入: 601328.SHA
    2015-06-01 全仓买入: 601998.SHA
    2015-07-08 全仓买入: 601328.SHA
    2015-08-31 全仓买入: 601998.SHA
    2015-11-18 全仓买入: 601328.SHA
    2016-06-06 全仓买入: 601998.SHA
    
    2016-11-28 全仓买入: 601328.SHA
    2017-04-19 全仓买入: 601998.SHA
    
    2018-02-05 全仓买入: 601328.SHA
    
    2018-09-14 全仓买入: 601998.SHA
    
    • 收益率54.33%
    • 年化收益率12.48%
    • 基准收益率-10.19%
    • 阿尔法0.15
    • 贝塔0.74
    • 夏普比率0.44
    • 胜率0.67
    • 盈亏比0.69
    • 收益波动率30.75%
    • 信息比率0.04
    • 最大回撤40.63%
    bigcharts-data-start/{"__id":"bigchart-56cff1c73cbc45268d29cd7a4da5d1ce","__type":"tabs"}/bigcharts-data-end