Skip to content

Commit d4ec0ba

Browse files
aliencaocaokernc
authored andcommitted
BUG: Change price comparisons from lt/gt to lte/gte, align with TradingView
Fixes #1157
1 parent 5c8a0af commit d4ec0ba

File tree

2 files changed

+7
-8
lines changed

2 files changed

+7
-8
lines changed

backtesting/backtesting.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -875,7 +875,7 @@ def _process_orders(self):
875875
# Check if stop condition was hit
876876
stop_price = order.stop
877877
if stop_price:
878-
is_stop_hit = ((high > stop_price) if order.is_long else (low < stop_price))
878+
is_stop_hit = ((high >= stop_price) if order.is_long else (low <= stop_price))
879879
if not is_stop_hit:
880880
continue
881881

@@ -886,13 +886,13 @@ def _process_orders(self):
886886
# Determine purchase price.
887887
# Check if limit order can be filled.
888888
if order.limit:
889-
is_limit_hit = low < order.limit if order.is_long else high > order.limit
889+
is_limit_hit = low <= order.limit if order.is_long else high >= order.limit
890890
# When stop and limit are hit within the same bar, we pessimistically
891891
# assume limit was hit before the stop (i.e. "before it counts")
892892
is_limit_hit_before_stop = (is_limit_hit and
893-
(order.limit < (stop_price or -np.inf)
893+
(order.limit <= (stop_price or -np.inf)
894894
if order.is_long
895-
else order.limit > (stop_price or np.inf)))
895+
else order.limit >= (stop_price or np.inf)))
896896
if not is_limit_hit or is_limit_hit_before_stop:
897897
continue
898898

@@ -905,9 +905,8 @@ def _process_orders(self):
905905
# Contingent orders always on next open
906906
prev_close = data.Close[-2]
907907
price = prev_close if self._trade_on_close and not order.is_contingent else open
908-
price = (max(price, stop_price or -np.inf)
909-
if order.is_long else
910-
min(price, stop_price or np.inf))
908+
if stop_price:
909+
price = max(price, stop_price) if order.is_long else min(price, stop_price)
911910

912911
# Determine entry/exit bar index
913912
is_market_order = not order.limit and not stop_price

backtesting/test/_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def next(self, _FEW_DAYS=pd.Timedelta('3 days')): # noqa: N803
218218
bt = Backtest(GOOG, Assertive)
219219
with self.assertWarns(UserWarning):
220220
stats = bt.run()
221-
self.assertEqual(stats['# Trades'], 144)
221+
self.assertEqual(stats['# Trades'], 131)
222222

223223
def test_broker_params(self):
224224
bt = Backtest(GOOG.iloc[:100], SmaCross,

0 commit comments

Comments
 (0)