复制链接
克隆策略

双均线策略+移动止损

    {"description":"实验创建于2017/8/26","graph":{"edges":[{"to_node_id":"-57:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-102:options_data","from_node_id":"-86:data"},{"to_node_id":"-86:input_data","from_node_id":"-57:data"},{"to_node_id":"-57:input_data","from_node_id":"-54:data"},{"to_node_id":"-102:instruments","from_node_id":"-62:data"}],"nodes":[{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nbuy_condition = where(close>110,1,0)\nsell_condition = where(close<=110,1,0)\nfactor1 = close/total_size\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24"}],"cacheable":false,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"-86","module_id":"BigQuantSpace.dropnan.dropnan-v1","parameters":[],"input_ports":[{"name":"input_data","node_id":"-86"}],"output_ports":[{"name":"data","node_id":"-86"}],"cacheable":true,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-57","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":"True","type":"Literal","bound_global_parameter":null},{"name":"remove_extra_columns","value":"True","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-57"},{"name":"features","node_id":"-57"}],"output_ports":[{"name":"data","node_id":"-57"}],"cacheable":true,"seq_num":8,"comment":"","comment_collapsed":true},{"node_id":"-102","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","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n\n #------------------------------------------止损模块START--------------------------------------------\n date = data.current_dt.strftime('%Y-%m-%d') \n equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n \n # 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断\n current_stoploss_stock = [] \n if len(equities) > 0:\n for i in equities.keys():\n stock_market_price = data.current(context.symbol(i), 'price') # 最新市场价格\n last_sale_date = equities[i].last_sale_date # 上次交易日期\n delta_days = data.current_dt - last_sale_date \n hold_days = delta_days.days # 持仓天数\n # 建仓以来的最高价\n highest_price_since_buy = data.history(context.symbol(i), 'high', hold_days, '1d').max()\n # 确定止损位置\n stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.1\n record('止损位置', stoploss_line)\n # 如果价格下穿止损位置\n if stock_market_price < stoploss_line:\n context.order_target_percent(context.symbol(i), 0) \n current_stoploss_stock.append(i)\n print('日期:', date , '股票:', i, '出现止损状况')\n #-------------------------------------------止损模块END--------------------------------------------------\n\n \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.portfolio.positions.items()}\n\n # 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;\n # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用\n cash_for_buy = context.portfolio.cash \n \n try:\n buy_stock = context.daily_stock_buy[today] # 当日符合买入条件的股票\n except:\n buy_stock=[] # 如果没有符合条件的股票,就设置为空\n \n try:\n sell_stock = context.daily_stock_sell[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 stock_to_adjust=[ i for i in stock_hold_now if i not in sell_stock ]\n \n # 如果有卖出信号\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\n if instrument in current_stoploss_stock:\n continue\n sid = context.symbol(instrument) # 将标的转化为equity格式\n cur_position = context.portfolio.positions[sid].amount # 持仓\n if cur_position > 0 and data.can_trade(sid):\n context.order_target_percent(sid, 0) # 全部卖出 \n # 因为设置的是早盘卖出早盘买入,需要根据卖出的股票更新可用现金;如果设置尾盘卖出早盘买入,则不需更新可用现金(可以删除下面的语句)\n cash_for_buy += stock_hold_now[instrument]\n \n # 如果有买入信号/有持仓\n if len(stock_to_buy)>0:\n weight = 1/len(set(stock_to_buy+stock_to_adjust)) # 每只股票的比重为等资金比例持有\n for instrument in set(stock_to_buy+stock_to_adjust):\n sid = context.symbol(instrument) # 将标的转化为equity格式\n if data.can_trade(sid):\n context.order_target_value(sid, weight*cash_for_buy) # 买入","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n df = m6.data.read_df()\n\n # 函数:求满足开仓条件的股票列表\n def open_pos_con(df):\n return list(df[df['buy_condition']>0].instrument)\n\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df[df['sell_condition']>0].instrument)\n\n # 每日买入股票的数据框\n context.daily_stock_buy= df.groupby('date').apply(open_pos_con)\n # 每日卖出股票的数据框\n context.daily_stock_sell= df.groupby('date').apply(close_pos_con)","type":"Literal","bound_global_parameter":null},{"name":"before_trading_start","value":"","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":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-102"},{"name":"options_data","node_id":"-102"},{"name":"history_ds","node_id":"-102"},{"name":"benchmark_ds","node_id":"-102"},{"name":"trading_calendar","node_id":"-102"}],"output_ports":[{"name":"raw_perf","node_id":"-102"}],"cacheable":false,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-54","module_id":"BigQuantSpace.datahub_load_datasource.datahub_load_datasource-v1","parameters":[{"name":"table","value":"market_performance_CN_CONBOND","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"2015-05-29","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-04-16","type":"Literal","bound_global_parameter":null},{"name":"instruments","value":"# #号开始的表示注释,注释需单独一行\n# 每行一条\n","type":"Literal","bound_global_parameter":null},{"name":"fields","value":"# #号开始的表示注释,注释需单独一行\n# 每行一条\nconversion_chg_pct_week\nbond_prem_ratio\npure_bond_ratio\nclose_equ\nremain_size\nclose\ntotal_size","type":"Literal","bound_global_parameter":null}],"input_ports":[],"output_ports":[{"name":"data","node_id":"-54"}],"cacheable":false,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-62","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2015-05-29","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-04-16","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_CONBOND","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":"-62"}],"output_ports":[{"name":"data","node_id":"-62"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='1141.1865844726562,-73.16772174835205,200,200'/><node_position Node='-86' Position='1078,418,200,200'/><node_position Node='-57' Position='1076,327,200,200'/><node_position Node='-102' Position='1048,529,200,200'/><node_position Node='-54' Position='928.1172485351562,34.537200927734375,200,200'/><node_position Node='-62' Position='793,190,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [22]:
    # 本代码由可视化策略环境自动生成 2022年4月19日 20:10
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    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):
    
        #------------------------------------------止损模块START--------------------------------------------
        date = data.current_dt.strftime('%Y-%m-%d')  
        equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
        
        # 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
        current_stoploss_stock = [] 
        if len(equities) > 0:
            for i in equities.keys():
                stock_market_price = data.current(context.symbol(i), 'price')  # 最新市场价格
                last_sale_date = equities[i].last_sale_date   # 上次交易日期
                delta_days = data.current_dt - last_sale_date  
                hold_days = delta_days.days # 持仓天数
                # 建仓以来的最高价
                highest_price_since_buy = data.history(context.symbol(i), 'high', hold_days, '1d').max()
                # 确定止损位置
                stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.1
                record('止损位置', stoploss_line)
                # 如果价格下穿止损位置
                if stock_market_price < stoploss_line:
                    context.order_target_percent(context.symbol(i), 0)     
                    current_stoploss_stock.append(i)
                    print('日期:', date , '股票:', i, '出现止损状况')
        #-------------------------------------------止损模块END--------------------------------------------------
    
           
        # 获取今日的日期
        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.portfolio.positions.items()}
    
        # 记录用于买入股票的可用现金,因为是早盘卖股票,需要记录卖出的股票市值并在买入下单前更新可用现金;
        # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
        cash_for_buy = context.portfolio.cash    
        
        try:
            buy_stock = context.daily_stock_buy[today]  # 当日符合买入条件的股票
        except:
            buy_stock=[]  # 如果没有符合条件的股票,就设置为空
        
        try:
            sell_stock = context.daily_stock_sell[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 ]  
        # 需要调仓的股票:已有持仓且不符合卖出条件的股票
        stock_to_adjust=[ i for i in stock_hold_now if i not in sell_stock ]
        
        # 如果有卖出信号
        if len(stock_to_sell)>0:
            for instrument in stock_to_sell:
                if instrument in current_stoploss_stock:
                    continue
                sid = context.symbol(instrument) # 将标的转化为equity格式
                cur_position = context.portfolio.positions[sid].amount # 持仓
                if cur_position > 0 and data.can_trade(sid):
                    context.order_target_percent(sid, 0) # 全部卖出 
                    # 因为设置的是早盘卖出早盘买入,需要根据卖出的股票更新可用现金;如果设置尾盘卖出早盘买入,则不需更新可用现金(可以删除下面的语句)
                    cash_for_buy += stock_hold_now[instrument]
        
        # 如果有买入信号/有持仓
        if len(stock_to_buy)>0:
            weight = 1/len(set(stock_to_buy+stock_to_adjust)) # 每只股票的比重为等资金比例持有
            for instrument in set(stock_to_buy+stock_to_adjust):
                sid = context.symbol(instrument) # 将标的转化为equity格式
                if  data.can_trade(sid):
                    context.order_target_value(sid, weight*cash_for_buy) # 买入
    # 回测引擎:准备数据,只执行一次
    def m3_prepare_bigquant_run(context):
        # 加载预测数据
        df = m6.data.read_df()
    
        # 函数:求满足开仓条件的股票列表
        def open_pos_con(df):
            return list(df[df['buy_condition']>0].instrument)
    
        # 函数:求满足平仓条件的股票列表
        def close_pos_con(df):
            return list(df[df['sell_condition']>0].instrument)
    
        # 每日买入股票的数据框
        context.daily_stock_buy= df.groupby('date').apply(open_pos_con)
        # 每日卖出股票的数据框
        context.daily_stock_sell= df.groupby('date').apply(close_pos_con)
    
    m1 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    buy_condition = where(close>110,1,0)
    sell_condition = where(close<=110,1,0)
    factor1 = close/total_size
    """,
        m_cached=False
    )
    
    m4 = M.datahub_load_datasource.v1(
        table='market_performance_CN_CONBOND',
        start_date='2015-05-29',
        end_date='2022-04-16',
        instruments="""# #号开始的表示注释,注释需单独一行
    # 每行一条
    """,
        fields="""# #号开始的表示注释,注释需单独一行
    # 每行一条
    conversion_chg_pct_week
    bond_prem_ratio
    pure_bond_ratio
    close_equ
    remain_size
    close
    total_size"""
    )
    
    m8 = M.derived_feature_extractor.v3(
        input_data=m4.data,
        features=m1.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=True,
        remove_extra_columns=True
    )
    
    m6 = M.dropnan.v1(
        input_data=m8.data
    )
    
    m2 = M.instruments.v2(
        start_date='2015-05-29',
        end_date='2022-04-16',
        market='CN_CONBOND',
        instrument_list='',
        max_count=0
    )
    
    m3 = M.trade.v4(
        instruments=m2.data,
        options_data=m6.data,
        start_date='',
        end_date='',
        initialize=m3_initialize_bigquant_run,
        handle_data=m3_handle_data_bigquant_run,
        prepare=m3_prepare_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=''
    )
    

    读取数据(DataSource) 数据统计 (前 268583 行) </font></font>

    date close conversion_chg_pct_week instrument close_equ total_size pure_bond_ratio bond_prem_ratio remain_size
    count(Nan) 0 0 2967 0 0 0 2080 0 0
    type datetime64[ns] float32 float32 object float32 float32 float64 float32 float32

    读取数据(DataSource) 数据预览 (前 5 行) </font></font>

    date close conversion_chg_pct_week instrument close_equ total_size pure_bond_ratio bond_prem_ratio remain_size
    0 2015-05-29 100.000000 0.000000 117005.ZCB 25.200001 2.16 108.365476 -28.571400 2.160000
    1 2015-05-29 128.520004 -0.035280 110023.HCB 10.020000 200.00 101.366477 3.957500 181.849014
    2 2015-05-29 165.500000 0.131160 110029.HCB 11.940000 100.00 99.999999 -21.546900 0.000000
    3 2015-05-29 237.639999 0.256557 110030.HCB 35.930000 9.80 87.784124 38.231998 9.800000
    4 2015-05-29 261.589996 0.162622 113008.HCB 21.680000 60.00 88.271955 29.347000 60.000000
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-22-37ba9a07e46a> in <module>
        150 )
        151 
    --> 152 m3 = M.trade.v4(
        153     instruments=m2.data,
        154     options_data=m6.data,
    
    TypeError: Can only merge Series or DataFrame objects, a <class 'NoneType'> was passed
    In [24]:
    df = m6.data.read_df().groupby('i')
    
    In [ ]: