From 0363e88254a25218f5e120e294f09a69e3519270 Mon Sep 17 00:00:00 2001 From: Kernc Date: Sun, 26 Jul 2020 23:13:26 +0200 Subject: [PATCH] ENH: Add `Trade.entry_time/.exit_time` Refs: https://github.com/kernc/backtesting.py/pull/47#issuecomment-663435418 Fixes: https://github.com/kernc/backtesting.py/issues/117 --- backtesting/backtesting.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/backtesting/backtesting.py b/backtesting/backtesting.py index b1d23c32..962116fd 100644 --- a/backtesting/backtesting.py +++ b/backtesting/backtesting.py @@ -574,6 +574,16 @@ def _tp_order(self): # Extra properties + @property + def entry_time(self): + """Datetime of when the trade was entered.""" + return self.__broker._data.index[self.__entry_bar] + + @property + def exit_time(self): + """Datetime of when the trade was exited.""" + return self.__broker._data.index[self.__exit_bar] + @property def is_long(self): """True if the trade is long (trade size is positive).""" @@ -1307,9 +1317,9 @@ def _compute_stats(self, broker: _Broker, strategy: Strategy) -> pd.Series: 'ExitPrice': [t.exit_price for t in trades], 'PnL': [t.pl for t in trades], 'ReturnPct': [t.pl_pct for t in trades], + 'EntryTime': [t.entry_time for t in trades], + 'ExitTime': [t.exit_time for t in trades], }) - trades_df['EntryTime'] = trades_df['EntryBar'].apply(index.__getitem__) - trades_df['ExitTime'] = trades_df['ExitBar'].apply(index.__getitem__) trades_df['Duration'] = trades_df['ExitTime'] - trades_df['EntryTime'] pl = trades_df['PnL']