From cd5ae83135b2644bf611134e6c8218ca7e845da0 Mon Sep 17 00:00:00 2001 From: Kernc Date: Tue, 13 Dec 2022 15:13:54 +0100 Subject: [PATCH] ENH: Show paid 'Commissions [$]' in stats --- backtesting/_stats.py | 4 ++++ backtesting/backtesting.py | 12 ++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/backtesting/_stats.py b/backtesting/_stats.py index f2bb4f7c..fa32f92d 100644 --- a/backtesting/_stats.py +++ b/backtesting/_stats.py @@ -53,6 +53,7 @@ def compute_stats( if isinstance(trades, pd.DataFrame): trades_df: pd.DataFrame = trades + commissions = None # Not shown else: # Came straight from Backtest.run() trades_df = pd.DataFrame({ @@ -68,6 +69,7 @@ def compute_stats( 'Tag': [t.tag for t in trades], }) trades_df['Duration'] = trades_df['ExitTime'] - trades_df['EntryTime'] + commissions = sum(t._commissions for t in trades) del trades pl = trades_df['PnL'] @@ -92,6 +94,8 @@ def _round_timedelta(value, _period=_data_period(index)): s.loc['Exposure Time [%]'] = have_position.mean() * 100 # In "n bars" time, not index time s.loc['Equity Final [$]'] = equity[-1] s.loc['Equity Peak [$]'] = equity.max() + if commissions: + s.loc['Commissions [$]'] = commissions s.loc['Return [%]'] = (equity[-1] - equity[0]) / equity[0] * 100 c = ohlc_data.Close.values s.loc['Buy & Hold Return [%]'] = (c[-1] - c[0]) / c[0] * 100 # long-only return diff --git a/backtesting/backtesting.py b/backtesting/backtesting.py index 1c6f7817..42ecd68b 100644 --- a/backtesting/backtesting.py +++ b/backtesting/backtesting.py @@ -538,6 +538,7 @@ def __init__(self, broker: '_Broker', size: int, entry_price: float, entry_bar, self.__sl_order: Optional[Order] = None self.__tp_order: Optional[Order] = None self.__tag = tag + self._commissions = 0 def __repr__(self): return f'