def get_bar(self, instrument, dt, frequency): order_book_id = instrument.order_book_id Collection = self._db.sp_future_min if frequency in ['1m', '1min']: data = Collection.find_one({ 'code': order_book_id, "datetime": dt.strftime('%Y-%m-%d %H:%M:%S'), 'type': '1min' }) else: data = None if data is None: # return super(SPDataSource, self).get_bar(instrument, dt, frequency) with open('missing_data.csv', 'a') as f: f.write(f'{frequency}, {order_book_id}, {dt}\n') logger.info( f'<Data Missing>lack of {frequency} data --- {order_book_id}@{dt} ' ) return { 'code': order_book_id, 'datetime': dt.strftime('%Y-%m-%d %H:%M:%S'), 'open': np.nan, 'high': np.nan, 'low': np.nan, 'close': np.nan, 'volume': np.nan } else: data.setdefault('volume', data.pop('vol')) return data
def handle_bar(context, bar_dict): ''' 交易函数 ''' s1 = history_bars(context.stocks[0], 21, '1d', 'close') s2 = history_bars(context.stocks[1], 21, '1d', 'close') logger.debug('s1:' + str(s1)) logger.debug('s2:' + str(s2)) import pdb pdb.set_trace() s1delta = (s1[-1] - s1[0]) / s1[0] s2delta = (s2[-1] - s2[0]) / s2[0] log_str = '元和 ' + str(s1[0]) + '->' + str(s1[-1]) + ' 涨幅: ' + str( round(s1delta, 3)) + ' 债券 ' + str(s2[0]) + '->' + str( s2[-1]) + ' 涨幅: ' + str(round(s2delta, 3)) trading = None if s1delta is not None and s2delta is not None: if s1delta < 0 and s2delta < 0: trading = 'cash' elif s1delta > s2delta: trading = context.stocks[0] else: trading = context.stocks[1] if trading is None or trading == context.hold: return if context.hold is not None and context.hold != 'cash': order_target_percent(context.hold, 0) log_str += ' sell ' + context.hold if trading != 'cash': order_target_percent(trading, 1) log_str += ' buy ' + trading context.hold = trading logger.info(log_str)
def init(context): ''' 策略初始化 ''' logger.info("init") context.stocks = STOCKS update_universe(context.stocks) context.hold = None
def init(context): # 在context中保存全局变量 print "111111111111" context.error = 0 context.ok = 0 logger.info("RunInfo: {}".format(context.run_info)) df = (all_instruments('CS')) context.all = df["order_book_id"]
def init(context): ''' 策略初始化 ''' logger.info("init") context.stocks = STOCKS #当前持仓品种,取值为STOCKS里的值以及cash context.hold = 'cash' #趋势判断窗口,往前看20个交易日 context.window_size = 20
def init(context): logger.info('initializing the strategy...') context.show_progress = True context.buyStkCount = 5 context.blackList = [] load_A_H_stock_price(context) logger.info('initialization completed!') context.stocks = [] context.holding_A = False context.sold_A = False
def handle_bar(context, bar_dict): """ Description : 选择的证券的数据更新将会触发此段逻辑 Arg : Returns : Raises : """ # 需要买的股票列表 _lst_buy_stock = [] # 遍历所有的股票 for _stock in context.stocks: # 首先取得前面多少日的收盘价 _data = history_bars(_stock, context.N, '1d', "close") # 判断是否是前面几天啦 if len(_data) < context.N: continue # 取得最小值和最大值 _min = _data.min() _max = _data.max() _close = _data[-1] # 先判断是否达到卖出的条件, # 条件是,达到止损 if _close < _max * (100 - context.loss)/100: # 然后判断是否有买入 if _stock in context.portfolio.positions.keys(): order_target_percent(_stock, 0) logger.info("清空股票:{}".format(_stock)) # 判断是否满足买的条件 if ((_close > _min * (100 + context.M)/100) and _close ==_max): logger.info("买入股票{}".format(_stock)) _lst_buy_stock.append(_stock) # 输出有多少个股票买入 # 因为有时候有很多股票需要买入,这里要判断最值得的。 # 我只买10个股票。 # 这里要判断要买那个股票 _lst_buy_stock_2 = [] # 这个是最终要选择的股票 if (len(_lst_buy_stock) > 10): # 按照ATX来购买。趋势高的就买喽。 pass else: _lst_buy_stock_2 = _lst_buy_stock # 如果现在持有的股票不在这个最终要选择的股票里边,就卖了吧 if _stock in context.portfolio.positions.keys(): if _stock not in _lst_buy_stock_2: order_target_percent(_stock, 0) logger.info("清空股票:{}".format(_stock)) # 然后购买最终持有的股票。 for _stock in _lst_buy_stock_2: order_target_percent(_stock, 0.1) logger.info("购买股票:{}".format(_stock)) logger.info("总共买入股票数量:{}".format(len(_lst_buy_stock)))
def handle_bar(context, bar_dict): """ Description : 选择的证券的数据更新将会触发此段逻辑 Arg : Returns : Raises : """ # 需要买的股票列表 _lst_buy_stock = [] # 遍历所有的股票 for _stock in context.stocks: # 首先取得前面多少日的收盘价 _data = history_bars(_stock, context.N + 1, '1d', "close") # 判断是否是前面几天啦 if len(_data) < context.N + 1: continue # 取得最小值和最大值 _data_2 = _data[0:context.N] _min = _data_2.min() _max = _data_2.max() _close_1 = _data_2[-1] _close_2 = _data[-1] # 先判断是否达到卖出的条件, # 条件是,达到止损 if _close_2 < _close_1 * (100 + context.min_up): # 然后判断是否有买入 if _stock in context.portfolio.positions.keys(): order_target_percent(_stock, 0) # logger.info("清空股票:{}".format(_stock)) # 判断是否是有仓位 if _stock in context.portfolio.positions.keys(): # 如果是有降低,就清仓啦 if _close_2 < _close_1: order_target_percent(_stock, 0) # logger.info("清空股票:{}".format(_stock)) # 判断是否满足买的条件 if ((_close_1 > _min * (100 + context.M) / 100) and _close_1 == _max and (_close_2 - _close_1) / _close_1 * 100 > context.min_up): # logger.info("买入股票{}".format(_stock)) # order_target_percent(_stock, 0.1) _lst_buy_stock.append(_stock) logger.info("{}".format(len(_lst_buy_stock)))
def handle_bar(context, bar_dict): # pass # #def handle_bar_weekly(context, bar_dict): ''' 交易函数 ''' hist_s1 = history_bars(context.stocks[0], context.window_size + 1, '1d', 'close') hist_s2 = history_bars(context.stocks[1], context.window_size + 1, '1d', 'close') curr_s1 = bar_dict[context.stocks[0]].close curr_s2 = bar_dict[context.stocks[1]].close logger.debug('s1:' + str(hist_s1)) logger.debug('s2:' + str(hist_s2)) s1delta = (curr_s1 - hist_s1[0]) / hist_s1[0] s2delta = (curr_s2 - hist_s2[0]) / hist_s2[0] log_str = '[' + context.now.isoformat() + ']' log_str += '沪深300 ' + str(hist_s1[0]) + '->' + str(curr_s1) log_str += ' 涨幅: ' + str(round(s1delta, 3)) log_str += ' 中证500 ' + str(hist_s2[0]) + '->' + str(curr_s2) log_str += ' 涨幅: ' + str(round(s2delta, 3)) trading = None if s1delta is not None and s2delta is not None: if s1delta < 0 and s2delta < 0: trading = 'cash' elif s1delta > s2delta: trading = context.stocks[0] else: trading = context.stocks[1] if trading is None or trading == context.hold: return if context.hold != 'cash': order_target_percent(context.hold, 0) log_str += ' sell ' + context.hold if trading != 'cash': order_target_percent(trading, 0.99) log_str += ' buy ' + trading context.hold = trading logger.info(log_str)
def handle_bar(context, bar_dict): logger.info("每一个Bar执行") logger.info("打印Bar数据:") logger.info("stock count %s" % len(context.all)) for s1 in context.all: logger.info("----------22222-------%s-------" % bar_dict[s1]) order_book_id = s1 global_start_time = time.time() history_close = history_bars(order_book_id, 51, '1d', 'close') history_close = history_close[:-1] if len(history_close) != 50: continue if not os.path.isfile('weight_week/%s.npy.h5' % order_book_id): continue if not os.path.isfile('weight_json_week/%s.npy.h5' % order_book_id): continue y = bar_dict[order_book_id].close yesterday_close = history_close[-2] normalised_history_close = [((float(p) / float(history_close[0])) - 1) for p in history_close] print history_close print normalised_history_close normalised_history_close = np.array(normalised_history_close) normalised_history_close = normalised_history_close[newaxis, :] normalised_history_close = normalised_history_close[:, :, newaxis] json_file = open("weight_json_week/%s.npy.h5" % order_book_id, 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) model.load_weights("weight_week/%s.npy.h5" % order_book_id) #model = load_model('model/%s.h5' % order_book_id) #model.compile(loss="mse", optimizer="rmsprop") predicted = model.predict(normalised_history_close)[0, 0] del model K.clear_session() normalised_history_close = [((float(p) / float(history_close[0])) - 1) for p in history_close] normalised_history_close.append(predicted) restore_normalise_window = [ float(history_close[0]) * (float(p) + 1) for p in normalised_history_close ] restore_predicted = restore_normalise_window[-1] logger.info( "predicted: %s yesterday_close:%s restore_predicted:%s real: %s" % (predicted, yesterday_close, restore_predicted, y)) flag = 0 if yesterday_close > y and yesterday_close > restore_predicted: context.ok = context.ok + 1 flag = flag + 1 if yesterday_close < y and yesterday_close < restore_predicted: context.ok = context.ok + 1 flag = flag + 1 if not flag: context.error = context.error + 1 logger.info("--eve----------------------------------------------") logger.info("stock count %s" % len(context.all)) logger.info( "error:%s ok:%s ratio:%s" % (context.error, context.ok, round(float(context.ok) / (context.error + context.ok), 2))) logger.info("--eve -------------------------------------------") print "Training duration (s) : %s %s" % ( time.time() - global_start_time, order_book_id)
def before_trading(context): logger.info("开盘前执行before_trading函数")
def log_cash(context, bar_dict): logger.info("Remaning cash: %r" % context.portfolio.cash)
def after_trading(context): logger.info("收盘后执行after_trading函数")