Skip to content

Commit

Permalink
ENH: Add entry/exit indicator values to stats['trades'] (#1116)
Browse files Browse the repository at this point in the history
* Updated _trades dataframe with 1D Indicator variables for Entry and Exit bars

* Shorter form, vectorized over index

* Remove Strategy.get_indicators_dataframe() public helper method

* Account for multi-dim indicators and/or no trades

---------

Co-authored-by: kernc <[email protected]>
  • Loading branch information
lachyn21 and kernc authored Jan 22, 2025
1 parent dfcab45 commit 4b829b7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
10 changes: 10 additions & 0 deletions backtesting/_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@ def compute_stats(
})
trades_df['Duration'] = trades_df['ExitTime'] - trades_df['EntryTime']
trades_df['Tag'] = [t.tag for t in trades]

# Add indicator values
if len(trades_df):
for ind in strategy_instance._indicators:
ind = np.atleast_2d(ind)
for i, values in enumerate(ind): # multi-d indicators
suffix = f'_{i}' if len(ind) > 1 else ''
trades_df[f'Entry_{ind.name}{suffix}'] = values[trades_df['EntryBar'].values]
trades_df[f'Exit_{ind.name}{suffix}'] = values[trades_df['ExitBar'].values]

commissions = sum(t._commissions for t in trades)
del trades

Expand Down
7 changes: 6 additions & 1 deletion backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,10 +333,15 @@ def almost_equal(a, b):

self.assertEqual(len(stats['_trades']), 66)

indicator_columns = [
f'{entry}_SMA(C,{n})'
for entry in ('Entry', 'Exit')
for n in (SmaCross.fast, SmaCross.slow)]
self.assertSequenceEqual(
sorted(stats['_trades'].columns),
sorted(['Size', 'EntryBar', 'ExitBar', 'EntryPrice', 'ExitPrice', 'SL', 'TP',
'PnL', 'ReturnPct', 'EntryTime', 'ExitTime', 'Duration', 'Tag']))
'PnL', 'ReturnPct', 'EntryTime', 'ExitTime', 'Duration', 'Tag',
*indicator_columns]))

def test_compute_stats_bordercase(self):

Expand Down

0 comments on commit 4b829b7

Please sign in to comment.