复制链接
克隆策略

    {"description":"实验创建于2017/8/26","graph":{"edges":[{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"to_node_id":"-339:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data1","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15:data"},{"to_node_id":"-339:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-346:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-362:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-213:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-355:features","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24:data"},{"to_node_id":"-2576:input_data","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data"},{"to_node_id":"-390:data1","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:predictions"},{"to_node_id":"-355:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"to_node_id":"-374:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"to_node_id":"-2158:instruments","from_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62:data"},{"to_node_id":"-346:input_data","from_node_id":"-339:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53:data2","from_node_id":"-346:data"},{"to_node_id":"-362:input_data","from_node_id":"-355:data"},{"to_node_id":"-2171:data2","from_node_id":"-362:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:model","from_node_id":"-213:model"},{"to_node_id":"-213:training_ds","from_node_id":"-2576:data"},{"to_node_id":"-1944:input_1","from_node_id":"-390:data"},{"to_node_id":"-2158:features","from_node_id":"-956:data"},{"to_node_id":"-2178:features","from_node_id":"-956:data"},{"to_node_id":"-2178:input_data","from_node_id":"-2158:data"},{"to_node_id":"-2171:data1","from_node_id":"-2165:data"},{"to_node_id":"-390:data2","from_node_id":"-2165:data"},{"to_node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60:data","from_node_id":"-2171:data"},{"to_node_id":"-2165:input_data","from_node_id":"-2178:data"},{"to_node_id":"-1944:input_2","from_node_id":"-1932:data_1"},{"to_node_id":"-374:options_data","from_node_id":"-1944:data_1"}],"nodes":[{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2017-01-01","type":"Literal","bound_global_parameter":null},{"name":"end_date","value":"2021-01-01","type":"Literal","bound_global_parameter":null},{"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":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-8"}],"cacheable":true,"seq_num":1,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15","module_id":"BigQuantSpace.advanced_auto_labeler.advanced_auto_labeler-v2","parameters":[{"name":"label_expr","value":"# #号开始的表示注释\n# 0. 每行一个,顺序执行,从第二个开始,可以使用label字段\n# 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html\n# 添加benchmark_99】【前缀,可使用对应的benchmark数据\n# 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_\n\n# 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)\nshift(close, -3) / shift(open, -1)\n\n# 极值处理:用1%和99%分位的值做clip\nclip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))\n\n# 将分数映射到分类,这里使用20个分类\nall_wbins(label, 20)\n\n# 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)\nwhere(shift(high, -1) == shift(low, -1), NaN, label)\n","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},{"name":"benchmark","value":"000300.SHA","type":"Literal","bound_global_parameter":null},{"name":"drop_na_label","value":"True","type":"Literal","bound_global_parameter":null},{"name":"cast_label_int","value":"True","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-15"}],"cacheable":true,"seq_num":2,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-24","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"# #号开始的表示注释\n# 多个特征,每行一个,可以包含基础特征和衍生特征\nclose_0/mean(close_0,5)\nclose_0/mean(close_0,10)\nclose_0/mean(close_0,20)\nclose_0/open_0\nopen_0/mean(close_0,5)\nopen_0/mean(close_0,10)\nopen_0/mean(close_0,20)\navg_turn_0/avg_turn_5\navg_turn_0/avg_turn_10\nmf_net_pct_main_0","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":true,"seq_num":3,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date,instrument","type":"Literal","bound_global_parameter":null},{"name":"how","value":"inner","type":"Literal","bound_global_parameter":null},{"name":"sort","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"data1","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"},{"name":"data2","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-53"}],"cacheable":true,"seq_num":7,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60","module_id":"BigQuantSpace.stock_ranker_predict.stock_ranker_predict-v5","parameters":[{"name":"m_lazy_run","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"model","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"output_ports":[{"name":"predictions","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"},{"name":"m_lazy_run","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-60"}],"cacheable":true,"seq_num":8,"comment":"","comment_collapsed":true},{"node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62","module_id":"BigQuantSpace.instruments.instruments-v2","parameters":[{"name":"start_date","value":"2021-03-01","type":"Literal","bound_global_parameter":"交易日期"},{"name":"end_date","value":"2022-04-28","type":"Literal","bound_global_parameter":"交易日期"},{"name":"market","value":"CN_STOCK_A","type":"Literal","bound_global_parameter":null},{"name":"instrument_list","value":"300505.SZA\n002226.SZA","type":"Literal","bound_global_parameter":null},{"name":"max_count","value":"0","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"rolling_conf","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"output_ports":[{"name":"data","node_id":"287d2cb0-f53c-4101-bdf8-104b137c8601-62"}],"cacheable":true,"seq_num":9,"comment":"预测数据,用于回测和模拟","comment_collapsed":false},{"node_id":"-339","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":"-339"},{"name":"features","node_id":"-339"}],"output_ports":[{"name":"data","node_id":"-339"}],"cacheable":true,"seq_num":15,"comment":"","comment_collapsed":true},{"node_id":"-346","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":"-346"},{"name":"features","node_id":"-346"}],"output_ports":[{"name":"data","node_id":"-346"}],"cacheable":true,"seq_num":16,"comment":"","comment_collapsed":true},{"node_id":"-355","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":"258","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-355"},{"name":"features","node_id":"-355"}],"output_ports":[{"name":"data","node_id":"-355"}],"cacheable":true,"seq_num":17,"comment":"","comment_collapsed":true},{"node_id":"-362","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":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-362"},{"name":"features","node_id":"-362"}],"output_ports":[{"name":"data","node_id":"-362"}],"cacheable":true,"seq_num":18,"comment":"","comment_collapsed":true},{"node_id":"-374","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":"\n# 回测引擎:初始化函数,只执行一次\ndef bigquant_run(context):\n # 加载预测数据\n context.ranker_prediction = context.options['data'].read_df()\n\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n #context.stock_count = 1\n context.stock_count = 10\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])\n context.stock_weights = [1/context.stock_count for k in range(context.stock_count)] #半仓买入,每只股票等资金分配\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.2\n context.options['hold_days'] = 5\n\n \n","type":"Literal","bound_global_parameter":null},{"name":"handle_data","value":"\ndef getMa(today,context,instruments):\n # 加载原始数据\n import datetime\n stock_raw_data = D.history_data(instruments, today+datetime.timedelta(days=-40), today, ['date','close','low'])\n #print('11111',stock_raw_data)\n stock_raw_data=stock_raw_data.iloc[-20:] \n #stock_raw_data=stock_raw_data[:55]\n #print('22222',stock_raw_data)\n sumMa=0\n lastClose=0\n for index,row in stock_raw_data.iterrows():\n #print(index,row)\n sumMa += row['close']\n lastClose=row['close']\n \n # 包含多个周期均线值的股票数据\n # stock_ma_data = stock_raw_data.groupby('instrument').apply(ma_calculate)\n return [sumMa/20,lastClose]\n\n\n\n# 回测引擎:每日数据处理函数,每天执行一次\ndef bigquant_run(context, data):\n # 按日期过滤得到今日的预测数据\n #context.ranker_prediction.set_index('date')\n ranker_prediction = context.ranker_prediction[\n context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n today = data.current_dt.strftime('%Y-%m-%d')\n # 当日可用资金\n cash_for_buy = context.portfolio.cash\n \n # 获取当日买入列表,每天选取context.stock_count只\n buy_list=[]\n buy1_list = list(ranker_prediction[ranker_prediction.my1 == 1].instrument[:30])\n buy2_list = list(ranker_prediction[ranker_prediction.my2== 1].instrument[:10])\n print(today, '--买一选股-buy1_list==',buy1_list,'===买二选股-buy2_list:', len(buy2_list),buy2_list,)\n if len(buy1_list) > 0 :\n buy_list.append(buy1_list)\n if len(buy2_list) > 0 :\n buy_list.append(buy2_list)\n \n # 获取当前持仓资金\n stock_hold_now = {e.symbol: p.amount * p.last_sale_price\n for e, p in context.perf_tracker.position_tracker.positions.items() if p.amount>0} \n\n equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}\n \n # 需要卖出的股票:已有持仓中不在买入列表的股票\n #stock_to_sell = [ i for i in stock_hold_now if i not in buy_list ]\n stock_to_sell = [ i for i in stock_hold_now ]\n #stock_to_buy = [ i for i in buy_list if i not in stock_hold_now ]\n stock_to_buy1 = [] # [ i for i in buy1_list ] 只测试my2\n stock_to_buy2 = [ i for i in buy2_list ]\n \n #print(today,' 选股stock_to_buy: ',len(stock_to_buy),' 个: ',stock_to_buy)\n #print(today,' context.ranker_prediction ==: ',context.ranker_prediction)\n # print('ranker_prediction.dtypes',ranker_prediction.dtypes)\n\n # 处理一阳穿多线的买二准备 \n # for i, instrument in enumerate(stock_to_buy):\n # print(today, i,instrument )\n # dfinstrument=ranker_prediction[ranker_prediction.instrument==instrument]\n # junxians=list(dfinstrument['junxian'])\n # junxian=junxians[0]\n #print(today, i ,' junxian==',junxian)\n # if(junxian==1):\n # 通过标签赋值\n # dfinstrument.loc[0,'isReadyBuy2'] = 1\n #dfinstrument.loc[0,'date'] = '2022-03-25'\n # dfinstrument[dfinstrument['date'] == today] =str(today) + str(datetime.timedelta(days=1))\n #dfinstrument[dfinstrument['date'] == today] = (today.date()+datetime.timedelta(days=1)).strftime('%Y-%m-%d')\n #再处理非交易日和2天后数据也还有该条数据的问题\n # print(today,' append dfinstrument ',dfinstrument)\n # dfinstrument.set_index('date')\n # context.ranker_prediction.append(dfinstrument)\n\n \n # print(today,' after context.ranker_prediction ==: ',context.ranker_prediction) \n \n #stocks=len(stock_hold_now) #?\n stocksBuy1N=0\n stocksBuy2N=0\n stockBuy1_hold_now=[] \n stockBuy2_hold_now=[] \n # 卖出列表进行卖出操作\n if len(stock_to_sell)>0:\n for instrument in stock_to_sell:\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 instruments=[]\n instruments.append(instrument) \n #ri10=getMa(data.current_dt,context,instruments)\n #print('df after get ma 55==',ri55)\n try :\n a=getMa(data.current_dt,context,instruments)\n ri20=a[0]\n lastClose=a[1]\n except :\n ri20=0\n lastClose=0\n #print(instrument,today,'ma10===',ri10,'lastClose===',lastClose)\n \n stock_market_price = data.current(context.symbol(instrument), 'price') # 最新市场价格\n stock_market_today_high = data.current(context.symbol(instrument), 'high') #今日最高价 \n stock_market_today_close = data.current(context.symbol(instrument), 'close') #今日收盘价\n last_sale_date = equities[instrument].last_sale_date # 上次交易日期\n last_cost_price = equities[instrument].cost_basis # 上次交易金额\n delta_days = data.current_dt - last_sale_date \n hold_days = delta_days.days # 持仓天数\n # 最高收益\n #high_return = (highclose_price_since_buy-last_cost_price)/last_cost_price\n \n target_return = stock_market_today_close/last_cost_price\n #\n isBuy1=stock_hold_now[instrument]/context.portfolio.portfolio_value\n #print(instrument,' isBuy1 or buy2 ==',isBuy1)\n if isBuy1< 1/30 : #处理买一订单,买一股票池300,持仓10天轮动,每天30只\n \n if hold_days>=10 :\n context.order_target(sid, 0)\n print(today,'买一超期卖出 :','收益: ',target_return,sid)\n cash_for_buy += stock_hold_now[instrument]\n #stocks = stocks-1\n #elif target_return>=1.15 :\n # context.order_target(sid, 0)\n # print(today,'盈利卖出 :','收益: ',target_return,sid)\n # cash_for_buy += stock_hold_now[instrument]\n # stocks = stocks-1\n #elif lastClose<ri10 :\n # context.order_target(sid, 0)\n # print(today,' 跌破10日线止损卖出 ri10=:',ri10,' 收益: ',target_return,sid)\n # cash_for_buy += stock_hold_now[instrument]\n # stocks = stocks-1\n elif target_return<=0.92 :\n context.order_target(sid, 0)\n print(today,'买一止损卖出 :','收益: ',target_return,sid)\n cash_for_buy += stock_hold_now[instrument]\n #stocks = stocks-1\n else:\n stockBuy1_hold_now.append(instrument)\n stocksBuy1N=stocksBuy1N+1\n else : #处理买二订单\n stockBuy2_hold_now.append(instrument)\n if hold_days>=5 :\n context.order_target(sid, 0)\n print(today,'买二超期卖出 :','收益: ',target_return,sid)\n cash_for_buy += stock_hold_now[instrument]\n #stocks = stocks-1\n elif target_return>=1.1 :\n context.order_target(sid, 0)\n print(today,'买二盈利卖出 :','收益: ',target_return,sid)\n cash_for_buy += stock_hold_now[instrument]\n #stocks = stocks-1\n elif lastClose<ri20 :\n context.order_target(sid, 0)\n print(today,' 买二跌破20日线止损卖出 ri20=:',ri20,' 收益: ',target_return,sid)\n cash_for_buy += stock_hold_now[instrument]\n #stocks = stocks-1\n elif target_return<=0.95 :\n context.order_target(sid, 0)\n print(today,'买二止损卖出 :','收益: ',target_return,sid)\n cash_for_buy += stock_hold_now[instrument]\n # stocks = stocks-1\n else:\n stockBuy2_hold_now.append(instrument)\n stocksBuy2N=stocksBuy2N+1 \n \n #context.order_target_percent(sid, 0) # 全部卖出\n # 如果是早盘买早盘卖,卖出的资金可以用于买股票,此时应将下面的注释打开,卖出股票时更新可用现金;\n # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用\n #cash_for_buy += stock_hold_now[instrument]\n \n # 买入列表执行买操作\n #if len(stock_to_buy)>0:\n # for instrument,weight in zip(stock_to_buy,context.stock_weights):\n # sid = context.symbol(instrument) # 将标的转化为equity格式\n # if data.can_trade(sid):\n # context.order_target_value(sid, min(cash_for_buy,context.portfolio.portfolio_value*0.5)) # 买入 \n\n #print(today,'--stockBuy1_hold_now--=:',stockBuy1_hold_now)\n stockBuy1_hold_now\n # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n #buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])\n buy1N=min(30,(300-stocksBuy1N))\n buy2N=min(10,(20-stocksBuy2N))\n buy1_instruments = []\n if len(stock_to_buy1) > 0 :\n buy1_instruments=list(stock_to_buy1[:buy1N])\n buy2_instruments = []\n if len(stock_to_buy2) > 0 :\n buy2_instruments=list(stock_to_buy2[:buy2N])\n #print(today,' buy_instruments:',buy_instruments,' 权重: ',buy_cash_weights)\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy1_instruments):\n #cash = cash_for_buy * buy_cash_weights[i] \n #cash = context.portfolio.portfolio_value * buy_cash_weights[i]\n #用20分1的资金买一(300zhi)\n cash = (cash_for_buy/20)/(200-stocksBuy1N)\n #print('cash_for_buy==',cash_for_buy, ' cash==',cash)\n #if cash > max_cash_per_instrument - stock_hold_now.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n # cash = max_cash_per_instrument - stock_hold_now.get(instrument, 0)\n if cash > 0:\n if instrument not in stockBuy1_hold_now : #不重复买入\n context.order_value(context.symbol(instrument), cash)\n # print(today,' 买入一买 ',instrument)\n \n for i, instrument in enumerate(buy2_instruments):\n #cash = cash_for_buy * buy_cash_weights[i] \n #cash = context.portfolio.portfolio_value * buy_cash_weights[i]\n cash = (cash_for_buy*0.9)/(20-stocksBuy2N)\n #print('cash_for_buy==',cash_for_buy, ' cash==',cash)\n # if cash > max_cash_per_instrument - stock_hold_now.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n # cash = max_cash_per_instrument - stock_hold_now.get(instrument, 0)\n if cash > 0:\n #if instrument in stockBuy1_hold_now :\n context.order_value(context.symbol(instrument), cash)\n print(today,' 买入二买 ',instrument)\n # else:\n # print(today,' 发现二买,但没有一买,放弃买入:---',instrument)\n else:\n print(today,' 无资金买入二买 ',instrument)\n \n ","type":"Literal","bound_global_parameter":null},{"name":"prepare","value":"# 回测引擎:准备数据,只执行一次\ndef bigquant_run(context):\n pass\n","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":"twap_1","type":"Literal","bound_global_parameter":null},{"name":"order_price_field_sell","value":"twap_1","type":"Literal","bound_global_parameter":null},{"name":"capital_base","value":"10000000","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":"-374"},{"name":"options_data","node_id":"-374"},{"name":"history_ds","node_id":"-374"},{"name":"benchmark_ds","node_id":"-374"},{"name":"trading_calendar","node_id":"-374"}],"output_ports":[{"name":"raw_perf","node_id":"-374"}],"cacheable":false,"seq_num":19,"comment":"","comment_collapsed":true},{"node_id":"-213","module_id":"BigQuantSpace.stock_ranker_train.stock_ranker_train-v6","parameters":[{"name":"learning_algorithm","value":"排序","type":"Literal","bound_global_parameter":null},{"name":"number_of_leaves","value":30,"type":"Literal","bound_global_parameter":null},{"name":"minimum_docs_per_leaf","value":1000,"type":"Literal","bound_global_parameter":null},{"name":"number_of_trees","value":20,"type":"Literal","bound_global_parameter":null},{"name":"learning_rate","value":0.1,"type":"Literal","bound_global_parameter":null},{"name":"max_bins","value":1023,"type":"Literal","bound_global_parameter":null},{"name":"feature_fraction","value":1,"type":"Literal","bound_global_parameter":null},{"name":"data_row_fraction","value":1,"type":"Literal","bound_global_parameter":null},{"name":"plot_charts","value":"True","type":"Literal","bound_global_parameter":null},{"name":"ndcg_discount_base","value":1,"type":"Literal","bound_global_parameter":null},{"name":"m_lazy_run","value":"False","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"training_ds","node_id":"-213"},{"name":"features","node_id":"-213"},{"name":"test_ds","node_id":"-213"},{"name":"base_model","node_id":"-213"}],"output_ports":[{"name":"model","node_id":"-213"},{"name":"feature_gains","node_id":"-213"},{"name":"m_lazy_run","node_id":"-213"}],"cacheable":true,"seq_num":4,"comment":"","comment_collapsed":true},{"node_id":"-2576","module_id":"BigQuantSpace.dropnan.dropnan-v2","parameters":[],"input_ports":[{"name":"input_data","node_id":"-2576"},{"name":"features","node_id":"-2576"}],"output_ports":[{"name":"data","node_id":"-2576"}],"cacheable":true,"seq_num":5,"comment":"","comment_collapsed":true},{"node_id":"-390","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date,instrument","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":"data1","node_id":"-390"},{"name":"data2","node_id":"-390"}],"output_ports":[{"name":"data","node_id":"-390"}],"cacheable":true,"seq_num":11,"comment":"","comment_collapsed":true},{"node_id":"-956","module_id":"BigQuantSpace.input_features.input_features-v1","parameters":[{"name":"features","value":"#600335.SHA\n#300061.SZA\n#300364.SZA\n#002173.SZA\n#002433.SZA\n#601020.SHA\n#000545.SZA\n#000514.SZA\n#300505.SZA\n#002226.SZA\n#300299.SZA\n#600425.SHA\n#000632.SZA\n#002060.SZA\n\n#gaodianN5=where(ts_argmax(high_0, 258*5)<800,1,0)\n#gaodianN4=where(ts_argmax(high_0, 258*4)<800,1,0)\n#5年高点,1年按258个交易日算\n#isgaodian=max(gaodianN5,gaodianN4)\n\n#1年低点,1年按258个交易日算\n#didianN=ts_argmin(low_0, 258*1)\n#isdidian=where(didianN<200.0,1,0)\n\n#半年高点,1年按258个交易日算\nbanniangaodianN=ts_argmax(high_0, 128)\nisbanniangaodian=where(banniangaodianN<80.0,1,0)\n\n#timeperiod移动平均线\n#zhouma34=ta_ma(close_0, timeperiod=166)\n#timeperiod移动平均线\nzhouma55=ta_ma(close_0, timeperiod=258)\n#在周55均线之上,\nisupzhou55=where(close_0>zhouma55,1,0)\n#回调程度\nhuitiaodu=ts_max(high_0, 128)/low_1\n\n#反弹比例,选比例最高的10-20只交易,后面调试\n#yiniandidian=ts_min(low_0, 258*1)\nbanniangaodian=ts_max(high_0, 128*1)\n#fantanbili=banniangaodian/yiniandidian\n\n#macd1=ta_macd_macd_12_26_9_0\n#macd2=ta_macd_macdhist_12_26_9_0\n#macd3=ta_macd_macdsignal_12_26_9_0\n#sw1=swing_volatility_5_0 #振幅波动率,timeperiod=5* 取值: , 5, 10, 30, 60, 120, 240\n#sw2=swing_volatility_10_0\n#sw3=swing_volatility_30_0\n#sw4=swing_volatility_60_0\nvl1=volatility_5_0 #波动率,timeperiod=240* 取值: , 5, 10, 30, 60, 120, 240\nvl2=volatility_10_0\nvl3=volatility_30_0\n#vl4=volatility_60_0\n\n\nmacd_dif=ta_macd_dif(close_0/adjust_factor_0)\nmacd_h=ta_macd_hist(close_0/adjust_factor_0)\nduanqiup1=where(low_0>low_1,1,0)\nduanqiup2=where(macd_h>shift(macd_h,1),1,0)\nduanqiup=max(duanqiup1,duanqiup2)\n\n\n#st_status_0\n#my1==1&(vl2<vl3)&(vl2>0.012)&(vl2<0.038)&(macd1<0)&date>'2022-04-01'\n#my1=where((isbanniangaodian==1)&\\\n# (huitiaodu>1.2)&\\\n# (vl2<vl3)&(vl2>0.012)&(vl2<0.038)&(st_status_0==0),1,0)\n\nmy1=where((huitiaodu>1.2)&\\\n (vl2<vl3)&(vl2>0.012)&(vl2<0.038)&(st_status_0==0),1,0)\n\n#isgaodian==1&isdidian==1&isbanniangaodian==1&isbanniangaodian==1&fantanbili>1.5&date>='2022-03-08'\n#调试一下不要半年高点?只要回调度,不管什么时候回调的?涨停上穿也算\n\n#按前一天算ma,即线重合后第三天再买如\nma5=ta_ma(close_0, timeperiod=5)\nma10=ta_ma(close_0, timeperiod=10)\nma13=ta_ma(close_0, timeperiod=13)\nma20=ta_ma(close_0, timeperiod=20)\nma34=ta_ma(close_0, timeperiod=34)\nma55=ta_ma(close_0, timeperiod=55)\n\n#4-5线重合 真阳线 后面再调试是否要过滤returen0《5-8;-这样可以亏损幅度可以小一些;再调试回调幅度是否要大于1.5\n#junxian=where((ma5<=high_0) & (ma10<=high_0) & (ma13<=high_0) &(ma20<=high_0) & (ma34<=high_0) & (ma55<=high_0) &\\\n# (ma5 >=low_0) & (ma10>=low_0) & (ma13>=low_0) & (ma20>=low_0) & (ma34>=low_0) & (ma55>=low_0) &\\\n# (return_0>1.01)&(close_0>open_0)&(return_0<1.08)&(isbanniangaodian==1),1,0) \n#试试2日穿阳\njunxian=where((ma5<=high_0) & (ma10<=high_0) & (ma13<=high_0) &(ma20<=high_0) & (ma34<=high_0) & (ma55<=high_0) &\\\n (return_0>1.01)&(close_0>open_0)&(return_0<1.08),1,0) \n\nmaxline=max(ma5, ma10,ma13, ma20,ma34,ma55)\nminline=min(ma5, ma10,ma13, ma20,ma34,ma55)\nzhanshang55=close_0/maxline\n#4-5线重合度\njunxianchonghedu=minline/maxline\njunxianchonghedu5=shift(junxianchonghedu,5)\njunxianchonghedu18=shift(junxianchonghedu,18)\n# volume_* 第前 * 个交易日的交易量* 取值: 0 .. 20\n#一阳穿线需要放量1.5倍以上,后面调试. #nanmean(x, d), #过去 d 天 x 的均值(去除NaN值)\n\nfanliang=volume_0/volume_1 #放量\ndeaLn=deal_number_0/deal_number_1\ndaDan=fanliang/deaLn #交易笔数放量比不上交易额放量,说明是大单进入多,用大于1.18进行调试\n\n#my2ready=where((isbanniangaodian==1)&(junxian==1)&(zhanshang55>=1.0)&\n #(junxianchonghedu>0.94)&(huitiaodu>1.15)&(fanliang>1.45)&(daDan>1.18),1,0) #需要收拢条件\nmy2ready=where((junxian==1)&(zhanshang55>=1.0)&\\\n (junxianchonghedu>junxianchonghedu5)&(junxianchonghedu5>junxianchonghedu18)&\\\n (junxianchonghedu>0.95)&(huitiaodu>1.15)&(fanliang>1.5)&(daDan>1.2),1,0)\nmy2=where((shift(my2ready,1)==1)&(low_0>low_1)&(close_0>=ma5),1,0)\n#low_0>low_1这个条件太松了\n#最好不离55线太远,--my1使用\nnearMa55=ma55/close_0\n\nSW_code=industry_sw_level1_0\nmyrank=rank_fs_roe_ttm_0+rank_fs_net_profit_qoq_0-rank_pb_lf_0\n\npe_ttm_0 #滚动市盈率\nfs_eps_0 #每股收益\nfs_eps_yoy_0 #每股收益同比增长率\nfs_bps_0 #每股净资产\nfs_roa_ttm_0 #总资产报酬率 (TTM)\n\n#isbanniangaodian==1&junxian==1&zhanshang55>1&junxianchonghedu>0.95&huitiaodu>1.3&date>='2022-01-01'\nmy=max(my1,my2)","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"features_ds","node_id":"-956"}],"output_ports":[{"name":"data","node_id":"-956"}],"cacheable":true,"seq_num":12,"comment":"","comment_collapsed":true},{"node_id":"-2158","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":"580","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"instruments","node_id":"-2158"},{"name":"features","node_id":"-2158"}],"output_ports":[{"name":"data","node_id":"-2158"}],"cacheable":true,"seq_num":13,"comment":"","comment_collapsed":true},{"node_id":"-2165","module_id":"BigQuantSpace.filter.filter-v3","parameters":[{"name":"expr","value":"date>='2022-03-10'","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":"-2165"}],"output_ports":[{"name":"data","node_id":"-2165"},{"name":"left_data","node_id":"-2165"}],"cacheable":true,"seq_num":14,"comment":"my1","comment_collapsed":true},{"node_id":"-2171","module_id":"BigQuantSpace.join.join-v3","parameters":[{"name":"on","value":"date,instrument","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":"data1","node_id":"-2171"},{"name":"data2","node_id":"-2171"}],"output_ports":[{"name":"data","node_id":"-2171"}],"cacheable":true,"seq_num":20,"comment":"","comment_collapsed":true},{"node_id":"-2178","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":"False","type":"Literal","bound_global_parameter":null},{"name":"user_functions","value":"{}","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_data","node_id":"-2178"},{"name":"features","node_id":"-2178"}],"output_ports":[{"name":"data","node_id":"-2178"}],"cacheable":true,"seq_num":21,"comment":"","comment_collapsed":true},{"node_id":"-440","module_id":"BigQuantSpace.cached.cached-v3","parameters":[{"name":"run","value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(input_1, input_2, input_3):\n # 示例代码如下。在这里编写您的代码\n # 计算行业行业收益\n industry_df = DataSource(\"basic_info_index_CN_STOCK_A\").read()\n\n SW_industry_list = industry_df[industry_df.instrument.str.startswith('SW')].instrument.tolist()\n\n SW_industry_df = DataSource(\"bar1d_index_CN_STOCK_A\").read(SW_industry_list)\n\n SW_industry_ret = SW_industry_df.groupby('instrument').apply(calcu_ret)\n SW_industry_ret.reset_index(inplace=True, drop=True)\n #SW_industry_ret['date'] = SW_industry_ret['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n print('after apply SW_industry_ret==\\n',SW_industry_ret) \n \n #????daily_buy_industry_dict = {dt:seek_head_industry(SW_industry_ret.set_index('date').loc[dt]) for dt in list(set(SW_industry_ret.date))}\n #print('daily_buy_industry_dict==\\n',daily_buy_industry_dict) \n \n daily_stock = input_1.read()\n daily_stock['SW_code'] = daily_stock['SW_code'].apply(lambda x:'SW'+str(x)+'.HIX')\n print('daily_stock=111=\\n',daily_stock[:10]) \n #daily_stock = daily_stock.groupby(['date', 'industry_sw_level1_0']).apply(seek_head_stock).reset_index()\n #print('daily_stock=222=\\n',daily_stock[:10]) \n buy_df = pd.DataFrame()\n \n print('daily_stock.SW_code.tolist()',daily_stock.SW_code.tolist())\n #for dt in list(set(SW_industry_ret.date)): t=test.loc[(test[\"所属区域\"].isin([\"苏州\",\"昆\n buy_df=seek_head_industry(SW_industry_ret.loc[(SW_industry_ret['instrument'].isin(daily_stock.SW_code.tolist()))])\n \n #for k,v in daily_buy_industry_dict.items():\n # buy_df = buy_df.append(daily_stock[(daily_stock.date==k)&(daily_stock.industry_sw_level1_0.apply(lambda x: x in v))])\n #print('buy_df=====\\n',buy_df) \n #buy_df = buy_df.groupby('date').apply(lambda x:x[0].values.tolist()).reset_index()\n # buy_df[0] = buy_df[0].apply(lambda x:x[0]+x[1]+x[2])\n #daily_stock['date'] = daily_stock['date'].apply(lambda x:x.strftime('%Y-%m-%d')) \n buy_df=buy_df[['date','SW_code','score','SW_p']]\n #buy_df['date'] = buy_df['date'].apply(lambda x:x.strftime('%Y-%m-%d')) \n print('buy_df=222====\\n',buy_df) \n \n data=pd.merge(daily_stock,buy_df,on=['date','SW_code'],how='inner',suffixes=('','_r'))\n #data['date'] = data['date'].apply(lambda x:x.strftime('%Y-%m-%d')) \n print('data=dddd=\\n',data)\n data_1 = DataSource.write_df(data)\n #data_2 = DataSource.write_df(buy_df)\n \n \n return Outputs(data_1=data_1, data_2=None, data_3=None)\n\n\n\n\n# 计算不同周期的动量\ndef calcu_ret(df):\n df = df.sort_values('date')\n for i in [42, 84, 126]: # 分别代表2月、4月、半年的动量\n df['ret_%s'%i] = df['close']/df['close'].shift(i)-1 \n return df\n\n# 计算出得分\ndef seek_head_industry(df):\n for j in ['ret_42','ret_84','ret_126']:\n df['%s'%j] = df['%s'%j].rank(ascending=True) \n df['score'] = 0.4*df['ret_42']+0.3*df['ret_84']+0.3*df['ret_126'] # 得分的权重分别为0.4、0.3、0.3\n df['SW_code'] = df['instrument']\n print('result---111--',df)\n #result=df.sort_values('score', ascending=False)\n df.sort_values('score', ascending=False)\n #df.groupby('date').sort(['score'])\n df['SW_p']=df.index+1\n print('result--22---',df) \n \n return df\n\n# 选出特定行业优质股票\ndef seek_head_stock(df):\n result = df.sort_values(['myrank'], ascending=False)\n #return list(result.instrument[:10]) # 每个行业选10只股票\n return list(result.instrument) # 每个行业选10只股票","type":"Literal","bound_global_parameter":null},{"name":"post_run","value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","type":"Literal","bound_global_parameter":null},{"name":"input_ports","value":"","type":"Literal","bound_global_parameter":null},{"name":"params","value":"{}","type":"Literal","bound_global_parameter":null},{"name":"output_ports","value":"data_1","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-440"},{"name":"input_2","node_id":"-440"},{"name":"input_3","node_id":"-440"}],"output_ports":[{"name":"data_1","node_id":"-440"},{"name":"data_2","node_id":"-440"},{"name":"data_3","node_id":"-440"}],"cacheable":true,"seq_num":6,"comment":"","comment_collapsed":true},{"node_id":"-1932","module_id":"BigQuantSpace.cached.cached-v3","parameters":[{"name":"run","value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run():\n # 示例代码如下。在这里编写您的代码\n # 计算行业行业收益\n industry_df = DataSource(\"basic_info_index_CN_STOCK_A\").read()\n SW_industry_list = industry_df[industry_df.instrument.str.startswith('SW')].instrument.tolist()\n SW_industry_df = DataSource(\"bar1d_index_CN_STOCK_A\").read(SW_industry_list)\n SW_industry_ret = SW_industry_df.groupby('instrument').apply(calcu_ret)\n SW_industry_ret.reset_index(inplace=True, drop=True)\n buy_df = pd.DataFrame()\n buy_df=seek_head_industry(SW_industry_ret)\n industry_name_df = DataSource(\"basic_info_IndustrySw\").read()\n industry_name_df = industry_name_df[(industry_name_df.industry_sw_level==1)&(industry_name_df.version==2021)]\n industry_name_df['SW_code'] = industry_name_df['code'].apply(lambda x:'SW'+str(x)+'.HIX')\n #print('industry_name_df==',industry_name_df)\n data=pd.merge(buy_df,industry_name_df,on=['SW_code'],how='inner')\n data=data[['date','SW_code','SW_score','name']]\n #print(data,'222 data==',data)\n # dateList=['2022-03-25','2022-03-30']\n # for dateI in dateList:\n # todayData=data[data.date==dateI]\n # print(dateI,'Data==',todayData)\n # todayData=todayData.sort_values('SW_score', ascending=False)\n # todayData=todayData.reset_index(drop=True)\n # todayData['SW_p']=todayData.index+1\n # print(dateI,'222 todayData==',todayData)\n data_1 = DataSource.write_df(data)\n return Outputs(data_1=data_1, data_2=None, data_3=None)\n\n# 计算不同周期的动量\ndef calcu_ret(df):\n df = df.sort_values('date')\n for i in [42, 84, 126]: # 分别代表2月、4月、半年的动量\n df['ret_%s'%i] = df['close']/df['close'].shift(i)-1 \n return df\n\n# 计算出得分\ndef seek_head_industry(df):\n for j in ['ret_42','ret_84','ret_126']:\n df['%s'%j] = df['%s'%j].rank(ascending=True) \n df['SW_score'] = 0.4*df['ret_42']+0.3*df['ret_84']+0.3*df['ret_126'] # 得分的权重分别为0.4、0.3、0.3\n df['SW_code'] = df['instrument']\n # print('result--22---',df) \n return df\n","type":"Literal","bound_global_parameter":null},{"name":"post_run","value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","type":"Literal","bound_global_parameter":null},{"name":"input_ports","value":"","type":"Literal","bound_global_parameter":null},{"name":"params","value":"{}","type":"Literal","bound_global_parameter":null},{"name":"output_ports","value":"data_1","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-1932"},{"name":"input_2","node_id":"-1932"},{"name":"input_3","node_id":"-1932"}],"output_ports":[{"name":"data_1","node_id":"-1932"},{"name":"data_2","node_id":"-1932"},{"name":"data_3","node_id":"-1932"}],"cacheable":true,"seq_num":10,"comment":"获取板块动量","comment_collapsed":true},{"node_id":"-1944","module_id":"BigQuantSpace.cached.cached-v3","parameters":[{"name":"run","value":"# Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端\ndef bigquant_run(inputData,inputSWinfo):\n inputDf=inputData.read()\n inputSW_DF=inputSWinfo.read()\n #print('inputDf==',inputDf)\n dateList=list(inputDf.groupby(['date']).groups.keys())\n #print('dateList==',dateList)\n #dateList['date']=dateList['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n # print('dateList==',list(dateList))\n out_df = pd.DataFrame()\n for dateI in dateList:\n #print('dateI==',dateI)\n todayData1=inputDf[inputDf.date==dateI]\n todayData1['SW_code'] = todayData1['SW_code'].apply(lambda x:'SW'+str(x)+'.HIX')\n todayData1['date']=todayData1['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n \n todayData2=inputSW_DF[inputSW_DF.date==dateI]\n #print(dateI,'Data==',todayData)\n todayData2=todayData2.sort_values('SW_score', ascending=False)\n todayData2=todayData2.reset_index(drop=True)\n todayData2['SW_p']=todayData2.index+1\n todayData2['date']=todayData2['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n #print('todayData1==',todayData1)\n #print('todayData2==',todayData2)\n \n todayData=pd.merge(todayData1,todayData2,suffixes=('_left','_SW'),on=['date','SW_code'],how='inner')\n #print(dateI,' todayData==',todayData)\n out_df=out_df.append(todayData)\n out_df=out_df.reset_index(drop=True)\n #out_df = out_df.reindex(columns=['date','instrument'])\n #out_df['date']=out_df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))\n \n data_1 = DataSource.write_df(out_df)\n print('data_1===\\n',data_1.read())\n return Outputs(data_1=data_1, data_2=None, data_3=None)\n","type":"Literal","bound_global_parameter":null},{"name":"post_run","value":"# 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。\ndef bigquant_run(outputs):\n return outputs\n","type":"Literal","bound_global_parameter":null},{"name":"input_ports","value":"","type":"Literal","bound_global_parameter":null},{"name":"params","value":"{}","type":"Literal","bound_global_parameter":null},{"name":"output_ports","value":"data_1","type":"Literal","bound_global_parameter":null}],"input_ports":[{"name":"input_1","node_id":"-1944"},{"name":"input_2","node_id":"-1944"},{"name":"input_3","node_id":"-1944"}],"output_ports":[{"name":"data_1","node_id":"-1944"},{"name":"data_2","node_id":"-1944"},{"name":"data_3","node_id":"-1944"}],"cacheable":true,"seq_num":22,"comment":"获取某天板块动量","comment_collapsed":true}],"node_layout":"<node_postions><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-8' Position='209,64,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-15' Position='64,173,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-24' Position='633,-23,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-53' Position='249,375,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-60' Position='877,620,200,200'/><node_position Node='287d2cb0-f53c-4101-bdf8-104b137c8601-62' Position='1002,-2,200,200'/><node_position Node='-339' Position='392,142,200,200'/><node_position Node='-346' Position='385,280,200,200'/><node_position Node='-355' Position='1078,234,200,200'/><node_position Node='-362' Position='1061,339,200,200'/><node_position Node='-374' Position='874,983,200,200'/><node_position Node='-213' Position='640,539,200,200'/><node_position Node='-2576' Position='496,462,200,200'/><node_position Node='-390' Position='1020,718,200,200'/><node_position Node='-956' Position='1328,66,200,200'/><node_position Node='-2158' Position='1342,175,200,200'/><node_position Node='-2165' Position='1406,357,200,200'/><node_position Node='-2171' Position='1084,531,200,200'/><node_position Node='-2178' Position='1407,288,200,200'/><node_position Node='-440' Position='1525,481,200,200'/><node_position Node='-1932' Position='1497,635,200,200'/><node_position Node='-1944' Position='1332,786,200,200'/></node_postions>"},"nodes_readonly":false,"studio_version":"v2"}
    In [102]:
    # 本代码由可视化策略环境自动生成 2022年4月24日 22:46
    # 本代码单元只能在可视化模式下编辑。您也可以拷贝代码,粘贴到新建的代码单元或者策略,然后修改。
    
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m6_run_bigquant_run(input_1, input_2, input_3):
        # 示例代码如下。在这里编写您的代码
        # 计算行业行业收益
        industry_df = DataSource("basic_info_index_CN_STOCK_A").read()
    
        SW_industry_list = industry_df[industry_df.instrument.str.startswith('SW')].instrument.tolist()
    
        SW_industry_df = DataSource("bar1d_index_CN_STOCK_A").read(SW_industry_list)
    
        SW_industry_ret = SW_industry_df.groupby('instrument').apply(calcu_ret)
        SW_industry_ret.reset_index(inplace=True, drop=True)
        #SW_industry_ret['date'] = SW_industry_ret['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
        print('after apply SW_industry_ret==\n',SW_industry_ret) 
        
        #????daily_buy_industry_dict = {dt:seek_head_industry(SW_industry_ret.set_index('date').loc[dt]) for dt in list(set(SW_industry_ret.date))}
        #print('daily_buy_industry_dict==\n',daily_buy_industry_dict) 
        
        daily_stock = input_1.read()
        daily_stock['SW_code'] = daily_stock['SW_code'].apply(lambda x:'SW'+str(x)+'.HIX')
        print('daily_stock=111=\n',daily_stock[:10]) 
        #daily_stock = daily_stock.groupby(['date', 'industry_sw_level1_0']).apply(seek_head_stock).reset_index()
        #print('daily_stock=222=\n',daily_stock[:10]) 
        buy_df = pd.DataFrame()
        
        print('daily_stock.SW_code.tolist()',daily_stock.SW_code.tolist())
        #for dt in list(set(SW_industry_ret.date)): t=test.loc[(test["所属区域"].isin(["苏州","昆
        buy_df=seek_head_industry(SW_industry_ret.loc[(SW_industry_ret['instrument'].isin(daily_stock.SW_code.tolist()))])
            
        #for k,v in daily_buy_industry_dict.items():
       #     buy_df = buy_df.append(daily_stock[(daily_stock.date==k)&(daily_stock.industry_sw_level1_0.apply(lambda x: x in v))])
        #print('buy_df=====\n',buy_df) 
        #buy_df = buy_df.groupby('date').apply(lambda x:x[0].values.tolist()).reset_index()
       # buy_df[0] = buy_df[0].apply(lambda x:x[0]+x[1]+x[2])
        #daily_stock['date'] = daily_stock['date'].apply(lambda x:x.strftime('%Y-%m-%d'))  
        buy_df=buy_df[['date','SW_code','score','SW_p']]
        #buy_df['date'] = buy_df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))  
        print('buy_df=222====\n',buy_df) 
        
        data=pd.merge(daily_stock,buy_df,on=['date','SW_code'],how='inner',suffixes=('','_r'))
        #data['date'] = data['date'].apply(lambda x:x.strftime('%Y-%m-%d'))  
        print('data=dddd=\n',data)
        data_1 = DataSource.write_df(data)
        #data_2 = DataSource.write_df(buy_df)
        
        
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    
    
    
    # 计算不同周期的动量
    def calcu_ret(df):
        df = df.sort_values('date')
        for i in [42, 84, 126]: # 分别代表2月、4月、半年的动量
            df['ret_%s'%i] = df['close']/df['close'].shift(i)-1 
        return df
    
    # 计算出得分
    def seek_head_industry(df):
        for j in ['ret_42','ret_84','ret_126']:
            df['%s'%j] = df['%s'%j].rank(ascending=True) 
        df['score'] = 0.4*df['ret_42']+0.3*df['ret_84']+0.3*df['ret_126']  # 得分的权重分别为0.4、0.3、0.3
        df['SW_code'] = df['instrument']
        print('result---111--',df)
        #result=df.sort_values('score', ascending=False)
        df.sort_values('score', ascending=False)
        #df.groupby('date').sort(['score'])
        df['SW_p']=df.index+1
        print('result--22---',df)    
        
        return df
    
    # 选出特定行业优质股票
    def seek_head_stock(df):
        result = df.sort_values(['myrank'], ascending=False)
        #return list(result.instrument[:10]) # 每个行业选10只股票
        return list(result.instrument) # 每个行业选10只股票
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m6_post_run_bigquant_run(outputs):
        return outputs
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m10_run_bigquant_run():
        # 示例代码如下。在这里编写您的代码
        # 计算行业行业收益
        industry_df = DataSource("basic_info_index_CN_STOCK_A").read()
        SW_industry_list = industry_df[industry_df.instrument.str.startswith('SW')].instrument.tolist()
        SW_industry_df = DataSource("bar1d_index_CN_STOCK_A").read(SW_industry_list)
        SW_industry_ret = SW_industry_df.groupby('instrument').apply(calcu_ret)
        SW_industry_ret.reset_index(inplace=True, drop=True)
        buy_df = pd.DataFrame()
        buy_df=seek_head_industry(SW_industry_ret)
        industry_name_df = DataSource("basic_info_IndustrySw").read()
        industry_name_df = industry_name_df[(industry_name_df.industry_sw_level==1)&(industry_name_df.version==2021)]
        industry_name_df['SW_code'] = industry_name_df['code'].apply(lambda x:'SW'+str(x)+'.HIX')
        #print('industry_name_df==',industry_name_df)
        data=pd.merge(buy_df,industry_name_df,on=['SW_code'],how='inner')
        data=data[['date','SW_code','SW_score','name']]
        #print(data,'222 data==',data)
       # dateList=['2022-03-25','2022-03-30']
       # for dateI in dateList:
        #    todayData=data[data.date==dateI]
        #    print(dateI,'Data==',todayData)
        #    todayData=todayData.sort_values('SW_score', ascending=False)
       #     todayData=todayData.reset_index(drop=True)
       #     todayData['SW_p']=todayData.index+1
       #     print(dateI,'222 todayData==',todayData)
        data_1 = DataSource.write_df(data)
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    # 计算不同周期的动量
    def calcu_ret(df):
        df = df.sort_values('date')
        for i in [42, 84, 126]: # 分别代表2月、4月、半年的动量
            df['ret_%s'%i] = df['close']/df['close'].shift(i)-1 
        return df
    
    # 计算出得分
    def seek_head_industry(df):
        for j in ['ret_42','ret_84','ret_126']:
            df['%s'%j] = df['%s'%j].rank(ascending=True) 
        df['SW_score'] = 0.4*df['ret_42']+0.3*df['ret_84']+0.3*df['ret_126']  # 得分的权重分别为0.4、0.3、0.3
        df['SW_code'] = df['instrument']
       # print('result--22---',df)      
        return df
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m10_post_run_bigquant_run(outputs):
        return outputs
    
    # Python 代码入口函数,input_1/2/3 对应三个输入端,data_1/2/3 对应三个输出端
    def m22_run_bigquant_run(inputData,inputSWinfo):
        inputDf=inputData.read()
        inputSW_DF=inputSWinfo.read()
        #print('inputDf==',inputDf)
        dateList=list(inputDf.groupby(['date']).groups.keys())
        #print('dateList==',dateList)
        #dateList['date']=dateList['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
       # print('dateList==',list(dateList))
        out_df = pd.DataFrame()
        for dateI in dateList:
            #print('dateI==',dateI)
            todayData1=inputDf[inputDf.date==dateI]
            todayData1['SW_code'] = todayData1['SW_code'].apply(lambda x:'SW'+str(x)+'.HIX')
            todayData1['date']=todayData1['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
            
            todayData2=inputSW_DF[inputSW_DF.date==dateI]
            #print(dateI,'Data==',todayData)
            todayData2=todayData2.sort_values('SW_score', ascending=False)
            todayData2=todayData2.reset_index(drop=True)
            todayData2['SW_p']=todayData2.index+1
            todayData2['date']=todayData2['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
            #print('todayData1==',todayData1)
            #print('todayData2==',todayData2)
            
            todayData=pd.merge(todayData1,todayData2,suffixes=('_left','_SW'),on=['date','SW_code'],how='inner')
            #print(dateI,' todayData==',todayData)
            out_df=out_df.append(todayData)
        out_df=out_df.reset_index(drop=True)
        #out_df = out_df.reindex(columns=['date','instrument'])
        #out_df['date']=out_df['date'].apply(lambda x:x.strftime('%Y-%m-%d'))
        
        data_1 = DataSource.write_df(out_df)
        print('data_1===\n',data_1.read())
        return Outputs(data_1=data_1, data_2=None, data_3=None)
    
    # 后处理函数,可选。输入是主函数的输出,可以在这里对数据做处理,或者返回更友好的outputs数据格式。此函数输出不会被缓存。
    def m22_post_run_bigquant_run(outputs):
        return outputs
    
    
    # 回测引擎:初始化函数,只执行一次
    def m19_initialize_bigquant_run(context):
        # 加载预测数据
        context.ranker_prediction = context.options['data'].read_df()
    
        # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数
        context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))
        # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)
        # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只
        #context.stock_count = 1
        context.stock_count = 10
        # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]
        #context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, context.stock_count)])
        context.stock_weights = [1/context.stock_count for k in range(context.stock_count)]  #半仓买入,每只股票等资金分配
        # 设置每只股票占用的最大资金比例
        context.max_cash_per_instrument = 0.2
        context.options['hold_days'] = 5
    
        
    
    
    def getMa(today,context,instruments):
        # 加载原始数据
        import datetime
        stock_raw_data = D.history_data(instruments, today+datetime.timedelta(days=-40), today, ['date','close','low'])
        #print('11111',stock_raw_data)
        stock_raw_data=stock_raw_data.iloc[-20:] 
        #stock_raw_data=stock_raw_data[:55]
        #print('22222',stock_raw_data)
        sumMa=0
        lastClose=0
        for index,row in stock_raw_data.iterrows():
            #print(index,row)
            sumMa += row['close']
            lastClose=row['close']
            
        # 包含多个周期均线值的股票数据
       # stock_ma_data = stock_raw_data.groupby('instrument').apply(ma_calculate)
        return [sumMa/20,lastClose]
    
    
    
    # 回测引擎:每日数据处理函数,每天执行一次
    def m19_handle_data_bigquant_run(context, data):
        # 按日期过滤得到今日的预测数据
        #context.ranker_prediction.set_index('date')
        ranker_prediction = context.ranker_prediction[
            context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]
        today = data.current_dt.strftime('%Y-%m-%d')
        # 当日可用资金
        cash_for_buy = context.portfolio.cash
        
        # 获取当日买入列表,每天选取context.stock_count只
        buy_list=[]
        buy1_list = list(ranker_prediction[ranker_prediction.my1 == 1].instrument[:30])
        buy2_list = list(ranker_prediction[ranker_prediction.my2== 1].instrument[:10])
        print(today, '--买一选股-buy1_list==',buy1_list,'===买二选股-buy2_list:', len(buy2_list),buy2_list,)
        if len(buy1_list) > 0 :
            buy_list.append(buy1_list)
        if len(buy2_list) > 0 :
            buy_list.append(buy2_list)
       
        # 获取当前持仓资金
        stock_hold_now = {e.symbol: p.amount * p.last_sale_price
                          for e, p in context.perf_tracker.position_tracker.positions.items() if p.amount>0} 
    
        equities = {e.symbol: p for e, p in context.portfolio.positions.items() if p.amount>0}
        
        # 需要卖出的股票:已有持仓中不在买入列表的股票
        #stock_to_sell = [ i for i in stock_hold_now if i not in buy_list ]
        stock_to_sell = [ i for i in stock_hold_now ]
        #stock_to_buy =  [ i for i in buy_list if i not in stock_hold_now ]
        stock_to_buy1 = [] # [ i for i in buy1_list ] 只测试my2
        stock_to_buy2 =  [ i for i in buy2_list ]
        
        #print(today,' 选股stock_to_buy: ',len(stock_to_buy),' 个: ',stock_to_buy)
        #print(today,' context.ranker_prediction ==: ',context.ranker_prediction)
       # print('ranker_prediction.dtypes',ranker_prediction.dtypes)
    
         # 处理一阳穿多线的买二准备    
       # for i, instrument in enumerate(stock_to_buy):
       #     print(today, i,instrument )
       #     dfinstrument=ranker_prediction[ranker_prediction.instrument==instrument]
       #     junxians=list(dfinstrument['junxian'])
       #     junxian=junxians[0]
            #print(today, i ,' junxian==',junxian)
      #      if(junxian==1):
                # 通过标签赋值
       #         dfinstrument.loc[0,'isReadyBuy2'] = 1
                #dfinstrument.loc[0,'date'] = '2022-03-25'
       #         dfinstrument[dfinstrument['date'] == today] =str(today) + str(datetime.timedelta(days=1))
                #dfinstrument[dfinstrument['date'] == today] = (today.date()+datetime.timedelta(days=1)).strftime('%Y-%m-%d')
                #再处理非交易日和2天后数据也还有该条数据的问题
      #          print(today,' append dfinstrument ',dfinstrument)
       #         dfinstrument.set_index('date')
      #          context.ranker_prediction.append(dfinstrument)
    
                                                     
      #  print(today,' after context.ranker_prediction ==: ',context.ranker_prediction)             
                    
        #stocks=len(stock_hold_now) #?
        stocksBuy1N=0
        stocksBuy2N=0
        stockBuy1_hold_now=[]             
        stockBuy2_hold_now=[]            
        # 卖出列表进行卖出操作
        if len(stock_to_sell)>0:
            for instrument in stock_to_sell:
                sid = context.symbol(instrument) # 将标的转化为equity格式
                cur_position = context.portfolio.positions[sid].amount # 持仓
                if cur_position > 0 and data.can_trade(sid):
                    instruments=[]
                    instruments.append(instrument)  
                    #ri10=getMa(data.current_dt,context,instruments)
                    #print('df after get ma 55==',ri55)
                    try :
                        a=getMa(data.current_dt,context,instruments)
                        ri20=a[0]
                        lastClose=a[1]
                    except :
                        ri20=0
                        lastClose=0
                    #print(instrument,today,'ma10===',ri10,'lastClose===',lastClose)
                    
                    stock_market_price = data.current(context.symbol(instrument), 'price')  # 最新市场价格
                    stock_market_today_high = data.current(context.symbol(instrument), 'high') #今日最高价      
                    stock_market_today_close = data.current(context.symbol(instrument), 'close') #今日收盘价
                    last_sale_date = equities[instrument].last_sale_date   # 上次交易日期
                    last_cost_price = equities[instrument].cost_basis # 上次交易金额
                    delta_days = data.current_dt - last_sale_date  
                    hold_days = delta_days.days # 持仓天数
            # 最高收益
            #high_return = (highclose_price_since_buy-last_cost_price)/last_cost_price
            
                    target_return = stock_market_today_close/last_cost_price
                    #
                    isBuy1=stock_hold_now[instrument]/context.portfolio.portfolio_value
                    #print(instrument,'  isBuy1 or buy2 ==',isBuy1)
                    if isBuy1< 1/30 :  #处理买一订单,买一股票池300,持仓10天轮动,每天30只
                        
                        if hold_days>=10 :
                            context.order_target(sid, 0)
                            print(today,'买一超期卖出 :','收益: ',target_return,sid)
                            cash_for_buy += stock_hold_now[instrument]
                            #stocks = stocks-1
                        #elif target_return>=1.15 :
                        #    context.order_target(sid, 0)
                        #    print(today,'盈利卖出 :','收益: ',target_return,sid)
                        #    cash_for_buy += stock_hold_now[instrument]
                         #   stocks = stocks-1
                        #elif lastClose<ri10 :
                      #     context.order_target(sid, 0)
                      #     print(today,' 跌破10日线止损卖出 ri10=:',ri10,' 收益: ',target_return,sid)
                      #     cash_for_buy += stock_hold_now[instrument]
                      #     stocks = stocks-1
                        elif target_return<=0.92 :
                            context.order_target(sid, 0)
                            print(today,'买一止损卖出 :','收益: ',target_return,sid)
                            cash_for_buy += stock_hold_now[instrument]
                            #stocks = stocks-1
                        else:
                            stockBuy1_hold_now.append(instrument)
                            stocksBuy1N=stocksBuy1N+1
                    else :  #处理买二订单
                        stockBuy2_hold_now.append(instrument)
                        if hold_days>=5 :
                            context.order_target(sid, 0)
                            print(today,'买二超期卖出 :','收益: ',target_return,sid)
                            cash_for_buy += stock_hold_now[instrument]
                            #stocks = stocks-1
                        elif target_return>=1.1 :
                            context.order_target(sid, 0)
                            print(today,'买二盈利卖出 :','收益: ',target_return,sid)
                            cash_for_buy += stock_hold_now[instrument]
                            #stocks = stocks-1
                        elif lastClose<ri20 :
                            context.order_target(sid, 0)
                            print(today,' 买二跌破20日线止损卖出 ri20=:',ri20,' 收益: ',target_return,sid)
                            cash_for_buy += stock_hold_now[instrument]
                            #stocks = stocks-1
                        elif target_return<=0.95 :
                            context.order_target(sid, 0)
                            print(today,'买二止损卖出 :','收益: ',target_return,sid)
                            cash_for_buy += stock_hold_now[instrument]
                           # stocks = stocks-1
                        else:
                            stockBuy2_hold_now.append(instrument)
                            stocksBuy2N=stocksBuy2N+1                        
                 
                    #context.order_target_percent(sid, 0) # 全部卖出
                    # 如果是早盘买早盘卖,卖出的资金可以用于买股票,此时应将下面的注释打开,卖出股票时更新可用现金;
                    # 如果是早盘买尾盘卖,则卖出时不需更新可用现金,因为尾盘卖出股票所得现金无法使用
                    #cash_for_buy += stock_hold_now[instrument]
                    
        # 买入列表执行买操作
        #if len(stock_to_buy)>0:
        #    for instrument,weight in zip(stock_to_buy,context.stock_weights):
        #        sid = context.symbol(instrument) # 将标的转化为equity格式
        #        if data.can_trade(sid):
       #             context.order_target_value(sid, min(cash_for_buy,context.portfolio.portfolio_value*0.5)) # 买入                         
    
        #print(today,'--stockBuy1_hold_now--=:',stockBuy1_hold_now)
        stockBuy1_hold_now
        # 3. 生成买入订单:按机器学习算法预测的排序,买入前面的stock_count只股票
        buy_cash_weights = context.stock_weights
        #buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])
        buy1N=min(30,(300-stocksBuy1N))
        buy2N=min(10,(20-stocksBuy2N))
        buy1_instruments = []
        if len(stock_to_buy1) > 0 :
            buy1_instruments=list(stock_to_buy1[:buy1N])
        buy2_instruments = []
        if len(stock_to_buy2) > 0 :
            buy2_instruments=list(stock_to_buy2[:buy2N])
        #print(today,' buy_instruments:',buy_instruments,'  权重: ',buy_cash_weights)
        max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument
        for i, instrument in enumerate(buy1_instruments):
            #cash = cash_for_buy * buy_cash_weights[i] 
            #cash = context.portfolio.portfolio_value * buy_cash_weights[i]
             #用20分1的资金买一(300zhi)
            cash = (cash_for_buy/20)/(200-stocksBuy1N)
            #print('cash_for_buy==',cash_for_buy, ' cash==',cash)
            #if cash > max_cash_per_instrument - stock_hold_now.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
            #    cash = max_cash_per_instrument - stock_hold_now.get(instrument, 0)
            if cash > 0:
                 if instrument not in stockBuy1_hold_now :  #不重复买入
                    context.order_value(context.symbol(instrument), cash)
                   # print(today,' 买入一买 ',instrument)
                  
        for i, instrument in enumerate(buy2_instruments):
            #cash = cash_for_buy * buy_cash_weights[i] 
            #cash = context.portfolio.portfolio_value * buy_cash_weights[i]
            cash = (cash_for_buy*0.9)/(20-stocksBuy2N)
            #print('cash_for_buy==',cash_for_buy, ' cash==',cash)
           # if cash > max_cash_per_instrument - stock_hold_now.get(instrument, 0):
                # 确保股票持仓量不会超过每次股票最大的占用资金量
            #    cash = max_cash_per_instrument - stock_hold_now.get(instrument, 0)
            if cash > 0:
                #if instrument in stockBuy1_hold_now :
                    context.order_value(context.symbol(instrument), cash)
                    print(today,' 买入二买 ',instrument)
               # else:
               #     print(today,' 发现二买,但没有一买,放弃买入:---',instrument)
            else:
                print(today,' 无资金买入二买 ',instrument)
                  
                
    # 回测引擎:准备数据,只执行一次
    def m19_prepare_bigquant_run(context):
        pass
    
    
    m1 = M.instruments.v2(
        start_date='2017-01-01',
        end_date='2021-01-01',
        market='CN_STOCK_A',
        instrument_list='',
        max_count=0
    )
    
    m2 = M.advanced_auto_labeler.v2(
        instruments=m1.data,
        label_expr="""# #号开始的表示注释
    # 0. 每行一个,顺序执行,从第二个开始,可以使用label字段
    # 1. 可用数据字段见 https://bigquant.com/docs/data_history_data.html
    #   添加benchmark_99】【前缀,可使用对应的benchmark数据
    # 2. 可用操作符和函数见 `表达式引擎 <https://bigquant.com/docs/big_expr.html>`_
    
    # 计算收益:5日收盘价(作为卖出价格)除以明日开盘价(作为买入价格)
    shift(close, -3) / shift(open, -1)
    
    # 极值处理:用1%和99%分位的值做clip
    clip(label, all_quantile(label, 0.01), all_quantile(label, 0.99))
    
    # 将分数映射到分类,这里使用20个分类
    all_wbins(label, 20)
    
    # 过滤掉一字涨停的情况 (设置label为NaN,在后续处理和训练中会忽略NaN的label)
    where(shift(high, -1) == shift(low, -1), NaN, label)
    """,
        start_date='',
        end_date='',
        benchmark='000300.SHA',
        drop_na_label=True,
        cast_label_int=True
    )
    
    m3 = M.input_features.v1(
        features="""# #号开始的表示注释
    # 多个特征,每行一个,可以包含基础特征和衍生特征
    close_0/mean(close_0,5)
    close_0/mean(close_0,10)
    close_0/mean(close_0,20)
    close_0/open_0
    open_0/mean(close_0,5)
    open_0/mean(close_0,10)
    open_0/mean(close_0,20)
    avg_turn_0/avg_turn_5
    avg_turn_0/avg_turn_10
    mf_net_pct_main_0"""
    )
    
    m15 = M.general_feature_extractor.v7(
        instruments=m1.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=0
    )
    
    m16 = M.derived_feature_extractor.v3(
        input_data=m15.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=False,
        remove_extra_columns=False
    )
    
    m7 = M.join.v3(
        data1=m2.data,
        data2=m16.data,
        on='date,instrument',
        how='inner',
        sort=False
    )
    
    m5 = M.dropnan.v2(
        input_data=m7.data
    )
    
    m4 = M.stock_ranker_train.v6(
        training_ds=m5.data,
        features=m3.data,
        learning_algorithm='排序',
        number_of_leaves=30,
        minimum_docs_per_leaf=1000,
        number_of_trees=20,
        learning_rate=0.1,
        max_bins=1023,
        feature_fraction=1,
        data_row_fraction=1,
        plot_charts=True,
        ndcg_discount_base=1,
        m_lazy_run=False
    )
    
    m9 = M.instruments.v2(
        start_date=T.live_run_param('trading_date', '2021-03-01'),
        end_date=T.live_run_param('trading_date', '2022-04-28'),
        market='CN_STOCK_A',
        instrument_list="""300505.SZA
    002226.SZA""",
        max_count=0
    )
    
    m17 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m3.data,
        start_date='',
        end_date='',
        before_start_days=258
    )
    
    m18 = M.derived_feature_extractor.v3(
        input_data=m17.data,
        features=m3.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=True,
        remove_extra_columns=False
    )
    
    m12 = M.input_features.v1(
        features="""#600335.SHA
    #300061.SZA
    #300364.SZA
    #002173.SZA
    #002433.SZA
    #601020.SHA
    #000545.SZA
    #000514.SZA
    #300505.SZA
    #002226.SZA
    #300299.SZA
    #600425.SHA
    #000632.SZA
    #002060.SZA
    
    #gaodianN5=where(ts_argmax(high_0, 258*5)<800,1,0)
    #gaodianN4=where(ts_argmax(high_0, 258*4)<800,1,0)
    #5年高点,1年按258个交易日算
    #isgaodian=max(gaodianN5,gaodianN4)
    
    #1年低点,1年按258个交易日算
    #didianN=ts_argmin(low_0, 258*1)
    #isdidian=where(didianN<200.0,1,0)
    
    #半年高点,1年按258个交易日算
    banniangaodianN=ts_argmax(high_0, 128)
    isbanniangaodian=where(banniangaodianN<80.0,1,0)
    
    #timeperiod移动平均线
    #zhouma34=ta_ma(close_0, timeperiod=166)
    #timeperiod移动平均线
    zhouma55=ta_ma(close_0, timeperiod=258)
    #在周55均线之上,
    isupzhou55=where(close_0>zhouma55,1,0)
    #回调程度
    huitiaodu=ts_max(high_0, 128)/low_1
    
    #反弹比例,选比例最高的10-20只交易,后面调试
    #yiniandidian=ts_min(low_0, 258*1)
    banniangaodian=ts_max(high_0, 128*1)
    #fantanbili=banniangaodian/yiniandidian
    
    #macd1=ta_macd_macd_12_26_9_0
    #macd2=ta_macd_macdhist_12_26_9_0
    #macd3=ta_macd_macdsignal_12_26_9_0
    #sw1=swing_volatility_5_0 #振幅波动率,timeperiod=5* 取值: , 5, 10, 30, 60, 120, 240
    #sw2=swing_volatility_10_0
    #sw3=swing_volatility_30_0
    #sw4=swing_volatility_60_0
    vl1=volatility_5_0 #波动率,timeperiod=240* 取值: , 5, 10, 30, 60, 120, 240
    vl2=volatility_10_0
    vl3=volatility_30_0
    #vl4=volatility_60_0
    
    
    macd_dif=ta_macd_dif(close_0/adjust_factor_0)
    macd_h=ta_macd_hist(close_0/adjust_factor_0)
    duanqiup1=where(low_0>low_1,1,0)
    duanqiup2=where(macd_h>shift(macd_h,1),1,0)
    duanqiup=max(duanqiup1,duanqiup2)
    
    
    #st_status_0
    #my1==1&(vl2<vl3)&(vl2>0.012)&(vl2<0.038)&(macd1<0)&date>'2022-04-01'
    #my1=where((isbanniangaodian==1)&\
    #          (huitiaodu>1.2)&\
    #          (vl2<vl3)&(vl2>0.012)&(vl2<0.038)&(st_status_0==0),1,0)
    
    my1=where((huitiaodu>1.2)&\
              (vl2<vl3)&(vl2>0.012)&(vl2<0.038)&(st_status_0==0),1,0)
    
    #isgaodian==1&isdidian==1&isbanniangaodian==1&isbanniangaodian==1&fantanbili>1.5&date>='2022-03-08'
    #调试一下不要半年高点?只要回调度,不管什么时候回调的?涨停上穿也算
    
    #按前一天算ma,即线重合后第三天再买如
    ma5=ta_ma(close_0, timeperiod=5)
    ma10=ta_ma(close_0, timeperiod=10)
    ma13=ta_ma(close_0, timeperiod=13)
    ma20=ta_ma(close_0, timeperiod=20)
    ma34=ta_ma(close_0, timeperiod=34)
    ma55=ta_ma(close_0, timeperiod=55)
    
    #4-5线重合 真阳线 后面再调试是否要过滤returen0《5-8;-这样可以亏损幅度可以小一些;再调试回调幅度是否要大于1.5
    #junxian=where((ma5<=high_0) & (ma10<=high_0) & (ma13<=high_0) &(ma20<=high_0) & (ma34<=high_0) & (ma55<=high_0) &\
    #              (ma5 >=low_0) & (ma10>=low_0) & (ma13>=low_0) & (ma20>=low_0) &  (ma34>=low_0) & (ma55>=low_0) &\
    #              (return_0>1.01)&(close_0>open_0)&(return_0<1.08)&(isbanniangaodian==1),1,0) 
    #试试2日穿阳
    junxian=where((ma5<=high_0) & (ma10<=high_0) & (ma13<=high_0) &(ma20<=high_0) & (ma34<=high_0) & (ma55<=high_0) &\
                 (return_0>1.01)&(close_0>open_0)&(return_0<1.08),1,0) 
    
    maxline=max(ma5, ma10,ma13, ma20,ma34,ma55)
    minline=min(ma5, ma10,ma13, ma20,ma34,ma55)
    zhanshang55=close_0/maxline
    #4-5线重合度
    junxianchonghedu=minline/maxline
    junxianchonghedu5=shift(junxianchonghedu,5)
    junxianchonghedu18=shift(junxianchonghedu,18)
    # volume_* 第前 * 个交易日的交易量* 取值: 0 .. 20
    #一阳穿线需要放量1.5倍以上,后面调试.  #nanmean(x, d), #过去 d 天 x 的均值(去除NaN值)
    
    fanliang=volume_0/volume_1  #放量
    deaLn=deal_number_0/deal_number_1
    daDan=fanliang/deaLn  #交易笔数放量比不上交易额放量,说明是大单进入多,用大于1.18进行调试
    
    #my2ready=where((isbanniangaodian==1)&(junxian==1)&(zhanshang55>=1.0)&
                   #(junxianchonghedu>0.94)&(huitiaodu>1.15)&(fanliang>1.45)&(daDan>1.18),1,0)    #需要收拢条件
    my2ready=where((junxian==1)&(zhanshang55>=1.0)&\
                   (junxianchonghedu>junxianchonghedu5)&(junxianchonghedu5>junxianchonghedu18)&\
                   (junxianchonghedu>0.95)&(huitiaodu>1.15)&(fanliang>1.5)&(daDan>1.2),1,0)
    my2=where((shift(my2ready,1)==1)&(low_0>low_1)&(close_0>=ma5),1,0)
    #low_0>low_1这个条件太松了
    #最好不离55线太远,--my1使用
    nearMa55=ma55/close_0
    
    SW_code=industry_sw_level1_0
    myrank=rank_fs_roe_ttm_0+rank_fs_net_profit_qoq_0-rank_pb_lf_0
    
    pe_ttm_0 #滚动市盈率
    fs_eps_0 #每股收益
    fs_eps_yoy_0 #每股收益同比增长率
    fs_bps_0 #每股净资产
    fs_roa_ttm_0 #总资产报酬率 (TTM)
    
    #isbanniangaodian==1&junxian==1&zhanshang55>1&junxianchonghedu>0.95&huitiaodu>1.3&date>='2022-01-01'
    my=max(my1,my2)"""
    )
    
    m13 = M.general_feature_extractor.v7(
        instruments=m9.data,
        features=m12.data,
        start_date='',
        end_date='',
        before_start_days=580
    )
    
    m21 = M.derived_feature_extractor.v3(
        input_data=m13.data,
        features=m12.data,
        date_col='date',
        instrument_col='instrument',
        drop_na=True,
        remove_extra_columns=False,
        user_functions={}
    )
    
    m14 = M.filter.v3(
        input_data=m21.data,
        expr='date>=\'2022-03-10\'',
        output_left_data=False
    )
    
    m20 = M.join.v3(
        data1=m14.data,
        data2=m18.data,
        on='date,instrument',
        how='left',
        sort=False
    )
    
    m8 = M.stock_ranker_predict.v5(
        model=m4.model,
        data=m20.data,
        m_lazy_run=False
    )
    
    m11 = M.join.v3(
        data1=m8.predictions,
        data2=m14.data,
        on='date,instrument',
        how='left',
        sort=False
    )
    
    m6 = M.cached.v3(
        run=m6_run_bigquant_run,
        post_run=m6_post_run_bigquant_run,
        input_ports='',
        params='{}',
        output_ports='data_1'
    )
    
    m10 = M.cached.v3(
        run=m10_run_bigquant_run,
        post_run=m10_post_run_bigquant_run,
        input_ports='',
        params='{}',
        output_ports='data_1'
    )
    
    m22 = M.cached.v3(
        input_1=m11.data,
        input_2=m10.data_1,
        run=m22_run_bigquant_run,
        post_run=m22_post_run_bigquant_run,
        input_ports='',
        params='{}',
        output_ports='data_1'
    )
    
    m19 = M.trade.v4(
        instruments=m9.data,
        options_data=m22.data_1,
        start_date='',
        end_date='',
        initialize=m19_initialize_bigquant_run,
        handle_data=m19_handle_data_bigquant_run,
        prepare=m19_prepare_bigquant_run,
        volume_limit=0.025,
        order_price_field_buy='twap_1',
        order_price_field_sell='twap_1',
        capital_base=10000000,
        auto_cancel_non_tradable_orders=True,
        data_frequency='daily',
        price_type='后复权',
        product_type='股票',
        plot_charts=True,
        backtest_only=False,
        benchmark=''
    )
    
    设置评估测试数据集,查看训练曲线
    [视频教程]StockRanker训练曲线
    bigcharts-data-start/{"__type":"tabs","__id":"bigchart-cb97c099ae4a4d719f8082f2ce63e81a"}/bigcharts-data-end
    data_1===
               date  instrument     score  position  adjust_factor_0    close_0  \
    0   2022-03-10  002226.SZA  0.334925         1        12.765221  73.782974   
    1   2022-03-10  300505.SZA  0.269226         2         1.331137  40.719482   
    2   2022-03-11  300505.SZA  0.194691         1         1.331137  40.493187   
    3   2022-03-11  002226.SZA  0.193227         2        12.765221  74.293587   
    4   2022-03-14  002226.SZA  0.260441         1        12.765221  74.931847   
    5   2022-03-14  300505.SZA  0.228725         2         1.331137  39.934109   
    6   2022-03-15  002226.SZA  0.367409         1        12.765221  72.251152   
    7   2022-03-15  300505.SZA  0.115725         2         1.331137  37.657867   
    8   2022-03-16  002226.SZA  0.187927         1        12.765221  74.038284   
    9   2022-03-16  300505.SZA  0.098299         2         1.331137  38.975693   
    10  2022-03-17  002226.SZA  0.215069         1        12.765221  73.527672   
    11  2022-03-17  300505.SZA  0.157976         2         1.331137  38.602974   
    12  2022-03-18  002226.SZA  0.234232         1        12.765221  76.974281   
    13  2022-03-18  300505.SZA  0.080104         2         1.331137  39.135429   
    14  2022-03-21  002226.SZA  0.286523         1        12.765221  77.740196   
    15  2022-03-21  300505.SZA  0.249216         2         1.331137  39.508144   
    16  2022-03-22  002226.SZA  0.214097         1        12.765221  78.250801   
    17  2022-03-22  300505.SZA  0.065792         2         1.331137  39.042248   
    18  2022-03-23  002226.SZA  0.325332         1        12.765221  77.357239   
    19  2022-03-23  300505.SZA  0.041683         2         1.331137  38.895824   
    20  2022-03-24  300505.SZA  0.194812         1         1.331137  40.559746   
    21  2022-03-24  002226.SZA -0.235488         2        12.765221  85.144028   
    22  2022-03-25  300505.SZA  0.228303         1         1.331137  40.919151   
    23  2022-03-25  002226.SZA  0.038537         2        12.765221  83.995155   
    24  2022-03-28  300505.SZA  0.186878         1         1.331137  42.543140   
    25  2022-03-28  002226.SZA  0.143926         2        12.765221  81.952721   
    26  2022-03-29  002226.SZA  0.014649         1        12.765221  84.122803   
    27  2022-03-29  300505.SZA -0.443747         2         1.331137  48.573189   
    28  2022-03-30  002226.SZA  0.321298         1        12.765221  82.208023   
    29  2022-03-30  300505.SZA -0.294600         2         1.331137  49.944260   
    30  2022-03-31  002226.SZA  0.247716         1        12.765221  82.208023   
    31  2022-03-31  300505.SZA -0.243747         2         1.331137  49.212135   
    32  2022-04-01  002226.SZA  0.340346         1        12.765221  78.761414   
    33  2022-04-01  300505.SZA -0.243747         2         1.331137  50.556583   
    34  2022-04-06  002226.SZA  0.052459         1        12.765221  79.782631   
    35  2022-04-06  300505.SZA -0.243747         2         1.331137  50.969234   
    36  2022-04-07  002226.SZA  0.193706         1        12.765221  77.612541   
    37  2022-04-07  300505.SZA -0.294600         2         1.331137  55.375298   
    38  2022-04-08  002226.SZA  0.160832         1        12.765221  79.782631   
    39  2022-04-08  300505.SZA -0.377721         2         1.331137  61.977737   
    40  2022-04-11  002226.SZA  0.112754         1        12.765221  81.697418   
    41  2022-04-11  300505.SZA -0.347004         2         1.331137  60.739780   
    42  2022-04-12  002226.SZA  0.002518         1        12.765221  80.548546   
    43  2022-04-12  300505.SZA -0.129649         2         1.331137  57.358692   
    44  2022-04-13  002226.SZA  0.135575         1        12.765221  79.016716   
    45  2022-04-13  300505.SZA  0.135008         2         1.331137  54.576618   
    46  2022-04-14  002226.SZA  0.233960         1        12.765221  79.272026   
    47  2022-04-14  300505.SZA -0.132275         2         1.331137  59.035927   
    48  2022-04-15  300505.SZA  0.388372         1         1.331137  52.979252   
    49  2022-04-15  002226.SZA  0.120222         2        12.765221  74.421242   
    50  2022-04-18  300505.SZA  0.207534         1         1.331137  53.618198   
    51  2022-04-18  002226.SZA  0.169544         2        12.765221  75.570107   
    52  2022-04-19  002226.SZA  0.417717         1        12.765221  78.633759   
    53  2022-04-19  300505.SZA  0.064575         2         1.331137  55.854507   
    54  2022-04-20  300505.SZA  0.326898         1         1.331137  53.937672   
    55  2022-04-20  002226.SZA  0.100062         2        12.765221  76.974281   
    56  2022-04-21  300505.SZA  0.585492         1         1.331137  48.320274   
    57  2022-04-21  002226.SZA  0.106364         2        12.765221  71.868195   
    58  2022-04-22  300505.SZA -0.001019         1         1.331137  46.456680   
    59  2022-04-22  002226.SZA -0.005751         2        12.765221  72.378799   
    
        deal_number_0  deal_number_1  fs_bps_0  fs_eps_0  ...    myrank  \
    0           37661          25296    3.8987    0.2982  ...  0.733463   
    1           19660          15816    8.5900    0.7511  ...  0.643135   
    2           18631          19660    8.5900    0.7511  ...  0.651307   
    3           23717          37661    3.8987    0.2982  ...  0.731797   
    4           43946          23717    3.8987    0.2982  ...  0.831930   
    5           18941          18631    8.5900    0.7511  ...  0.641138   
    6           32806          43946    3.8987    0.2982  ...  0.824213   
    7           15603          18941    8.5900    0.7511  ...  0.642944   
    8           32264          32806    3.8987    0.2982  ...  0.826104   
    9           13858          15603    8.5900    0.7511  ...  0.639388   
    10          30523          32264    3.8987    0.2982  ...  0.837164   
    11          12741          13858    8.5900    0.7511  ...  0.658730   
    12          38253          30523    3.8987    0.2982  ...  0.824240   
    13          13502          12741    8.5900    0.7511  ...  0.655189   
    14          38282          38253    3.8987    0.2982  ...  0.827671   
    15          12528          13502    8.5900    0.7511  ...  0.658565   
    16          30260          38282    3.8987    0.2982  ...  0.827889   
    17          11554          12528    8.5900    0.7511  ...  0.663520   
    18          24074          30260    3.8987    0.2982  ...  0.832502   
    19           8232          11554    8.5900    0.7511  ...  0.668994   
    20          21227           8232    8.5900    0.7511  ...  0.632860   
    21          36009          24074    3.8987    0.2982  ...  0.775073   
    22          20741          21227    8.5900    0.7511  ...  0.624394   
    23          67135          36009    3.8987    0.2982  ...  0.785275   
    24          22365          20741    8.5900    0.7511  ...  0.600694   
    25          42767          67135    3.8987    0.2982  ...  0.797339   
    26          50419          42767    3.2248    0.3974  ...  1.329865   
    27          48597          22365    8.5900    0.7511  ...  0.529693   
    28          28061          50419    3.2248    0.3974  ...  1.348424   
    29          41849          48597   10.0266    1.4159  ...  0.851961   
    30          30907          28061    3.2248    0.3974  ...  1.345323   
    31          34141          41849   10.0266    1.4159  ...  0.851617   
    32          23192          30907    3.2248    0.3974  ...  1.366089   
    33          46284          34141   10.0266    1.4159  ...  0.834315   
    34          20759          23192    3.2248    0.3974  ...  1.366439   
    35          42068          46284   10.0266    1.4159  ...  0.831471   
    36          17941          20759    3.2248    0.3974  ...  1.366357   
    37          57040          42068   10.0266    1.4159  ...  0.777467   
    38          26214          17941    3.2248    0.3974  ...  1.351129   
    39          67910          57040   10.0266    1.4159  ...  0.733226   
    40          41765          26214    3.2248    0.3974  ...  1.312571   
    41          56185          67910   10.0266    1.4159  ...  0.726744   
    42          29030          41765    3.2248    0.3974  ...  1.332198   
    43          50054          56185   10.0266    1.4159  ...  0.743499   
    44          24596          29030    3.2248    0.3974  ...  1.330013   
    45          56439          50054   10.0266    1.4159  ...  0.755597   
    46          19086          24596    3.2248    0.3974  ...  1.332921   
    47          67899          56439   10.0266    1.4159  ...  0.730969   
    48          61826          67899   10.0266    1.4159  ...  0.762431   
    49          21646          19086    3.2248    0.3974  ...  1.356904   
    50          55614          61826   10.0266    1.4159  ...  0.759764   
    51          24701          21646    3.2248    0.3974  ...  1.349151   
    52          24361          24701    3.2248    0.3974  ...  1.322859   
    53          50643          55614   10.0266    1.4159  ...  0.737426   
    54          55534          50643   10.0266    1.4159  ...  0.744594   
    55          23785          24361    3.2248    0.3974  ...  1.331308   
    56          62553          55534   10.0266    1.4159  ...  0.772244   
    57          34044          23785    3.2248    0.3974  ...  1.349201   
    58          46956          62553   10.0266    1.4159  ...  0.772140   
    59          19057          34044    3.2248    0.3974  ...  1.332696   
    
        pe_ttm_0 #滚动市盈率  fs_eps_0 #每股收益  fs_eps_yoy_0 #每股收益同比增长率  fs_bps_0 #每股净资产  \
    0         26.708723          0.2982                32.005314           3.8987   
    1         50.157150          0.7511                99.495354           8.5900   
    2         49.878407          0.7511                99.495354           8.5900   
    3         26.893559          0.2982                32.005314           3.8987   
    4         14.771270          0.2982                32.005314           3.8987   
    5         49.189751          0.7511                99.495354           8.5900   
    6         14.242826          0.2982                32.005314           3.8987   
    7         46.385937          0.7511                99.495354           8.5900   
    8         14.595122          0.2982                32.005314           3.8987   
    9         48.009197          0.7511                99.495354           8.5900   
    10        14.494466          0.2982                32.005314           3.8987   
    11        47.550091          0.7511                99.495354           8.5900   
    12        15.173894          0.2982                32.005314           3.8987   
    13        48.205956          0.7511                99.495354           8.5900   
    14        15.324878          0.2982                32.005314           3.8987   
    15        48.665062          0.7511                99.495354           8.5900   
    16        15.425534          0.2982                32.005314           3.8987   
    17        48.091179          0.7511                99.495354           8.5900   
    18        15.249386          0.2982                32.005314           3.8987   
    19        47.910816          0.7511                99.495354           8.5900   
    20        49.960392          0.7511                99.495354           8.5900   
    21        16.784389          0.2982                32.005314           3.8987   
    22        50.403099          0.7511                99.495354           8.5900   
    23        16.557915          0.2982                32.005314           3.8987   
    24        52.403481          0.7511                99.495354           8.5900   
    25        16.155291          0.2982                32.005314           3.8987   
    26        16.583078          0.3974               135.566101           3.2248   
    27        59.831135          0.7511                99.495354           8.5900   
    28        16.205618          0.3974               135.566101           3.2248   
    29        29.726673          1.4159               344.692200          10.0266   
    30        16.205618          0.3974               135.566101           3.2248   
    31        29.290915          1.4159               344.692200          10.0266   
    32        15.526190          0.3974               135.566101           3.2248   
    33        30.091125          1.4159               344.692200          10.0266   
    34        15.727502          0.3974               135.566101           3.2248   
    35        30.336735          1.4159               344.692200          10.0266   
    36        15.299714          0.3974               135.566101           3.2248   
    37        32.959209          1.4159               344.692200          10.0266   
    38        15.727502          0.3974               135.566101           3.2248   
    39        36.888962          1.4159               344.692200          10.0266   
    40        16.104961          0.3974               135.566101           3.2248   
    41        36.152134          1.4159               344.692200          10.0266   
    42        15.878486          0.3974               135.566101           3.2248   
    43        34.139721          1.4159               344.692200          10.0266   
    44        15.576518          0.3974               135.566101           3.2248   
    45        32.483837          1.4159               344.692200          10.0266   
    46        15.626846          0.3974               135.566101           3.2248   
    47        35.138004          1.4159               344.692200          10.0266   
    48        31.533091          1.4159               344.692200          10.0266   
    49        14.670614          0.3974               135.566101           3.2248   
    50        31.913389          1.4159               344.692200          10.0266   
    51        14.897090          0.3974               135.566101           3.2248   
    52        15.501026          0.3974               135.566101           3.2248   
    53        33.244434          1.4159               344.692200          10.0266   
    54        32.103539          1.4159               344.692200          10.0266   
    55        15.173894          0.3974               135.566101           3.2248   
    56        28.760080          1.4159               344.692200          10.0266   
    57        14.167334          0.3974               135.566101           3.2248   
    58        27.650877          1.4159               344.692200          10.0266   
    59        14.267990          0.3974               135.566101           3.2248   
    
        fs_roa_ttm_0 #总资产报酬率 (TTM)  my  SW_score  name  SW_p  
    0                       8.4487   0   27074.2  基础化工    15  
    1                       6.4608   1   27074.2  基础化工    15  
    2                       6.4608   1   32244.8  基础化工    12  
    3                       8.4487   0   32244.8  基础化工    12  
    4                       8.4487   0   24769.7  基础化工    12  
    5                       6.4608   1   24769.7  基础化工    12  
    6                       8.4487   0   16721.4  基础化工    13  
    7                       6.4608   1   16721.4  基础化工    13  
    8                       8.4487   0   20424.8  基础化工    15  
    9                       6.4608   1   20424.8  基础化工    15  
    10                      8.4487   0   23014.8  基础化工    16  
    11                      6.4608   1   23014.8  基础化工    16  
    12                      8.4487   0   23122.9  基础化工    14  
    13                      6.4608   1   23122.9  基础化工    14  
    14                      8.4487   0   26372.3  基础化工    12  
    15                      6.4608   0   26372.3  基础化工    12  
    16                      8.4487   0   26139.5  基础化工    11  
    17                      6.4608   0   26139.5  基础化工    11  
    18                      8.4487   0   24941.5  基础化工    12  
    19                      6.4608   0   24941.5  基础化工    12  
    20                      6.4608   1   25615.0  基础化工    11  
    21                      8.4487   0   25615.0  基础化工    11  
    22                      6.4608   1   23908.1  基础化工    12  
    23                      8.4487   0   23908.1  基础化工    12  
    24                      6.4608   1   24336.9  基础化工    12  
    25                      8.4487   0   24336.9  基础化工    12  
    26                     10.6420   0   26964.9  基础化工    11  
    27                      6.4608   0   26964.9  基础化工    11  
    28                     10.6420   0   30014.4  基础化工    11  
    29                     10.2092   0   30014.4  基础化工    11  
    30                     10.6420   0   30460.3  基础化工    12  
    31                     10.2092   0   30460.3  基础化工    12  
    32                     10.6420   0   30429.8  基础化工    14  
    33                     10.2092   0   30429.8  基础化工    14  
    34                     10.6420   0   34021.9  基础化工    16  
    35                     10.2092   0   34021.9  基础化工    16  
    36                     10.6420   0   33747.8  基础化工    13  
    37                     10.2092   0   33747.8  基础化工    13  
    38                     10.6420   0   36100.9  基础化工     9  
    39                     10.2092   0   36100.9  基础化工     9  
    40                     10.6420   1   29138.8  基础化工     9  
    41                     10.2092   0   29138.8  基础化工     9  
    42                     10.6420   0   28961.3  基础化工    12  
    43                     10.2092   0   28961.3  基础化工    12  
    44                     10.6420   0   24276.9  基础化工    12  
    45                     10.2092   0   24276.9  基础化工    12  
    46                     10.6420   0   29553.5  基础化工    10  
    47                     10.2092   0   29553.5  基础化工    10  
    48                     10.2092   0   25989.8  基础化工    11  
    49                     10.6420   0   25989.8  基础化工    11  
    50                     10.2092   0   25784.7  基础化工    10  
    51                     10.6420   0   25784.7  基础化工    10  
    52                     10.6420   1   26941.7  基础化工     9  
    53                     10.2092   0   26941.7  基础化工     9  
    54                     10.2092   0   20576.6  基础化工    12  
    55                     10.6420   0   20576.6  基础化工    12  
    56                     10.2092   0   13614.6  基础化工    15  
    57                     10.6420   0   13614.6  基础化工    15  
    58                     10.2092   0   11884.0  基础化工    18  
    59                     10.6420   1   11884.0  基础化工    18  
    
    [60 rows x 73 columns]