def operate_st(action_type): """ 将st内容,转换成标签添加在对应code下 """ f = h5py.File(conf.HDF5_FILE_BASIC, 'a') console.write_head(action_type, conf.HDF5_RESOURCE_TUSHARE, conf.HDF5_BASIC_ST) path = '/' + conf.HDF5_BASIC_ST # 如果文件不存在,则退出 if f.get(path) is None: console.write_msg("st的detail文件不存在") return st_df = tool.df_from_dataset(f[path], conf.HDF5_BASIC_ST, None) if st_df is not None and st_df.empty is not True: st_df["code"] = st_df["code"].str.decode("utf-8") # 将st内容,转换成标签添加在对应code下 tool.op_attr_by_codelist(action_type, st_df["code"].values, conf.HDF5_BASIC_ST, True) else: console.write_msg("st的detail数据获取失败") console.write_tail() f.close() return
def monitor(): global monitor_timer global wallet_amount global strategy_dict global exec_level # 仓位倍率 factor_multi = 0.01 factor_price_range = 5 for code in strategy_dict: try: obj = strategy_dict[code] # 更新数据并检查 obj.update() ret = obj.check_new() console.write_msg("时间%s,bar的操作结果:%s" % (obj.small.iloc[-1]["date"], ret)) if ret is not False: obj.output() # 1.结算上次交易 # 如果仓位小于0,则卖空需要赎回,如果仓位大于0,则做多需要卖出 current_position = account.position(10) current = current_position["current"] if current != 0: if current > 0: side = order.SIDE_SELL elif current < 0: side = order.SIDE_BUY result = order.create_contract(code, side, abs(current), order.TYPE_MARKET) if result["price"]: msg = "合约%s兑现, 操作%s, 份额%f,价格%f, 下单成功" console.write_msg( msg % (code, side, abs(current), result["price"])) # 2.更新钱包数额(暂时不更新钱包) # wallet_detail = account.wallet() # wallet_amount = wallet_detail['amount'] # 3.判断交易类别,进行做空或做多 # 方案A,取两者的平均值,基本很难触发(已舍弃) # 方案B,取最新价格的偏差,目前固定为5(低级别不适用) trend_price = obj.small.iloc[-1]["close"] amount = wallet_amount * factor_multi if ret == conf.BUY_SIDE: price = trend_price - factor_price_range result = order.create_simple(code, order.SIDE_BUY, amount, order.TYPE_LIMIT, price) elif ret == conf.SELL_SIDE: price = trend_price + factor_price_range result = order.create_simple(code, order.SIDE_SELL, amount, order.TYPE_LIMIT, price) else: raise Exception("交易类别异常") if result["price"]: msg = "合约%s, 操作%s, 份额%f,价格%f, 下单成功" console.write_msg(msg % (code, ret, amount, price)) else: print(result) # 4.标记过期时间 result = order.cancel_all_after(30000) if result["cancelTime"]: console.write_msg("预计过期时间:%s" % (result["cancelTime"])) else: print(result) except Exception as er: print(obj.small.tail(10)) print(obj.phase.tail(10)) print(str(er)) exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print(exc_type, fname, exc_tb.tb_lineno) sys.exit(2) if exec_level == conf.BINSIZE_FIVE_MINUTE: time_span = "5" elif exec_level == conf.BINSIZE_ONE_MINUTE: time_span = "1" else: raise Exception("级别异常") remain_second = tradetime.get_remain_second(time_span) monitor_timer = threading.Timer(remain_second + 2, monitor) monitor_timer.start() return
def output(self): now = self.trade.iloc[-1] console.write_msg( "【%s, %s, %s】" % (self.code, now[conf.HDF5_SHARE_DATE_INDEX], now["type"])) msg = "个股5min,趋势%s,连续%d次,macd趋势%f, macd差值%d%%" console.write_msg( msg % (now[DF_FIVE + TRADE_STATUS], now[DF_FIVE + TRADE_TREND_COUNT], now[DF_FIVE + TRADE_MACD_PHASE], now[DF_FIVE + TRADE_MACD_DIFF])) dtype_dict = { DF_THIRTY: "个股30min", DF_BIG: "个股大趋势", DF_INDEX: "指数30min", } for dtype in dtype_dict: msg = "%s,趋势%s,连续%d次,macd趋势%f, macd差值%d%%" console.write_msg( msg % (dtype_dict[dtype], now[dtype + TRADE_STATUS], now[dtype + TRADE_TREND_COUNT], now[dtype + TRADE_MACD_PHASE], now[dtype + TRADE_MACD_DIFF])) # TODO 背离情况要计算两次买卖点trend_count的差值 trend_count = now[DF_FIVE + TRADE_TREND_COUNT] upper_estimate = (trend_count + 1) * 5 lower_estimate = (trend_count - 1) * 5 if self.stype == conf.STYPE_ASHARE: remain_seconds = tradetime.get_ashare_remain_second( now[conf.HDF5_SHARE_DATE_INDEX]) remain_minutes = round(remain_seconds / 60, 0) msg = "剩余时间%d分钟,下个交易点预估需要%d-%d分钟,模式%s" if (upper_estimate * 60) <= remain_seconds: trade_opportunity = "T+0" else: trade_opportunity = "T+1" console.write_msg(msg % (remain_minutes, lower_estimate, upper_estimate, trade_opportunity)) elif self.stype == conf.STYPE_BITMEX: msg = "下个交易点预估需要%d-%d分钟" console.write_msg(msg % (lower_estimate, upper_estimate)) console.write_msg("建议仓位:%d/3" % (now[TRADE_POSITIONS])) console.write_blank() return
def all_exec(omit_list): """ 筛选出存在背离的股票 """ # 筛选记录内容如下: # 1. 月线macd趋势 # 2. 周线macd趋势 # 3. 日线macd趋势,是否背离,数值差距 # 4. 30min的macd趋势,是否背离,数值差距,震荡中枢数量 # 5. 5min的macd趋势,是否背离,数值差距,震荡中枢数量 console.write_head(conf.HDF5_OPERATE_SCREEN, conf.HDF5_RESOURCE_TUSHARE, conf.STRATEGY_TREND_AND_REVERSE) f = h5py.File(conf.HDF5_FILE_SHARE, 'a') filter_df = tool.init_empty_df(_ini_filter_columns()) for code_prefix in f: if code_prefix in omit_list: continue for code in f[code_prefix]: code_group_path = '/' + code_prefix + '/' + code if f.get(code_group_path) is None: console.write_blank() console.write_msg(code + "的tushare数据不存在") continue # 忽略停牌、退市、无法获取的情况 if f[code_prefix][code].attrs.get( conf.HDF5_BASIC_QUIT ) is not None or f[code_prefix][code].attrs.get( conf.HDF5_BASIC_ST) is not None: console.write_blank() console.write_msg(code + "已退市或停牌") continue try: code_dict = code_exec(f, code) if code_dict is None: console.write_pass() continue else: console.write_exec() filter_df = filter_df.append(code_dict, ignore_index=True) except Exception as er: console.write_msg("[" + code + "]" + str(er)) f.close() f_screen = h5py.File(conf.HDF5_FILE_SCREEN, 'a') if f_screen.get(conf.STRATEGY_TREND_AND_REVERSE) is None: f_screen.create_group(conf.STRATEGY_TREND_AND_REVERSE) if f_screen[conf.STRATEGY_TREND_AND_REVERSE].get( conf.SCREEN_SHARE_FILTER) is None: f_screen[conf.STRATEGY_TREND_AND_REVERSE].create_group( conf.SCREEN_SHARE_FILTER) today_str = tradetime.get_today() tool.delete_dataset( f_screen[conf.STRATEGY_TREND_AND_REVERSE][conf.SCREEN_SHARE_FILTER], today_str) tool.merge_df_dataset( f_screen[conf.STRATEGY_TREND_AND_REVERSE][conf.SCREEN_SHARE_FILTER], today_str, filter_df) f_screen.close() console.write_blank() console.write_tail() return
def mark_grade(today_str=None): """ 对筛选结果进行打分 """ console.write_head(conf.HDF5_OPERATE_SCREEN, conf.HDF5_RESOURCE_TUSHARE, conf.SCREEN_SHARE_GRADE) f = h5py.File(conf.HDF5_FILE_SCREEN, 'a') f_share = h5py.File(conf.HDF5_FILE_SHARE, 'a') if today_str is None: today_str = tradetime.get_today() if f[conf.STRATEGY_TREND_AND_REVERSE][conf.SCREEN_SHARE_FILTER].get( today_str) is None: console.write_msg(today_str + "个股筛选结果不存在") return grade_df = tool.init_empty_df([ "code", "status", "d_price_space", "d_price_per", "30_price_space", "30_price_per", "d_macd", "30_macd" ]) screen_df = tool.df_from_dataset( f[conf.STRATEGY_TREND_AND_REVERSE][conf.SCREEN_SHARE_FILTER], today_str, None) screen_df["d_m_status"] = screen_df["d_m_status"].str.decode("utf-8") screen_df["w_m_status"] = screen_df["w_m_status"].str.decode("utf-8") screen_df["m_m_status"] = screen_df["m_m_status"].str.decode("utf-8") screen_df["code"] = screen_df["code"].str.decode("utf-8") for index, row in screen_df.iterrows(): code = row["code"] grade_dict = dict() grade_dict["code"] = code grade_dict["status"] = 0 grade_dict["status"] += _status_grade(row["d_m_status"]) grade_dict["status"] += _status_grade(row["w_m_status"]) grade_dict["status"] += _status_grade(row["m_m_status"]) code_prefix = code[0:3] code_group_path = '/' + code_prefix + '/' + code for ktype in ["D", "30"]: detail_ds_name = ktype index_ds_name = conf.HDF5_INDEX_DETAIL + "_" + ktype if f_share[code_group_path].get(detail_ds_name) is None: console.write_msg(code + "的detail数据不存在") continue if f_share[code_group_path].get(index_ds_name) is None: console.write_msg(code + "的index数据不存在") continue detail_df = tool.df_from_dataset(f_share[code_group_path], detail_ds_name, None) index_df = tool.df_from_dataset(f_share[code_group_path], index_ds_name, None) latest_price = detail_df.tail(1)["close"].values[0] latest_macd = index_df.tail(1)["macd"].values[0] diverse_price_start = row[str.lower(ktype) + INDEX_MACD_DIVERSE_PRICE_START] if diverse_price_start == 0: grade_dict[str.lower(ktype) + "_price_space"] = 0 grade_dict[str.lower(ktype) + "_price_per"] = 0 else: grade_dict[str.lower(ktype) + "_price_space"] = round( diverse_price_start - latest_price, 2) grade_dict[str.lower(ktype) + "_price_per"] = round( grade_dict[str.lower(ktype) + "_price_space"] * 100 / diverse_price_start, 2) grade_dict[str.lower(ktype) + "_macd"] = latest_macd grade_df = grade_df.append(grade_dict, ignore_index=True) if f[conf.STRATEGY_TREND_AND_REVERSE].get(conf.SCREEN_SHARE_GRADE) is None: f[conf.STRATEGY_TREND_AND_REVERSE].create_group( conf.SCREEN_SHARE_GRADE) tool.delete_dataset( f[conf.STRATEGY_TREND_AND_REVERSE][conf.SCREEN_SHARE_GRADE], today_str) tool.merge_df_dataset( f[conf.STRATEGY_TREND_AND_REVERSE][conf.SCREEN_SHARE_GRADE], today_str, grade_df) f_share.close() f.close() console.write_tail() return