Skip to content

Commit 72e56f3

Browse files
committed
BUG: Fix cleared SL value in stats._trades data frame
Fixes #1288 Thanks @xyffar for the analysis!
1 parent 804d77f commit 72e56f3

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

backtesting/backtesting.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,9 @@ def _process_orders(self):
934934
if trade in self.trades:
935935
self._reduce_trade(trade, price, size, time_index)
936936
assert order.size != -_prev_size or trade not in self.trades
937+
if price == stop_price:
938+
# Set SL back on the order for stats._trades["SL"]
939+
trade._sl_order._replace(stop_price=stop_price)
937940
if order in (trade._sl_order,
938941
trade._tp_order):
939942
assert order.size == -trade.size

backtesting/test/_test.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1140,3 +1140,14 @@ def test_optimize_datetime_index_with_timezone(self):
11401140
data.index = data.index.tz_localize('Asia/Kolkata')
11411141
res = Backtest(data, SmaCross).optimize(fast=range(2, 3), slow=range(4, 5))
11421142
self.assertGreater(res['# Trades'], 0)
1143+
1144+
def test_sl_tp_values_in_trades_df(self):
1145+
class S(_S):
1146+
def next(self):
1147+
self.next = lambda: None
1148+
self.buy(size=1, tp=111)
1149+
self.buy(size=1, sl=99)
1150+
1151+
trades = Backtest(SHORT_DATA, S).run()._trades
1152+
self.assertEqual(trades['SL'].fillna(0).tolist(), [0, 99])
1153+
self.assertEqual(trades['TP'].fillna(0).tolist(), [111, 0])

0 commit comments

Comments
 (0)