复制链接
克隆策略

    {"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":"-1372:input_1","from_node_id":"-353:data"},{"to_node_id":"-865:input_data","from_node_id":"-360:data"},{"to_node_id":"-531:input_data","from_node_id":"-390:sorted_data"},{"to_node_id":"-370:options_data","from_node_id":"-531:data"},{"to_node_id":"-93:input_data","from_node_id":"-865:data"},{"to_node_id":"-390:input_ds","from_node_id":"-93:data"},{"to_node_id":"-443:input_data","from_node_id":"-220:data"},{"to_node_id":"-220:instruments","from_node_id":"-226:data"},{"to_node_id":"-220:features","from_node_id":"-234:data"},{"to_node_id":"-443:features","from_node_id":"-234:data"},{"to_node_id":"-2883:input_1","from_node_id":"-443:data"},{"to_node_id":"-360:input_data","from_node_id":"-1372:data"},{"to_node_id":"-2883:input_2","from_node_id":"-2864:data"},{"to_node_id":"-2864:instruments","from_node_id":"-2870:data"},{"to_node_id":"-2864:features","from_node_id":"-2878:data"},{"to_node_id":"-1372:input_2","from_node_id":"-2883:data"}],"nodes":[{"node_id":"-51","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2020-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2022-02-23","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":"isXiaDie0=where((return_0<1),1,0)\n#当天A股下跌数\nxd_num=group_sum(date, isXiaDie0)\nisZhangtToday=where((return_0>1.09)&(close_0==high_0),1,0)\nisDietToday=where((return_0<0.91)&(close_0==low_0),1,0)\nreturn0=return_0\npriceLowBl10=close_0/ts_min(close_0,10)\nzgzzf=high_0/close_1\nzdzzf=low_0/close_1\nkp1=(open_0-close_1)/close_1\nkp=shift((open_0-close_1)/close_1,-1)\nzd=shift((low_0-close_1)/close_1,-1)\nzg=shift((high_0-close_1)/close_1,-1)\n\n#逻辑一:大盘大跌情况下的涨停票后续效果\n#myls=where((xd_num>3500)&(isZhangtToday==1),1,0)\n#逻辑二:大盘大跌情况下的跌停票后续效果\n#myls=where((xd_num>3500)&(isDietToday==1),1,0)\n#逻辑三:大盘大跌情况下的跌停票后续效果,精选个股\nmyls=where((xd_num>3500)&(isDietToday==1)&(priceLowBl10<1.05)&(kp1>-0.05),1,0)\n\nshouyi=(shift(open_0,-2)-shift(open_0,-1))/shift(open_0,-1)\nshouyi2=(shift(close_0,-2)-shift(open_0,-1))/shift(open_0,-1)\n\nkp=where((kp<-0.096),1,kp)\n#zhangf=(close_0-open_0)/open_0\n\n#附合这个选股逻辑,第二天开盘执行买入\nbuy_condition=where(myls==1,1,0)\n#卖出不做特别处理,按三天收盘执行卖出\nsell_condition=where(myls==2,1,0)","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":"0","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":"True","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 # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n context.stock_count = 1\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 每只股票的权重平均分配\n context.stock_weights = 1/context.stock_count\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 1\n context.options['hold_days'] = 0\n\n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n today = 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 stock_now = len(equities); #获取当前持仓股票数量\n stock_count = context.stock_count\n \n # 按日期过滤得到今日的预测数据\n # 加载预测数据\n df = context.options['data'].read_df()\n df_today = df[df.date == data.current_dt.strftime('%Y-%m-%d')]\n df_today.set_index('instrument')\n \n \n\n #------------------------------------------止损模块START--------------------------------------------\n \n # 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断\n stoploss_stock = []\n stopwin_stock = []\n now_stock = []\n if len(equities) > 0:\n for i in equities.keys():\n now_stock.append(i)\n try :\n amount_zfs=list(df_today[df_today.instrument==i]['amount_zf'])\n amount_zf=amount_zfs[0]\n amount_bls=list(df_today[df_today.instrument==i]['amount_bl'])\n amount_bl=amount_bls[0]\n mc1s=list(df_today[df_today.instrument==i]['mc1'])\n mc1=mc1s[0]\n mc3s=list(df_today[df_today.instrument==i]['mc3'])\n mc3=mc3s[0]\n mc4s=list(df_today[df_today.instrument==i]['mc4'])\n mc4=mc4s[0]\n gzxzs=list(df_today[df_today.instrument==i]['gzxz'])\n gzxz=gzxzs[0]\n hasMdins=list(df_today[df_today.instrument==i]['hasMdin'])\n hasMdin=hasMdins[0]\n d2s=list(df_today[df_today.instrument==i]['d2'])\n d2=d2s[0]\n except :\n amount_bl=0\n amount_zf=0\n mc1=0\n gzxz=0\n mc3=0\n mc4=0\n hasMdin=0\n d2=0\n stock_market_price = data.current(context.symbol(i), 'price') # 最新市场价格\n stock_market_today_high = data.current(context.symbol(i), 'high') #今日最高价 \n stock_market_today_close = data.current(context.symbol(i), 'close') #今日收盘价\n last_sale_date = equities[i].last_sale_date # 上次交易日期\n last_cost_price = equities[i].cost_basis # 上次交易金额\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 highclose_price_since_buy = data.history(context.symbol(i), 'close', hold_days, '1d').max()\n # 确定止损位置\n stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.05\n \n # 确定止盈位置\n stopwin_line = last_cost_price * 1.1\n # 最高收益\n high_return = (highclose_price_since_buy-last_cost_price)/last_cost_price\n # 今日回落(最高价-收盘价)/收盘价\n hui_luo = (stock_market_today_high - stock_market_price)/stock_market_price\n if(i=='603909.SHA'):\n print('日期:',today,'high_return:',high_return) \n #record('止损位置', stoploss_line)\n # 如果价格下穿止损位置\n if stock_market_price < stoploss_line:\n if(i=='002735.SZA'):\n print('日期:',today,'最高价:',highest_price_since_buy)\n print('日期:',today,'止损价:',stoploss_line)\n print('日期:',today,'当前价:',stock_market_price)\n print('日期:',today,'建仓价:',last_cost_price)\n #context.order_target_percent(context.symbol(i), 0)\n context.order_target(context.symbol(i), 0)\n stoploss_stock.append(i)\n stock_now = stock_now -1\n #收益达6个点后,冲高回落时卖出\n elif high_return>0.06 and hui_luo>0.04 and amount_zf<1.5 and amount_bl<2:\n context.order_target(context.symbol(i), 0)\n stoploss_stock.append(i)\n stock_now = stock_now -1\n print('日期:', today, '股票:', context.symbol(i), 'huiluo:',hui_luo,'high_return:',high_return)\n print('日期:', today, '股票:', i, '出现冲高回落止损状况')\n #当天涨幅或相对前一天涨幅大于5个点,且成交量下降时卖出\n elif mc1==1 :\n context.order_target(context.symbol(i), 0)\n stoploss_stock.append(i)\n stock_now = stock_now -1\n print('日期:', today, '股票:', i, '大涨且成交量下降时卖出')\n #大涨后,出现高幅振汤且小涨卖出\n elif high_return>0.06 and gzxz==1 :\n context.order_target(context.symbol(i), 0)\n stoploss_stock.append(i)\n stock_now = stock_now -1\n print('日期:', today, '股票:', i, '大涨后出现高振小涨卖出')\n #大涨后,出现下跌时卖出\n elif mc3==1 and high_return>0.08:\n context.order_target(context.symbol(i), 0)\n stoploss_stock.append(i)\n stock_now = stock_now -1\n print('日期:', today, '股票:', i, '大涨后小跌时卖出')\n #高振幅小涨时卖出\n elif mc4==1:\n context.order_target(context.symbol(i), 0)\n stoploss_stock.append(i)\n stock_now = stock_now -1\n print('日期:', today, '股票:', i, '高振幅小涨时卖出')\n elif hasMdin==1: \n #获取M顶的最大值\n if(i=='002633.SZA'):\n mDinValue = data.history(context.symbol(i), 'close',29-int(d2), '1d')[0]\n #M顶出现后的最高值\n mDinLaterMax = data.history(context.symbol(i), 'close',29-int(d2), '1d').max()\n print('日期:', today, '股票:', i, 'M顶值为:',mDinValue,'M顶后的最大值:',mDinLaterMax)\n \n #elif stock_market_price > stopwin_line:\n # context.order_target(context.symbol(i), 0)\n # stopwin_stock.append(i)\n # stock_now = stock_now -1\n if len(stoploss_stock)>0:\n print('日期:', today, '股票:', stoploss_stock, '出现跟踪止损状况')\n #if len(stopwin_stock)>0:\n # print('日期:', today, '股票:', stopwin_stock, '出现跟踪止盈状况')\n \n #-------------------------------------------止损模块END--------------------------------------------- \n \n try:\n buy_list = context.daily_buy_stock[today]\n except:\n buy_list = []\n\n \n # 1. 资金分配\n #is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天) \n stock_cash = context.portfolio.portfolio_value/stock_count\n #cash_avg = context.portfolio.portfolio_value\n #cash_for_buy = min(context.portfolio.cash, stock_cash)\n #cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n \n positions = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items()}\n \n # 2. 生成卖出订单:hold_days天之后才开始卖出;\n try:\n sell_stock_list = context.daily_sell_stock[today] # 当日符合卖出条件的股票\n except:\n sell_stock_list = []\n # 需要卖出的股票:已有持仓中符合卖出条件的股票\n stock_to_sell = [i for i in positions if i in sell_stock_list]\n #print('日期:', today, '股票:', stock_to_sell, '需要卖出的股票')\n sell_stock = []\n \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(context.symbol(instrument), 0)\n sell_stock.append(instrument)\n stock_now = stock_now -1\n if(instrument=='002735.SZA'):\n print('日期:',today,'卖出1:',instrument)\n \n #if not is_staging :\n if 1==1 : \n if len(equities) > 0:\n for i in equities.keys():\n last_sale_date = equities[i].last_sale_date\t# 上次交易日期\n delta_days = data.current_dt - last_sale_date \n hold_days = delta_days.days # 持仓天数\n print('日期:',today,'hold_days:',hold_days,'股票:',i)\n if hold_days >= context.options['hold_days'] and i not in buy_list + stoploss_stock + stopwin_stock + sell_stock:\n print('日期:',today,'卖出2:',i)\n context.order_target(context.symbol(i), 0)\n sell_stock.append(i)\n stock_now = stock_now -1\n if(i=='002735.SZA'):\n print('日期:',today,'卖出2:',i)\n #print('日期:', today, '股票:', i, ' 卖出')\n \n# 3. 生成买入订单\n buy_num = stock_count - stock_now\n #if is_staging :\n # buy_num = 1\n if len(buy_list)>0:\n print('日期:', today, '选出股票数量:', len(buy_list))\n if buy_num>0 and len(buy_list)>0 :\n # 不再买入已经轮仓卖出和移动止损的股票,以防止出现空头持仓\n buy_instruments = [i for i in buy_list if i not in sell_stock + stoploss_stock + stopwin_stock + now_stock][:buy_num]\n for i, instrument in enumerate(buy_instruments):\n current_price = data.current(context.symbol(instrument), 'price')\n #过滤不买入的\n try :\n hasMdins=list(df_today[df_today.instrument==instrument]['hasMdin'])\n hasMdin=hasMdins[0]\n d2s=list(df_today[df_today.instrument==instrument]['d2'])\n d2=d2s[0]\n zs_a1=list(df_today[df_today.instrument==instrument]['zs_a1'])[0]\n zs_a2=list(df_today[df_today.instrument==instrument]['zs_a2'])[0]\n zs_bmy1=list(df_today[df_today.instrument==instrument]['zs_bmy1'])[0] \n except :\n hasMdin=0\n d2=0\n zs_bmy1=0\n # bmy4=0\n if hasMdin==1: #需要优化M顶的逻辑\n mDinValue = data.history(context.symbol(instrument), 'close',29-int(d2), '1d')[0]\n #M顶出现后的最高值\n mDinLaterMax = data.history(context.symbol(instrument), 'close',29-int(d2), '1d').max()\n mDinLaterMin = data.history(context.symbol(instrument), 'close',29-int(d2), '1d').min()\n #当出现了M顶,且M顶未被突破,当前的价格低于M顶,且当前价格接近M顶的位置,不买入\n if mDinLaterMax/mDinValue<1.03 and current_price<mDinValue and mDinValue/current_price<1.04 and mDinValue/mDinLaterMin>1.07:\n print('日期:',today,'买入时过滤有顶部压力的股票:',instrument)\n continue\n if zs_bmy1==3:\n print('日期:',today,'买入时过滤指数不买入股票:',instrument,'指数a1:',zs_a1,'指数a2:',zs_a2)\n #continue\n cash_for_buy = min(context.portfolio.cash, stock_cash)\n if cash_for_buy>0 and data.can_trade(context.symbol(instrument)): \n amount = math.floor(cash_for_buy / current_price / 100) * 100\n context.order(context.symbol(instrument), amount)\n #if(instrument=='002735.SZA'):\n print('日期:',today,'买入:',instrument)\n else :\n print('日期:',today,'无资金或不能交易未买入:',instrument)","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)\n # 函数:求满足平仓条件的股票列表\n def close_pos_con(df):\n return list(df[df['sell_condition']>0].instrument)\n \n # 每日卖出股票的数据框\n context.daily_sell_stock= df.groupby('date').apply(close_pos_con) \n # 每日买入股票的数据框\n context.daily_buy_stock= df.groupby('date').apply(open_pos_con) \n\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":"200000","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":"kp","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_id":"-531","module_id":"BigQuantSpace.filter.filter-v3","parameters":[{"name":"expr","value":"myls==1","type":"Literal","bound_global_parameter":null},{"name":"output_left_data","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-531"}],"output_ports":[{"name":"data","node_id":"-531"},{"name":"left_data","node_id":"-531"}],"cacheable":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"-865","module_id":"BigQuantSpace.chinaa_stock_filter.chinaa_stock_filter-v1","parameters":[{"name":"index_constituent_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%8150%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22displayValue%22%3A%22%E6%B2%AA%E6%B7%B1300%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81500%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81800%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81180%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22displayValue%22%3A%22%E4%B8%AD%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81100%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"board_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E4%B8%8A%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22displayValue%22%3A%22%E6%B7%B1%E8%AF%81%E4%B8%BB%E6%9D%BF%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22displayValue%22%3A%22%E5%88%9B%E4%B8%9A%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%A7%91%E5%88%9B%E6%9D%BF%22%2C%22displayValue%22%3A%22%E7%A7%91%E5%88%9B%E6%9D%BF%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"industry_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22displayValue%22%3A%22%E4%BA%A4%E9%80%9A%E8%BF%90%E8%BE%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%91%E9%97%B2%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22displayValue%22%3A%22%E4%BC%A0%E5%AA%92%2F%E4%BF%A1%E6%81%AF%E6%9C%8D%E5%8A%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22displayValue%22%3A%22%E5%85%AC%E7%94%A8%E4%BA%8B%E4%B8%9A%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22displayValue%22%3A%22%E5%86%9C%E6%9E%97%E7%89%A7%E6%B8%94%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%8C%96%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22displayValue%22%3A%22%E5%8C%BB%E8%8D%AF%E7%94%9F%E7%89%A9%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22displayValue%22%3A%22%E5%95%86%E4%B8%9A%E8%B4%B8%E6%98%93%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22displayValue%22%3A%22%E5%9B%BD%E9%98%B2%E5%86%9B%E5%B7%A5%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22displayValue%22%3A%22%E5%AE%B6%E7%94%A8%E7%94%B5%E5%99%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E6%9D%90%E6%96%99%2F%E5%BB%BA%E7%AD%91%E5%BB%BA%E6%9D%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22displayValue%22%3A%22%E5%BB%BA%E7%AD%91%E8%A3%85%E9%A5%B0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22displayValue%22%3A%22%E6%88%BF%E5%9C%B0%E4%BA%A7%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22displayValue%22%3A%22%E6%9C%89%E8%89%B2%E9%87%91%E5%B1%9E%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%9C%BA%E6%A2%B0%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E6%B1%BD%E8%BD%A6%2F%E4%BA%A4%E8%BF%90%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22displayValue%22%3A%22%E7%94%B5%E5%AD%90%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22displayValue%22%3A%22%E7%94%B5%E6%B0%94%E8%AE%BE%E5%A4%87%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22displayValue%22%3A%22%E7%BA%BA%E7%BB%87%E6%9C%8D%E8%A3%85%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22displayValue%22%3A%22%E7%BB%BC%E5%90%88%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22displayValue%22%3A%22%E8%AE%A1%E7%AE%97%E6%9C%BA%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22displayValue%22%3A%22%E8%BD%BB%E5%B7%A5%E5%88%B6%E9%80%A0%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22displayValue%22%3A%22%E9%80%9A%E4%BF%A1%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%87%87%E6%8E%98%22%2C%22displayValue%22%3A%22%E9%87%87%E6%8E%98%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%92%A2%E9%93%81%22%2C%22displayValue%22%3A%22%E9%92%A2%E9%93%81%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22displayValue%22%3A%22%E9%93%B6%E8%A1%8C%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22displayValue%22%3A%22%E9%9D%9E%E9%93%B6%E9%87%91%E8%9E%8D%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22displayValue%22%3A%22%E9%A3%9F%E5%93%81%E9%A5%AE%E6%96%99%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"st_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22displayValue%22%3A%22%E6%AD%A3%E5%B8%B8%22%2C%22selected%22%3Atrue%7D%2C%7B%22value%22%3A%22ST%22%2C%22displayValue%22%3A%22ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22*ST%22%2C%22displayValue%22%3A%22*ST%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22displayValue%22%3A%22%E6%9A%82%E5%81%9C%E4%B8%8A%E5%B8%82%22%2C%22selected%22%3Afalse%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"delist_cond","value":"%7B%22enumItems%22%3A%5B%7B%22value%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22displayValue%22%3A%22%E5%85%A8%E9%83%A8%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%80%80%E5%B8%82%22%2C%22displayValue%22%3A%22%E9%80%80%E5%B8%82%22%2C%22selected%22%3Afalse%7D%2C%7B%22value%22%3A%22%E9%9D%9E%E9%80%80%E5%B8%82%22%2C%22displayValue%22%3A%22%E9%9D%9E%E9%80%80%E5%B8%82%22%2C%22selected%22%3Atrue%7D%5D%7D","type":"Literal","bound_global_parameter":null},{"name":"output_left_data","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-865"}],"output_ports":[{"name":"data","node_id":"-865"},{"name":"left_data","node_id":"-865"}],"cacheable":true,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-93","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-93"},{"name":"features","node_id":"-93"}],"output_ports":[{"name":"data","node_id":"-93"}],"cacheable":true,"seq_num":11,"comment":"","comment_collapsed":true},{"node_id":"-220","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"bar1d_index_CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-220"},{"name":"features","node_id":"-220"}],"output_ports":[{"name":"data","node_id":"-220"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-226","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2010-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-12-30","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"000002.HIX","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-226"}],"output_ports":[{"name":"data","node_id":"-226"}],"cacheable":true,"seq_num":10,"comment":"","comment_collapsed":true},{"node_id":"-234","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nzs_zhangf=(close-open)/open\nzs_open=open/shift(close,1)\nzs_huiluo=(high-close)/close\nzs_huishen=(close-low)/low\nzs_zhenf=(high-low)/shift(close,1)\nzs_volume_zf=volume/shift(volume,1)\nzs_return_0=close/shift(close,1)\nzs_return_1=shift(zs_return_0,1)\nzs_return_2=shift(zs_return_0,2)\nzs_max10=ts_max(close,10)\nzs_max10d=ts_argmax(close,10)\nzs_max30=ts_max(close,30)\n#zs_max30d=ts_argmax(close,30)\nzs_min10=ts_min(close,10)\n#zs_min10d=ts_argmin(close,10)\nzs_min30=ts_min(close,30)\n#zs_min30d=ts_argmin(close,30)\nzs_priceHighBl10=close/zs_max10\nzs_priceLowBl10=close/zs_min10\nzs_priceHighBl30=close/zs_max30\nzs_priceLowBl30=close/zs_min30","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-234"}],"output_ports":[{"name":"data","node_id":"-234"}],"cacheable":true,"seq_num":12,"comment":"","comment_collapsed":true},{"node_id":"-443","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":"True","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-443"},{"name":"features","node_id":"-443"}],"output_ports":[{"name":"data","node_id":"-443"}],"cacheable":true,"seq_num":13,"comment":"","comment_collapsed":true},{"node_id":"-1372","module_id":"BigQuantSpace.data_join.data_join-v3","parameters":[{"name":"on","value":"date","type":"Literal","bound_global_parameter":null},{"name":"how","value":"left","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-1372"},{"name":"input_2","node_id":"-1372"}],"output_ports":[{"name":"data","node_id":"-1372"}],"cacheable":true,"seq_num":14,"comment":"","comment_collapsed":true},{"node_id":"-2864","module_id":"BigQuantSpace.use_datasource.use_datasource-v1","parameters":[{"name":"datasource_id","value":"bar1d_index_CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"start_date","value":"","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-2864"},{"name":"features","node_id":"-2864"}],"output_ports":[{"name":"data","node_id":"-2864"}],"cacheable":true,"seq_num":17,"comment":"","comment_collapsed":true},{"node_id":"-2870","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2020-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2020-12-30","type":"Literal","bound_global_parameter":null},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"000002.HIX","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":0,"type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"-2870"}],"output_ports":[{"name":"data","node_id":"-2870"}],"cacheable":true,"seq_num":18,"comment":"","comment_collapsed":true},{"node_id":"-2878","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"\n# #号开始的表示注释,注释需单独一行\n# 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征\nclose\n","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-2878"}],"output_ports":[{"name":"data","node_id":"-2878"}],"cacheable":true,"seq_num":19,"comment":"","comment_collapsed":true},{"node_id":"-2883","module_id":"BigQuantSpace.data_join.data_join-v3","parameters":[{"name":"on","value":"date","type":"Literal","bound_global_parameter":null},{"name":"how","value":"left","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-2883"},{"name":"input_2","node_id":"-2883"}],"output_ports":[{"name":"data","node_id":"-2883"}],"cacheable":true,"seq_num":20,"comment":"","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='-51' Position='76,91,200,200'/><node_position Node='-59' Position='448,31,200,200'/><node_position Node='-353' Position='427,203,200,200'/><node_position Node='-360' Position='274,348,200,200'/><node_position Node='-370' Position='362,922,200,200'/><node_position Node='-390' Position='290,615,200,200'/><node_position Node='-531' Position='355,761,200,200'/><node_position Node='-865' Position='583,453,200,200'/><node_position Node='-93' Position='266,521,200,200'/><node_position Node='-220' Position='801,-38,200,200'/><node_position Node='-226' Position='664,-179,200,200'/><node_position Node='-234' Position='1057,-181,200,200'/><node_position Node='-443' Position='806,119,200,200'/><node_position Node='-1372' Position='784,320,200,200'/><node_position Node='-2864' Position='1340,90,200,200'/><node_position Node='-2870' Position='1137,-23,200,200'/><node_position Node='-2878' Position='1530,-25,200,200'/><node_position Node='-2883' Position='1092,261,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [1]:
    # 本代码由可视化策略环境自动生成 2022年3月1日 17:54
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # 回测引擎:初始化函数,只执行一次
    def m8_initialize_bigquant_run(context):
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        context.stock_count = 1
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])
        # 每只股票的权重平均分配
        context.stock_weights = 1/context.stock_count
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 1
        context.options['hold_days'] = 0
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m8_handle_data_bigquant_run(context, data):
        today = data.current_dt.strftime('%Y-%m-%d')
        equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
        stock_now = len(equities); #获取当前持仓股票数量
        stock_count = context.stock_count
        
        # 按日期过滤得到今日的预测数据
        # 加载预测数据
        df = context.options['data'].read_df()
        df_today = df[df.date == data.current_dt.strftime('%Y-%m-%d')]
        df_today.set_index('instrument')
        
        
    
        #------------------------------------------止损模块START--------------------------------------------
        
        # 新建当日止损股票列表是为了handle_data 策略逻辑部分不再对该股票进行判断
        stoploss_stock = []
        stopwin_stock = []
        now_stock = []
        if len(equities) > 0:
            for i in equities.keys():
                now_stock.append(i)
                try :
                    amount_zfs=list(df_today[df_today.instrument==i]['amount_zf'])
                    amount_zf=amount_zfs[0]
                    amount_bls=list(df_today[df_today.instrument==i]['amount_bl'])
                    amount_bl=amount_bls[0]
                    mc1s=list(df_today[df_today.instrument==i]['mc1'])
                    mc1=mc1s[0]
                    mc3s=list(df_today[df_today.instrument==i]['mc3'])
                    mc3=mc3s[0]
                    mc4s=list(df_today[df_today.instrument==i]['mc4'])
                    mc4=mc4s[0]
                    gzxzs=list(df_today[df_today.instrument==i]['gzxz'])
                    gzxz=gzxzs[0]
                    hasMdins=list(df_today[df_today.instrument==i]['hasMdin'])
                    hasMdin=hasMdins[0]
                    d2s=list(df_today[df_today.instrument==i]['d2'])
                    d2=d2s[0]
                except :
                    amount_bl=0
                    amount_zf=0
                    mc1=0
                    gzxz=0
                    mc3=0
                    mc4=0
                    hasMdin=0
                    d2=0
                stock_market_price = data.current(context.symbol(i), 'price')  # 最新市场价格
                stock_market_today_high = data.current(context.symbol(i), 'high') #今日最高价      
                stock_market_today_close = data.current(context.symbol(i), 'close') #今日收盘价
                last_sale_date = equities[i].last_sale_date   # 上次交易日期
                last_cost_price = equities[i].cost_basis # 上次交易金额
                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()
                # 建仓以来的收盘价的最高价
                highclose_price_since_buy = data.history(context.symbol(i), 'close', hold_days, '1d').max()
                # 确定止损位置
                stoploss_line = highest_price_since_buy - highest_price_since_buy * 0.05
                
                # 确定止盈位置
                stopwin_line = last_cost_price * 1.1
                # 最高收益
                high_return = (highclose_price_since_buy-last_cost_price)/last_cost_price
                # 今日回落(最高价-收盘价)/收盘价
                hui_luo = (stock_market_today_high - stock_market_price)/stock_market_price
                if(i=='603909.SHA'):
                    print('日期:',today,'high_return:',high_return)   
                #record('止损位置', stoploss_line)
                # 如果价格下穿止损位置
                if stock_market_price < stoploss_line:
                    if(i=='002735.SZA'):
                        print('日期:',today,'最高价:',highest_price_since_buy)
                        print('日期:',today,'止损价:',stoploss_line)
                        print('日期:',today,'当前价:',stock_market_price)
                        print('日期:',today,'建仓价:',last_cost_price)
                    #context.order_target_percent(context.symbol(i), 0)
                    context.order_target(context.symbol(i), 0)
                    stoploss_stock.append(i)
                    stock_now = stock_now -1
                #收益达6个点后,冲高回落时卖出
                elif high_return>0.06 and hui_luo>0.04 and amount_zf<1.5 and amount_bl<2:
                    context.order_target(context.symbol(i), 0)
                    stoploss_stock.append(i)
                    stock_now = stock_now -1
                    print('日期:', today, '股票:', context.symbol(i), 'huiluo:',hui_luo,'high_return:',high_return)
                    print('日期:', today, '股票:', i, '出现冲高回落止损状况')
                #当天涨幅或相对前一天涨幅大于5个点,且成交量下降时卖出
                elif mc1==1 :
                    context.order_target(context.symbol(i), 0)
                    stoploss_stock.append(i)
                    stock_now = stock_now -1
                    print('日期:', today, '股票:', i, '大涨且成交量下降时卖出')
                #大涨后,出现高幅振汤且小涨卖出
                elif high_return>0.06 and gzxz==1 :
                    context.order_target(context.symbol(i), 0)
                    stoploss_stock.append(i)
                    stock_now = stock_now -1
                    print('日期:', today, '股票:', i, '大涨后出现高振小涨卖出')
                #大涨后,出现下跌时卖出
                elif mc3==1 and high_return>0.08:
                    context.order_target(context.symbol(i), 0)
                    stoploss_stock.append(i)
                    stock_now = stock_now -1
                    print('日期:', today, '股票:', i, '大涨后小跌时卖出')
                #高振幅小涨时卖出
                elif mc4==1:
                    context.order_target(context.symbol(i), 0)
                    stoploss_stock.append(i)
                    stock_now = stock_now -1
                    print('日期:', today, '股票:', i, '高振幅小涨时卖出')
                elif hasMdin==1:   
                    #获取M顶的最大值
                    if(i=='002633.SZA'):
                        mDinValue = data.history(context.symbol(i), 'close',29-int(d2), '1d')[0]
                        #M顶出现后的最高值
                        mDinLaterMax = data.history(context.symbol(i), 'close',29-int(d2), '1d').max()
                        print('日期:', today, '股票:', i, 'M顶值为:',mDinValue,'M顶后的最大值:',mDinLaterMax)
                        
                #elif stock_market_price > stopwin_line:
                #    context.order_target(context.symbol(i), 0)
                #    stopwin_stock.append(i)
                #    stock_now = stock_now -1
        if len(stoploss_stock)>0:
            print('日期:', today, '股票:', stoploss_stock, '出现跟踪止损状况')
        #if len(stopwin_stock)>0:
        #    print('日期:', today, '股票:', stopwin_stock, '出现跟踪止盈状况')
        
        #-------------------------------------------止损模块END---------------------------------------------   
        
        try:
            buy_list = context.daily_buy_stock[today]
        except:
            buy_list = []
    
        
        # 1. 资金分配
        #is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天) 
        stock_cash = context.portfolio.portfolio_value/stock_count
        #cash_avg = context.portfolio.portfolio_value
        #cash_for_buy = min(context.portfolio.cash,  stock_cash)
        #cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)
        
        positions = {e.symbol: p.amount * p.last_sale_price
                     for e, p in context.perf_tracker.position_tracker.positions.items()}
        
        # 2. 生成卖出订单:hold_days天之后才开始卖出;
        try:
            sell_stock_list = context.daily_sell_stock[today]  # 当日符合卖出条件的股票
        except:
            sell_stock_list = []
        # 需要卖出的股票:已有持仓中符合卖出条件的股票
        stock_to_sell = [i for i in positions if i in sell_stock_list]
        #print('日期:', today, '股票:', stock_to_sell, '需要卖出的股票')
        sell_stock = []
        
         # 卖出
        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(context.symbol(instrument), 0)
                sell_stock.append(instrument)
                stock_now = stock_now -1
                if(instrument=='002735.SZA'):
                        print('日期:',today,'卖出1:',instrument)
                
        #if not is_staging :
        if 1==1 :    
            if len(equities) > 0:
                for i in equities.keys():
                    last_sale_date = equities[i].last_sale_date	# 上次交易日期
                    delta_days = data.current_dt - last_sale_date  
                    hold_days = delta_days.days # 持仓天数
                    print('日期:',today,'hold_days:',hold_days,'股票:',i)
                    if hold_days >= context.options['hold_days'] and i not in buy_list + stoploss_stock + stopwin_stock + sell_stock:
                        print('日期:',today,'卖出2:',i)
                        context.order_target(context.symbol(i), 0)
                        sell_stock.append(i)
                        stock_now = stock_now -1
                        if(i=='002735.SZA'):
                            print('日期:',today,'卖出2:',i)
                        #print('日期:', today, '股票:', i, ' 卖出')
                     
    # 3. 生成买入订单
        buy_num = stock_count - stock_now
        #if is_staging :
        #    buy_num = 1
        if len(buy_list)>0:
            print('日期:', today, '选出股票数量:', len(buy_list))
        if buy_num>0 and len(buy_list)>0 :
            # 不再买入已经轮仓卖出和移动止损的股票,以防止出现空头持仓
            buy_instruments = [i for i in buy_list if i not in sell_stock + stoploss_stock + stopwin_stock + now_stock][:buy_num]
            for i, instrument in enumerate(buy_instruments):
                current_price = data.current(context.symbol(instrument), 'price')
                #过滤不买入的
                try :
                    hasMdins=list(df_today[df_today.instrument==instrument]['hasMdin'])
                    hasMdin=hasMdins[0]
                    d2s=list(df_today[df_today.instrument==instrument]['d2'])
                    d2=d2s[0]
                    zs_a1=list(df_today[df_today.instrument==instrument]['zs_a1'])[0]
                    zs_a2=list(df_today[df_today.instrument==instrument]['zs_a2'])[0]
                    zs_bmy1=list(df_today[df_today.instrument==instrument]['zs_bmy1'])[0]            
                except :
                    hasMdin=0
                    d2=0
                    zs_bmy1=0
                  #  bmy4=0
                if hasMdin==1: #需要优化M顶的逻辑
                    mDinValue = data.history(context.symbol(instrument), 'close',29-int(d2), '1d')[0]
                    #M顶出现后的最高值
                    mDinLaterMax = data.history(context.symbol(instrument), 'close',29-int(d2), '1d').max()
                    mDinLaterMin = data.history(context.symbol(instrument), 'close',29-int(d2), '1d').min()
                    #当出现了M顶,且M顶未被突破,当前的价格低于M顶,且当前价格接近M顶的位置,不买入
                    if mDinLaterMax/mDinValue<1.03 and current_price<mDinValue and mDinValue/current_price<1.04 and mDinValue/mDinLaterMin>1.07:
                        print('日期:',today,'买入时过滤有顶部压力的股票:',instrument)
                        continue
                if zs_bmy1==3:
                        print('日期:',today,'买入时过滤指数不买入股票:',instrument,'指数a1:',zs_a1,'指数a2:',zs_a2)
                        #continue
                cash_for_buy = min(context.portfolio.cash,  stock_cash)
                if cash_for_buy>0 and data.can_trade(context.symbol(instrument)):           
                    amount = math.floor(cash_for_buy / current_price / 100) * 100
                    context.order(context.symbol(instrument), amount)
                    #if(instrument=='002735.SZA'):
                    print('日期:',today,'买入:',instrument)
                else :
                    print('日期:',today,'无资金或不能交易未买入:',instrument)
    # 回测引擎:准备数据,只执行一次
    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)
        # 函数:求满足平仓条件的股票列表
        def close_pos_con(df):
            return list(df[df['sell_condition']>0].instrument)
        
        # 每日卖出股票的数据框
        context.daily_sell_stock= df.groupby('date').apply(close_pos_con)  
        # 每日买入股票的数据框
        context.daily_buy_stock= df.groupby('date').apply(open_pos_con)  
    
    
        
    
    # 回测引擎:每个单位时间开始前调用一次,即每日开盘前调用一次。
    def m8_before_trading_start_bigquant_run(context, data):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2020-01-01',
        end_date=T.live_run_param('trading_date', '2022-02-23'),
        market='CN_STOCK_A',
        instrument_list='        ',
        max_count=0
    )
    
    m2 = M.input_features.v1(
        features="""isXiaDie0=where((return_0<1),1,0)
    #当天A股下跌数
    xd_num=group_sum(date, isXiaDie0)
    isZhangtToday=where((return_0>1.09)&(close_0==high_0),1,0)
    isDietToday=where((return_0<0.91)&(close_0==low_0),1,0)
    return0=return_0
    priceLowBl10=close_0/ts_min(close_0,10)
    zgzzf=high_0/close_1
    zdzzf=low_0/close_1
    kp1=(open_0-close_1)/close_1
    kp=shift((open_0-close_1)/close_1,-1)
    zd=shift((low_0-close_1)/close_1,-1)
    zg=shift((high_0-close_1)/close_1,-1)
    
    #逻辑一:大盘大跌情况下的涨停票后续效果
    #myls=where((xd_num>3500)&(isZhangtToday==1),1,0)
    #逻辑二:大盘大跌情况下的跌停票后续效果
    #myls=where((xd_num>3500)&(isDietToday==1),1,0)
    #逻辑三:大盘大跌情况下的跌停票后续效果,精选个股
    myls=where((xd_num>3500)&(isDietToday==1)&(priceLowBl10<1.05)&(kp1>-0.05),1,0)
    
    shouyi=(shift(open_0,-2)-shift(open_0,-1))/shift(open_0,-1)
    shouyi2=(shift(close_0,-2)-shift(open_0,-1))/shift(open_0,-1)
    
    kp=where((kp<-0.096),1,kp)
    #zhangf=(close_0-open_0)/open_0
    
    #附合这个选股逻辑,第二天开盘执行买入
    buy_condition=where(myls==1,1,0)
    #卖出不做特别处理,按三天收盘执行卖出
    sell_condition=where(myls==2,1,0)"""
    )
    
    m5 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m2.data,
        start_date='',
        end_date='',
        before_start_days=0,
        m_cached=False
    )
    
    m10 = M.instruments.v2(
        start_date='2010-01-01',
        end_date='2021-12-30',
        market='CN_STOCK_A',
        instrument_list='000002.HIX',
        max_count=0
    )
    
    m12 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    zs_zhangf=(close-open)/open
    zs_open=open/shift(close,1)
    zs_huiluo=(high-close)/close
    zs_huishen=(close-low)/low
    zs_zhenf=(high-low)/shift(close,1)
    zs_volume_zf=volume/shift(volume,1)
    zs_return_0=close/shift(close,1)
    zs_return_1=shift(zs_return_0,1)
    zs_return_2=shift(zs_return_0,2)
    zs_max10=ts_max(close,10)
    zs_max10d=ts_argmax(close,10)
    zs_max30=ts_max(close,30)
    #zs_max30d=ts_argmax(close,30)
    zs_min10=ts_min(close,10)
    #zs_min10d=ts_argmin(close,10)
    zs_min30=ts_min(close,30)
    #zs_min30d=ts_argmin(close,30)
    zs_priceHighBl10=close/zs_max10
    zs_priceLowBl10=close/zs_min10
    zs_priceHighBl30=close/zs_max30
    zs_priceLowBl30=close/zs_min30"""
    )
    
    m4 = M.use_datasource.v1(
        instruments=m10.data,
        features=m12.data,
        datasource_id='bar1d_index_CN_STOCK_A',
        start_date='',
        end_date=''
    )
    
    m13 = M.derived_feature_extractor.v3(
        input_data=m4.data,
        features=m12.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=True,
        user_functions={}
    )
    
    m18 = M.instruments.v2(
        start_date='2020-01-01',
        end_date='2020-12-30',
        market='CN_STOCK_A',
        instrument_list='000002.HIX',
        max_count=0
    )
    
    m19 = M.input_features.v1(
        features="""
    # #号开始的表示注释,注释需单独一行
    # 多个特征,每行一个,可以包含基础特征和衍生特征,特征须为本平台特征
    close
    """
    )
    
    m17 = M.use_datasource.v1(
        instruments=m18.data,
        features=m19.data,
        datasource_id='bar1d_index_CN_STOCK_A',
        start_date='',
        end_date=''
    )
    
    m20 = M.data_join.v3(
        input_1=m13.data,
        input_2=m17.data,
        on='date',
        how='left',
        sort=False
    )
    
    m14 = M.data_join.v3(
        input_1=m5.data,
        input_2=m20.data,
        on='date',
        how='left',
        sort=False
    )
    
    m7 = M.derived_feature_extractor.v3(
        input_data=m14.data,
        features=m2.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=True,
        user_functions={}
    )
    
    m6 = M.chinaa_stock_filter.v1(
        input_data=m7.data,
        index_constituent_cond=['全部'],
        board_cond=['上证主板', '深证主板'],
        industry_cond=['全部'],
        st_cond=['正常'],
        delist_cond=['非退市'],
        output_left_data=False
    )
    
    m11 = M.dropnan.v2(
        input_data=m6.data
    )
    
    m9 = M.sort.v4(
        input_ds=m11.data,
        sort_by='kp',
        group_by='date',
        keep_columns='--',
        ascending=True
    )
    
    m3 = M.filter.v3(
        input_data=m9.sorted_data,
        expr='myls==1',
        output_left_data=False
    )
    
    m8 = M.trade.v4(
        instruments=m1.data,
        options_data=m3.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=200000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='真实价格',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    日期: 2020-02-03 选出股票数量: 11
    日期: 2020-02-03 买入: 603268.SHA
    日期: 2020-02-04 hold_days: 0 股票: 603268.SHA
    日期: 2020-02-04 卖出2: 603268.SHA
    日期: 2020-02-28 选出股票数量: 44
    日期: 2020-02-28 买入: 600083.SHA
    日期: 2020-03-02 hold_days: 0 股票: 600083.SHA
    日期: 2020-03-02 卖出2: 600083.SHA
    日期: 2020-07-16 选出股票数量: 65
    日期: 2020-07-16 买入: 002989.SZA
    日期: 2020-07-17 hold_days: 0 股票: 002989.SZA
    日期: 2020-07-17 卖出2: 002989.SZA
    日期: 2020-07-24 选出股票数量: 33
    日期: 2020-07-24 买入: 603538.SHA
    日期: 2020-07-27 hold_days: 0 股票: 603538.SHA
    日期: 2020-07-27 卖出2: 603538.SHA
    日期: 2021-03-09 选出股票数量: 13
    日期: 2021-03-09 买入: 603353.SHA
    日期: 2021-03-10 hold_days: 0 股票: 603353.SHA
    日期: 2021-03-10 卖出2: 603353.SHA
    日期: 2021-08-17 选出股票数量: 5
    日期: 2021-08-17 买入: 600293.SHA
    日期: 2021-08-18 hold_days: 0 股票: 600293.SHA
    日期: 2021-08-18 卖出2: 600293.SHA
    日期: 2021-09-27 选出股票数量: 109
    日期: 2021-09-27 买入: 002136.SZA
    日期: 2021-09-28 hold_days: 0 股票: 002136.SZA
    日期: 2021-09-28 卖出2: 002136.SZA
    日期: 2021-09-29 股票: ['002136.SZA'] 出现跟踪止损状况
    日期: 2021-09-29 hold_days: 1 股票: 002136.SZA
    日期: 2021-09-29 选出股票数量: 38
    日期: 2021-09-29 买入: 603619.SHA
    日期: 2021-09-30 hold_days: 0 股票: 603619.SHA
    日期: 2021-09-30 卖出2: 603619.SHA
    日期: 2021-10-12 选出股票数量: 6
    日期: 2021-10-12 买入: 002961.SZA
    日期: 2021-10-13 hold_days: 0 股票: 002961.SZA
    日期: 2021-10-13 卖出2: 002961.SZA
    日期: 2021-10-27 选出股票数量: 6
    日期: 2021-10-27 买入: 605089.SHA
    日期: 2021-10-28 hold_days: 0 股票: 605089.SHA
    日期: 2021-10-28 卖出2: 605089.SHA
    日期: 2021-12-06 选出股票数量: 2
    日期: 2021-12-06 买入: 603178.SHA
    日期: 2021-12-07 hold_days: 0 股票: 603178.SHA
    日期: 2021-12-07 卖出2: 603178.SHA
    日期: 2021-12-24 选出股票数量: 6
    日期: 2021-12-24 买入: 002623.SZA
    日期: 2021-12-27 hold_days: 0 股票: 002623.SZA
    日期: 2021-12-27 卖出2: 002623.SZA
    日期: 2022-01-20 选出股票数量: 9
    日期: 2022-01-20 买入: 002813.SZA
    日期: 2022-01-21 hold_days: 0 股票: 002813.SZA
    日期: 2022-01-21 卖出2: 002813.SZA
    日期: 2022-01-25 选出股票数量: 34
    日期: 2022-01-25 买入: 000798.SZA
    日期: 2022-01-26 hold_days: 0 股票: 000798.SZA
    日期: 2022-01-26 卖出2: 000798.SZA
    日期: 2022-01-27 选出股票数量: 35
    日期: 2022-01-27 买入: 002516.SZA
    日期: 2022-01-28 hold_days: 0 股票: 002516.SZA
    日期: 2022-01-28 卖出2: 002516.SZA
    日期: 2022-02-11 选出股票数量: 9
    日期: 2022-02-11 买入: 000999.SZA
    日期: 2022-02-14 hold_days: 0 股票: 000999.SZA
    日期: 2022-02-14 卖出2: 000999.SZA
    日期: 2022-02-22 选出股票数量: 1
    日期: 2022-02-22 买入: 600053.SHA
    日期: 2022-02-23 hold_days: 0 股票: 600053.SHA
    日期: 2022-02-23 卖出2: 600053.SHA
    
    • 收益率74.93%
    • 年化收益率31.27%
    • 基准收益率12.85%
    • 阿尔法0.29
    • 贝塔0.1
    • 夏普比率1.37
    • 胜率0.75
    • 盈亏比1.15
    • 收益波动率18.92%
    • 信息比率0.05
    • 最大回撤9.86%
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-f568f220ca7848628162b6b0982c1263"}/bigcharts-data-end
    In [ ]: