克隆策略

多条件选股策略

    {"description":"实验创建于2018/6/27","graph":{"edges":[{"to_node_id":"-353:instruments","from_node_id":"-51:data"},{"to_node_id":"-370:instruments","from_node_id":"-51:data"},{"to_node_id":"-353:features","from_node_id":"-59:data"},{"to_node_id":"-360:features","from_node_id":"-59:data"},{"to_node_id":"-360:input_data","from_node_id":"-353:data"},{"to_node_id":"-390:input_ds","from_node_id":"-360:data"},{"to_node_id":"-370:options_data","from_node_id":"-390:sorted_data"}],"nodes":[{"node_id":"-51","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2021-06-20","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-07-01","type":"Literal","bound_global_parameter":"交易日期"},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-51"}],"output_ports":[{"name":"data","node_id":"-51"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-59","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"\n# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition=where((open_0>close_1)&(mean(close_0,5)>mean(close_0,10)),1,0)\nsell_condition=where(mean(close_0,5)<mean(close_0,10),1,0)\npe_ttm_0\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-59"}],"output_ports":[{"name":"data","node_id":"-59"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"-353","module_id":"BigQuantSpace.general_feature_extractor.general_feature_extractor-v7","parameters":[{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"before_start_days","value":"60","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-353"},{"name":"features","node_id":"-353"}],"output_ports":[{"name":"data","node_id":"-353"}],"cacheable":false,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-360","module_id":"BigQuantSpace.derived_feature_extractor.derived_feature_extractor-v3","parameters":[{"name":"date_col","value":"date","type":"Literal","bound_global_parameter":null},{"name":"instrument_col","value":"instrument","type":"Literal","bound_global_parameter":null},{"name":"drop_na","value":"False","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-360"},{"name":"features","node_id":"-360"}],"output_ports":[{"name":"data","node_id":"-360"}],"cacheable":true,"seq_num":7,"comment":"","comment_collapsed":true},{"node_id":"-370","module_id":"BigQuantSpace.trade.trade-v4","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 # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n\n class FixedPriceSlippage(SlippageModel):\n def process_order(self, data, order, bar_volume=0, trigger_check_price=0):\n if order.limit is None:\n price_field = self._price_field_buy if order.amount > 0 else self._price_field_sell\n price = data.current(order.asset, price_field)\n else:\n price = data.current(order.asset, \"open\")\n print(\"==============开盘价成交 \",\"order.asset=\",order.asset,\"open price=\",price)\n \n # 返回希望成交的价格和数量\n return (price, order.amount)\n # 如果未限价,设置滑点范围为最低价到最高价,即未限价时按照最低价买入、最高价卖出\n context.fix_slippage = FixedPriceSlippage(price_field_buy='open', price_field_sell='close')\n context.set_slippage(us_equities=context.fix_slippage) # us是universe的简写,如果是期货,需要传入us_future\n\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 回测引擎:每日数据处理函数,每天执行一次\n today = data.current_dt.strftime('%Y-%m-%d') # 日期\n # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 记录用于买入股票的可用现金\n cash_for_buy = context.portfolio.cash\n \n # 获取当日符合买入/卖出条件的股票列表\n try:\n buy_stock = context.daily_buy_stock[today] # 当日符合买入条件的股票\n except:\n buy_stock=[]\n try:\n sell_stock = context.daily_sell_stock[today] # 当日符合卖出条件的股票\n except:\n sell_stock = []\n\n # 需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [i for i in stock_hold_now if i in sell_stock]\n # 需要买入的股票:没有持仓且符合买入条件的股票\n stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]\n # 卖出\n for instrument in stock_to_sell:\n # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态\n # 如果返回真值,则可以正常下单,否则会出错\n # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式\n if data.can_trade(context.symbol(instrument)):\n # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档\n if(today==\"2021-06-23\"):\n from zipline.finance.execution import LimitOrder\n price = data.current(context.symbol(instrument), \"close\")#不一定按照此价格成交,需要看初始化函数中自定义买卖价格那里如何设置的\n rv = context.order_target(context.symbol(instrument), 0, limit_price=price)\n else:\n context.order_target_percent(context.symbol(instrument), 0)\n # 开盘卖出后所得资金可用来买入股票,更新当日可用现金\n cash_for_buy += stock_hold_now[instrument]\n \n # 如果当天没有买入的股票,就返回\n if len(stock_to_buy) == 0:\n return\n \n # 买入\n for instrument in stock_to_buy:\n # 利用当日可用现金使用等资金比例下单买入\n cash = cash_for_buy / len(stock_to_buy)\n if data.can_trade(context.symbol(instrument)):\n current_price = data.current(context.symbol(instrument), 'price')\n amount = math.floor(cash / current_price / 100) * 100\n context.order(context.symbol(instrument), amount)","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = context.options['data'].read_df()\n # 函数:求满足开仓条件的股票列表\n def open_pos_con(df):\n return list(df[df['buy_condition']>0].instrument)[:10]\n\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df[df['sell_condition']>0].instrument)\n \n # 每日买入股票的数据框\n context.daily_buy_stock= df.groupby('date').apply(open_pos_con)\n # 每日卖出股票的数据框\n context.daily_sell_stock= df.groupby('date').apply(close_pos_con) \n \n \n","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"# 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。\ndef bigquant_run(context, data):\n pass\n","type":"Literal","bound_global_parameter":null},{"name":"volume_limit","value":0.025,"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":"capital_base","value":1000000,"type":"Literal","bound_global_parameter":null},{"name":"auto_cancel_non_tradable_orders","value":"True","type":"Literal","bound_global_parameter":null},{"name":"data_frequency","value":"daily","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":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"backtest_only","value":"False","type":"Literal","bound_global_parameter":null},{"name":"benchmark","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-370"},{"name":"options_data","node_id":"-370"},{"name":"history_ds","node_id":"-370"},{"name":"benchmark_ds","node_id":"-370"},{"name":"trading_calendar","node_id":"-370"}],"output_ports":[{"name":"raw_perf","node_id":"-370"}],"cacheable":false,"seq_num":8,"comment":"","comment_collapsed":true},{"node_id":"-390","module_id":"BigQuantSpace.sort.sort-v4","parameters":[{"name":"sort_by","value":"pe_ttm_0","type":"Literal","bound_global_parameter":null},{"name":"group_by","value":"date","type":"Literal","bound_global_parameter":null},{"name":"keep_columns","value":"--","type":"Literal","bound_global_parameter":null},{"name":"ascending","value":"True","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_ds","node_id":"-390"},{"name":"sort_by_ds","node_id":"-390"}],"output_ports":[{"name":"sorted_data","node_id":"-390"}],"cacheable":true,"seq_num":9,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-51' Position='89,21,200,200'/><node_position Node='-59' Position='448,124,200,200'/><node_position Node='-353' Position='257,236,200,200'/><node_position Node='-360' Position='239,338,200,200'/><node_position Node='-370' Position='198.12310791015625,549,200,200'/><node_position Node='-390' Position='291,437,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [59]:
    # 本代码由可视化策略环境自动生成 2021年7月10日17:42
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m8_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    
        class FixedPriceSlippage(SlippageModel):
            def process_order(self, data, order, bar_volume=0, trigger_check_price=0):
                if order.limit is None:
                    price_field = self._price_field_buy if order.amount > 0 else self._price_field_sell
                    price = data.current(order.asset, price_field)
                else:
                    price = data.current(order.asset, "open")
                    print("==============开盘价成交 ","order.asset=",order.asset,"open price=",price)
                
                # 返回希望成交的价格和数量
                return (price, order.amount)
        # 如果未限价,设置滑点范围为最低价到最高价,即未限价时按照最低价买入、最高价卖出
        context.fix_slippage = FixedPriceSlippage(price_field_buy='open', price_field_sell='close')
        context.set_slippage(us_equities=context.fix_slippage) # us是universe的简写,如果是期货,需要传入us_future
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m8_handle_data_bigquant_run(context, data):
        # 回测引擎:每日数据处理函数,每天执行一次
        today = data.current_dt.strftime('%Y-%m-%d') # 日期
        # 通过positions对象,使用列表生成式的方法获取目前持仓的股票列表和对应的最新市值
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
    
        # 记录用于买入股票的可用现金
        cash_for_buy = context.portfolio.cash
        
        # 获取当日符合买入/卖出条件的股票列表
        try:
            buy_stock = context.daily_buy_stock[today]  # 当日符合买入条件的股票
        except:
            buy_stock=[]
        try:
            sell_stock = context.daily_sell_stock[today]  # 当日符合卖出条件的股票
        except:
            sell_stock = []
    
        # 需要卖出的股票:已有持仓中符合卖出条件的股票
        stock_to_sell = [i for i in stock_hold_now if i in sell_stock]
        # 需要买入的股票:没有持仓且符合买入条件的股票
        stock_to_buy = [i for i in buy_stock if i not in stock_hold_now]
        # 卖出
        for instrument in stock_to_sell:
            # 如果该股票停牌,则没法成交。因此需要用can_trade方法检查下该股票的状态
            # 如果返回真值,则可以正常下单,否则会出错
            # 因为stock是字符串格式,我们用symbol方法将其转化成平台可以接受的形式:Equity格式
            if data.can_trade(context.symbol(instrument)):
                # order_target_percent是平台的一个下单接口,表明下单使得该股票的权重为0,即卖出全部股票,可参考回测文档
                if(today=="2021-06-23"):
                    from zipline.finance.execution import LimitOrder
                    price = data.current(context.symbol(instrument), "close")#不一定按照此价格成交,需要看初始化函数中自定义买卖价格那里如何设置的
                    rv = context.order_target(context.symbol(instrument), 0, limit_price=price)
                else:
                    context.order_target_percent(context.symbol(instrument), 0)
                # 开盘卖出后所得资金可用来买入股票,更新当日可用现金
                cash_for_buy += stock_hold_now[instrument]
                
        # 如果当天没有买入的股票,就返回
        if len(stock_to_buy) == 0:
            return
        
        # 买入
        for instrument in stock_to_buy:
            # 利用当日可用现金使用等资金比例下单买入
            cash = cash_for_buy / len(stock_to_buy)
            if data.can_trade(context.symbol(instrument)):
                current_price = data.current(context.symbol(instrument), 'price')
                amount = math.floor(cash / current_price / 100) * 100
                context.order(context.symbol(instrument), amount)
    # 回测引擎:准备数据,只执行一次
    def m8_prepare_bigquant_run(context):
        # 加载预测数据
        df = context.options['data'].read_df()
        # 函数:求满足开仓条件的股票列表
        def open_pos_con(df):
            return list(df[df['buy_condition']>0].instrument)[:10]
    
        # 函数:求满足平仓条件的股票列表
        def close_pos_con(df):
            return list(df[df['sell_condition']>0].instrument)
        
        # 每日买入股票的数据框
        context.daily_buy_stock= df.groupby('date').apply(open_pos_con)
        # 每日卖出股票的数据框
        context.daily_sell_stock= df.groupby('date').apply(close_pos_con)    
        
        
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m8_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2021-06-20',
        end_date=T.live_run_param('trading_date', '2021-07-01'),
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.input_features.v1(
        features="""
    # #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    buy_condition=where((open_0>close_1)&(mean(close_0,5)>mean(close_0,10)),1,0)
    sell_condition=where(mean(close_0,5)<mean(close_0,10),1,0)
    pe_ttm_0
    """
    )
    
    m5 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m2.data,
        start_date='',
        end_date='',
        before_start_days=60,
        m_cached=False
    )
    
    m7 = M.derived_feature_extractor.v3(
        input_data=m5.data,
        features=m2.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m9 = M.sort.v4(
        input_ds=m7.data,
        sort_by='pe_ttm_0',
        group_by='date',
        keep_columns='--',
        ascending=True
    )
    
    m8 = M.trade.v4(
        instruments=m1.data,
        options_data=m9.sorted_data,
        start_date='',
        end_date='',
        initialize=m8_initialize_bigquant_run,
        handle_data=m8_handle_data_bigquant_run,
        prepare=m8_prepare_bigquant_run,
        before_trading_start=m8_before_trading_start_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='open',
        order_price_field_sell='close',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    ==============开盘价成交  order.asset= Equity(1928 [600241.SHA]) open price= 7.2899995
    
    • 收益率-3.35%
    • 年化收益率-61.44%
    • 基准收益率2.49%
    • 阿尔法-0.48
    • 贝塔-0.48
    • 夏普比率-5.52
    • 胜率0.23
    • 盈亏比0.56
    • 收益波动率17.51%
    • 信息比率-0.43
    • 最大回撤3.66%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-da3e752f77e84014ae6321d7866a4849"}/bigcharts-data-end