Skip to content

Commit 3cc33b8

Browse files
committed
ENH: Add Trade.entry_time/.exit_time
Refs: #47 (comment) Fixes: #117
1 parent 28cf0a6 commit 3cc33b8

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

backtesting/backtesting.py

+14-2
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,18 @@ def _tp_order(self):
574574

575575
# Extra properties
576576

577+
@property
578+
def entry_time(self):
579+
"""Datetime of when the trade was entered."""
580+
return self.__broker._data.index[self.__entry_bar]
581+
582+
@property
583+
def exit_time(self):
584+
"""Datetime of when the trade was exited."""
585+
if self.__exit_bar is None:
586+
return None
587+
return self.__broker._data.index[self.__exit_bar]
588+
577589
@property
578590
def is_long(self):
579591
"""True if the trade is long (trade size is positive)."""
@@ -1307,9 +1319,9 @@ def _compute_stats(self, broker: _Broker, strategy: Strategy) -> pd.Series:
13071319
'ExitPrice': [t.exit_price for t in trades],
13081320
'PnL': [t.pl for t in trades],
13091321
'ReturnPct': [t.pl_pct for t in trades],
1322+
'EntryTime': [t.entry_time for t in trades],
1323+
'ExitTime': [t.exit_time for t in trades],
13101324
})
1311-
trades_df['EntryTime'] = trades_df['EntryBar'].apply(index.__getitem__)
1312-
trades_df['ExitTime'] = trades_df['ExitBar'].apply(index.__getitem__)
13131325
trades_df['Duration'] = trades_df['ExitTime'] - trades_df['EntryTime']
13141326

13151327
pl = trades_df['PnL']

backtesting/test/_test.py

+2
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,9 @@ def next(self, FIVE_DAYS=pd.Timedelta('3 days')):
193193
assert trade.is_short
194194
assert trade.size < 0
195195
assert trade.entry_bar > 0
196+
assert isinstance(trade.entry_time, pd.Timestamp)
196197
assert trade.exit_bar is None
198+
assert trade.exit_time is None
197199
assert trade.entry_price > 0
198200
assert trade.exit_price is None
199201
assert trade.pl / 1

0 commit comments

Comments
 (0)