async def run_backtest(self, params, f, slow=22, fast=10): self._cash_value = 1000 self._trader = BacktestTrader() self._pnl_manager = BasicPnLManager(get_balance_cb=None, broadcast_cb=None, crypto_coins=0, cash_value=self._cash_value, instrument={}) self._strategy = Aesop(self._trader, self._pnl_manager, slow=slow, fast=fast) first_update = None playback = Playback(f) for update in playback: if self._strategy._dual_ema._init_processed is not -1: if first_update is None and is_valid_book(update['book']): first_update = update await self._strategy.initialize(update) else: self._trader.on_market_data(update) await self._strategy.on_market_data(update) await self._trader.cancel_all() # Print final strategy value vs theoretical market value strategy_value, movement = await self._log_results( first_update, self._cash_value, slow, fast) return strategy_value, movement
async def run_backtest(self, params, f, slow=22, fast=10): strat_values = [] self._cash_value = 1000 self._trader = BacktestTrader() self._pnl_manager = BasicPnLManager(get_balance_cb=None, broadcast_cb=None, crypto_coins=0, cash_value=self._cash_value, instrument={}) self._strategy = Aesop(self._trader, self._pnl_manager, slow=slow, fast=fast) first_update = None playback = Playback(f) for update in playback: if self._strategy._dual_ema._init_processed is not -1: if first_update is None and is_valid_book(update['book']): first_update = update await self._strategy.initialize(update) else: self._trader.on_market_data(update) await self._strategy.on_market_data(update) timestamp = update['timestamp'] if timestamp[-6:] == '+00:00': timestamp = timestamp[:-6] ts = None try: ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f') except ValueError as e: ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') strat_values.append( StratValues( ts, (self._trader.get_strategy_value() + self._trader._resting_order_sim.get_resting_value()))) await self._trader.cancel_all() # Print final strategy value vs theoretical market value strategy_value, movement = await self._log_results( first_update, self._cash_value, slow, fast) # return strategy_value, movement return strat_values
async def initialize(self, update): assert self._init_processed != -1 if is_valid_book(update['book']): self._init_processed += 1 self._init_sum += simple_midpoint(update['book']) if self._init_processed == self._fast_window: self._fast_value = self._init_sum / self._fast_window if self._init_processed == self._slow_window: self._slow_value = self._init_sum / self._slow_window self._init_processed = -1 await self._on_init_complete(update)
async def on_market_data(self, update): assert self._init_processed is -1 if not is_valid_book(update['book']): return self._mkt_price = simple_midpoint(update['book']) self._slow_value = self._slow.on_price(self._mkt_price) self._fast_value = self._fast.on_price(self._mkt_price) if self._action == 'BUY': if self._fast_value < self._slow_value: self._action = 'SELL' if self._on_signal_cb: await self._on_signal_cb(self._action, update) else: if self._fast_value > self._slow_value: self._action = 'BUY' if self._on_signal_cb: await self._on_signal_cb(self._action, update)
def main(args): log.info('---------- Starting Signal Test ----------') if args['--input-file']: f = args['--input-file'] realized_vol = RealizedVolatility(10000) plot = [] num_updates = 0 playback = Playback(f) for update in playback: num_updates += 1 if is_valid_book(update['book']): timestamp = update['timestamp'] if timestamp[-6:] == '+00:00': timestamp = timestamp[:-6] ts = None try: ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f') except ValueError as e: ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') if num_updates < 100: realized_vol.add(update['book']) continue real_vol = realized_vol.get(update['book']) if real_vol is None: continue plot.append( PlotValues(ts, round(float(update['book']['bids'][0]['price']), 1), round(float(update['book']['asks'][0]['price']), 1), real_vol)) time_stamps = np.asarray([x.ts for x in plot]) bids = np.asarray([x.bid for x in plot]) asks = np.asarray([x.ask for x in plot]) real_vol = [x.realized_volitility for x in plot] min_val = min(bids) max_val = max(bids) max_real_vol = max(real_vol) norm_real_vol = [(float(i) / max_real_vol) * (max_val - min_val) + min_val for i in real_vol] real_vol = np.asarray(norm_real_vol) fig, ax = plt.subplots() ax.plot( time_stamps, bids, 'C2-', # Green time_stamps, asks, 'C9-', # Cyan time_stamps, real_vol, 'C0-') # Blue yearsFmt = mdates.DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(yearsFmt) ax.set_xlim(time_stamps[0], time_stamps[len(time_stamps) - 1]) fig.autofmt_xdate() ax.grid(True) plt.show() log.info('---------- Shutting down --------------\n\n\n\n\n\n')
async def run_against_params(self, params, files): realized_vol = RealizedVolatility(10000) plot = [] num_updates = 0 playback = Playback(files[0]) for update in playback: num_updates += 1 if is_valid_book(update['book']): timestamp = update['timestamp'] if timestamp[-6:] == '+00:00': timestamp = timestamp[:-6] ts = None try: ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S.%f') except ValueError as e: ts = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') realized_vol.on_market_data(update['book']) if num_updates < 100: continue real_vol = realized_vol.value if real_vol is None: continue plot.append( PlotValues( ts, round(float(simple_midpoint(update['book'])), 1), real_vol)) time_stamps = np.asarray([x.ts for x in plot]) mkt = np.asarray([x.mkt for x in plot]) y_anchor = Decimal(1000 - mkt[0]) slow = [x for x in range(12 * 5, 20 * 5, 8 * 5)] fast = [x for x in range(2 * 5, 10 * 5, 8 * 5)] options = list(itertools.product(slow, fast)) options = [x for x in options if x[0] > x[1]] log.info("parameter set [{}]: {}".format(len(options), options)) fig, ax = plt.subplots() strat_plot = [] colors = [ 'C0--', 'C1--', 'C2--', 'C3--', 'C4--', 'C5--', 'C6--', 'C7--', 'C8--', 'C9--' ] for f in files: log.info("Using file: {}".format(f)) for i in range(len(options)): strat_plot = await self.run_backtest(params, f, options[i][0], options[i][1]) first_ts = strat_plot[0] index = 0 for i, p in enumerate(plot): if p.ts == first_ts: index = i break shifted_mkt = mkt[index:] strat_time_stamps = np.asarray([x.ts for x in strat_plot]) pnl = np.asarray([(x.pnl - (1000 - shifted_mkt[i])) for i, x in enumerate(strat_plot)]) ax.plot(strat_time_stamps, pnl, colors[0], label=str(options[i])) print(strat_plot[len(strat_plot) - 1]) print(options[i]) colors.pop(0) real_vol = [x.realized_volitility for x in plot] min_val = min(mkt) max_val = 370 # max(mkt) max_real_vol = max(real_vol) norm_real_vol = [ (float(i) / max_real_vol) * (max_val - min_val) + min_val for i in real_vol ] real_vol = np.asarray(norm_real_vol) ax.plot(time_stamps, mkt, 'C2-', label="Market") # Green ax.plot(time_stamps, real_vol, 'C0-', label="RealVol") # Blue plt.legend() yearsFmt = mdates.DateFormatter('%H:%M:%S') ax.xaxis.set_major_formatter(yearsFmt) ax.set_xlim(time_stamps[0], time_stamps[len(time_stamps) - 1]) fig.autofmt_xdate() ax.grid(True) plt.show()