复制链接
克隆策略

多条件选股策略

版本 v1.0

目录

  • ### 多条件选股策略的交易规则

  • ### 策略构建步骤

  • ### 策略的实现

正文

一、多条件选股策略的交易规则

  • 买入条件:满足 1)今日开盘价大于昨日收盘价;2)5日收盘价均线大于10日收盘价均线,按PE升序排名取前十名,次日以开盘价买入;
  • 买入后,如果5日收盘价均线小于10日收盘价均线,则次日以开盘价卖出。

二、策略构建步骤

1、确定股票池和回测时间

  • 通过证券代码列表输入要回测的单只/多只股票,以及回测的起止日期

2、确定买卖条件信号

  • 在输入特征列表中通过表达式引擎定义 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),实现卖出信号。
  • 通过基础特征和衍生特征抽取模块实现买卖条件指标 buy_condition 和 sell_condition 数据的抽取。
  • 通过缺失数据处理模块删去有缺失值的数据。

3、确定买卖原则

  • 已有持仓中满足卖出条件的股票为卖出股票列表,需执行卖出操作并更新可用现金。
  • 满足买入条件且没有持仓的股票为买入股票列表,需根据可用现金执行等资金买入操作,此例采用整百股数下单。

4、模拟回测

  • 通过 trade 模块中的初始化函数定义交易手续费和滑点;
  • 通过 trade 模块中的准备函数定义 context.daily_stock_buy 和 context.daily_stock_sell 变量来获取并存放每日符合买卖条件的股票列表;
  • 通过 trade 模块中的主函数(handle函数)查看每日的买卖交易信号,按照买卖原则执行相应的买入/卖出操作。

三、策略的实现

可视化策略实现如下:

    {"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-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-01-31","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","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 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":"open","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":"000300.HIX","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='153.28524780273438,112.1507339477539,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='195,549,200,200'/><node_position Node='-390' Position='291,437,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [1]:
    # 本代码由可视化策略环境自动生成 2023年1月11日 18:41
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m8_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    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,即卖出全部股票,可参考回测文档
                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-01-01',
        end_date=T.live_run_param('trading_date', '2022-01-31'),
        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='open',
        capital_base=1000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark='000300.HIX'
    )
    
    • 收益率19.89%
    • 年化收益率19.06%
    • 基准收益率-12.43%
    • 阿尔法0.29
    • 贝塔0.48
    • 夏普比率0.66
    • 胜率0.34
    • 盈亏比2.43
    • 收益波动率27.76%
    • 信息比率0.07
    • 最大回撤15.52%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-1b050f67adb7489a9af0cafa917f2808"}/bigcharts-data-end
    In [2]:
    m8.read_raw_perf().to_csv("多条件选股.csv")