Skip to content

Commit a1444e5

Browse files
lachyn21kernc
andauthored
ENH: Add entry/exit indicator values to stats['trades'] (kernc#1116)
* 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]>
1 parent 2b352bf commit a1444e5

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

backtesting/_stats.py

+10
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,16 @@ def compute_stats(
7373
})
7474
trades_df['Duration'] = trades_df['ExitTime'] - trades_df['EntryTime']
7575
trades_df['Tag'] = [t.tag for t in trades]
76+
77+
# Add indicator values
78+
if len(trades_df):
79+
for ind in strategy_instance._indicators:
80+
ind = np.atleast_2d(ind)
81+
for i, values in enumerate(ind): # multi-d indicators
82+
suffix = f'_{i}' if len(ind) > 1 else ''
83+
trades_df[f'Entry_{ind.name}{suffix}'] = values[trades_df['EntryBar'].values]
84+
trades_df[f'Exit_{ind.name}{suffix}'] = values[trades_df['ExitBar'].values]
85+
7686
commissions = sum(t._commissions for t in trades)
7787
del trades
7888

backtesting/test/_test.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -333,10 +333,15 @@ def almost_equal(a, b):
333333

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

336+
indicator_columns = [
337+
f'{entry}_SMA(C,{n})'
338+
for entry in ('Entry', 'Exit')
339+
for n in (SmaCross.fast, SmaCross.slow)]
336340
self.assertSequenceEqual(
337341
sorted(stats['_trades'].columns),
338342
sorted(['Size', 'EntryBar', 'ExitBar', 'EntryPrice', 'ExitPrice', 'SL', 'TP',
339-
'PnL', 'ReturnPct', 'EntryTime', 'ExitTime', 'Duration', 'Tag']))
343+
'PnL', 'ReturnPct', 'EntryTime', 'ExitTime', 'Duration', 'Tag',
344+
*indicator_columns]))
340345

341346
def test_compute_stats_bordercase(self):
342347

0 commit comments

Comments
 (0)