def prepare_performance(self): start = time.time() perf = self.data.copy() perf['price'] = perf['close'] size = self.account.initial_capital / perf.iloc[0]['close'] perf['base_equity'] = [price * size for price in perf['close']] perf['equity'] = [e for _, e in self.account.equity] # BENCHMARK perf['benchmark_period_return'] = [ helpers.percent_change(perf['base_equity'][0], perf['base_equity'][i]) for i in range(0, len(perf['base_equity']))] perf['benchmark_max_drawdown'] = [ max_drawdown(perf['base_equity'][:i].pct_change()) for i in range(0, len(perf['base_equity']))] # STRATEGY perf['algorithm_period_return'] = [ helpers.percent_change(perf['equity'][0], perf['equity'][i]) for i in range(0, len(perf['equity']))] perf['returns'] = perf['equity'].pct_change() perf['max_drawdown'] = [ max_drawdown(perf['equity'][:i].pct_change()) for i in range(0, len(perf['equity']))] logger.debug( 'Performance prepared for {:.2} sec'.format(time.time() - start)) perf['ending_value'] = 0 # value of opened positions perf['Annualized Return'] = (1 + perf['algorithm_period_return']).cumprod()[-1]**(len(perf['base_equity'])/365) - 1 perf['alpha'] = '0' perf['beta'] = '0' perf['std'] = np.std(perf['returns']) perf['sharpe'] = perf['Annualized Return']/perf['std'] perf['calmer'] = perf['Annualized Return']/perf['max_drawdown'] return perf
def results_default(self): """ Print results of backtest to console :return: """ title = "{:=^52}".format(" Results (freq {}) ".format( self.sim_params['data_frequency'])) print(title + "\n") size = self.account.initial_capital / self.data.iloc[0]['close'] self.data['base_equity'] = [ price * size for price in self.data['close'] ] self.data['equity'] = [e for _, e in self.account.equity] # STRING FORMATS title_fmt = "{:-^40}" str_fmt = "{0:<13}: {1:.2f}{2}" # BENCHMARK percent_change = helpers.percent_change(self.data['base_equity'][0], self.data['base_equity'][-1]) bench = [ ("Capital", self.account.initial_capital, ""), ("Final Equity", self.data['base_equity'][-1], ""), ("Net profit", helpers.profit(self.account.initial_capital, percent_change), " ({:+.2f}%)".format(percent_change * 100)), ("Max Drawdown", max_drawdown(self.data['base_equity'].pct_change()) * 100, "%"), ] print(title_fmt.format(" Benchmark ")) for r in bench: print(str_fmt.format(*r)) # STRATEGY percent_change = helpers.percent_change(self.data['equity'][0], self.data['equity'][-1]) fee = sum([t.fee for t in self.account.closed_trades]) strategy = [ ("Capital", self.account.initial_capital, ""), ("Final Equity", self.data['equity'][-1], ""), ("Net profit", helpers.profit(self.account.initial_capital, percent_change), " ({:+.2f}%)".format(percent_change * 100)), ("Max Drawdown", max_drawdown(self.data['equity'].pct_change()) * 100, "%"), ("Fees paid", fee, ""), ] # STATISTICS longs = len( [t for t in self.account.opened_trades if t.type_ == 'Long']) sells = len( [t for t in self.account.closed_trades if t.type_ == 'Long']) shorts = len( [t for t in self.account.opened_trades if t.type_ == 'Short']) covers = len( [t for t in self.account.closed_trades if t.type_ == 'Short']) print(title_fmt.format(" Strategy ")) for r in strategy: print(str_fmt.format(*r)) # get trades' statistics l_sr, l_loss, l_win, l_ev = self._trades_analyze(type_=['Long']) s_sr, s_loss, s_win, s_ev = self._trades_analyze(type_=['Short']) all_sr, all_loss, all_win, all_ev = self._trades_analyze() stat = [('Success rate %', l_sr, s_sr, all_sr), ('Avg Win / trade', l_win, s_win, all_win), ('Avg Loss / trade', l_loss, s_loss, all_loss), ('Expected value', l_ev, s_ev, all_ev), ('Open', longs, shorts, longs + shorts), ('Closed', sells, covers, sells + covers), ('Total Trades', longs + sells, shorts + covers, longs + shorts + sells + covers)] str_fmt = "{:<20}: {:>10.4f} {:>10.4f} {:>10.4f}" title_fmt = "{:-^52}" print(title_fmt.format(" Statistics ")) title_fmt = "{:<20} {:>7} {:>10} {:>10}" print(title_fmt.format('', 'Long', 'Short', 'All')) for r in stat: print(str_fmt.format(*r)) print("-" * len(title))
def results(self): """ Print results of backtest to console :return: """ title = "{:=^50}".format(" Results (freq {}) ".format( self.sim_params['data_frequency'])) print(title + "\n") begin_price = self.data.iloc[0]['open'] final_price = self.data.iloc[-1]['close'] shares = self.account.initial_capital / self.data.iloc[0]['close'] self.data['base_equity'] = [ price * shares for price in self.data['close'] ] self.data['equity'] = [e for _, e in self.account.equity] # STRING FORMATS title_fmt = "{:-^40}" str_fmt = "{0:<13}: {1:.2f}{2}" # BENCHMARK percent_change = helpers.percent_change(self.data['base_equity'][0], self.data['base_equity'][-1]) benchmark = self.data['base_equity'].pct_change() bench = [ ("Capital", self.account.initial_capital, ""), ("Final Equity", self.data['base_equity'][-1], ""), ("Net profit", helpers.profit(self.account.initial_capital, percent_change), " ({:+.2f}%)".format(percent_change * 100)), ("Max Drawdown", max_drawdown(benchmark) * 100, "%"), ] print(title_fmt.format(" Benchmark ")) for r in bench: print(str_fmt.format(*r)) # STRATEGY percent_change = helpers.percent_change(self.data['equity'][0], self.data['equity'][-1]) open_fee = sum([t.fee for t in self.account.opened_trades]) close_fee = sum([t.fee for t in self.account.closed_trades]) # print trades # for t in self.account.opened_trades: print(t) returns = self.data['equity'].pct_change() strategy = [ ("Capital", self.account.initial_capital, ""), ("Final Equity", self.data['equity'][-1], ""), ("Net profit", helpers.profit(self.account.initial_capital, percent_change), " ({:+.2f}%)".format(percent_change * 100)), ("Max Drawdown", max_drawdown(returns) * 100, "%"), ("Sharpe Ratio", sharpe_ratio(returns), ""), ("Sortino Ratio", sortino_ratio(returns), ""), ("Alpha", alpha(returns, benchmark), ""), ("Beta", beta(returns, benchmark), ""), ("Fees paid", open_fee + close_fee, ""), ] print(title_fmt.format(" Strategy ")) for r in strategy: print(str_fmt.format(*r)) # STATISTICS longs = len( [t for t in self.account.opened_trades if t.type_ == 'Long']) sells = len( [t for t in self.account.closed_trades if t.type_ == 'Long']) shorts = len( [t for t in self.account.opened_trades if t.type_ == 'Short']) covers = len( [t for t in self.account.closed_trades if t.type_ == 'Short']) stat = [ ("Longs", longs, ""), ("Sells", sells, ""), ("Shorts", shorts, ""), ("Covers", covers, ""), ("Total Trades", longs + sells + shorts + covers, ""), ] str_fmt = "{0:<13}: {1:.0f}{2}" print(title_fmt.format(" Statistics ")) for r in stat: print(str_fmt.format(*r)) print("-" * len(title)) return percent_change