Skip to content

Commit 9938d08

Browse files
committed
ENH: lib.TrailingStrategy: set trailing SL by percent
Fixes #223 Closes #377
1 parent 0853e96 commit 9938d08

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

backtesting/lib.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -474,11 +474,24 @@ def set_atr_periods(self, periods: int = 100):
474474

475475
def set_trailing_sl(self, n_atr: float = 6):
476476
"""
477-
Sets the future trailing stop-loss as some multiple (`n_atr`)
477+
Set the future trailing stop-loss as some multiple (`n_atr`)
478478
average true bar ranges away from the current price.
479479
"""
480480
self.__n_atr = n_atr
481481

482+
def set_trailing_pct(self, pct: float = .05):
483+
"""
484+
Set the future trailing stop-loss as some percent (`0 < pct < 1`)
485+
below the current price (default 5% below).
486+
487+
.. note:: Stop-loss set by `pct` is inexact
488+
Stop-loss set by `set_trailing_pct` is converted to units of ATR
489+
with `mean(Close * pct / atr)` and set with `set_trailing_sl`.
490+
"""
491+
assert 0 < pct < 1, 'Need pct= as rate, i.e. 5% == 0.05'
492+
pct_in_atr = np.mean(self.data.Close * pct / self.__atr) # type: ignore
493+
self.set_trailing_sl(pct_in_atr)
494+
482495
def next(self):
483496
super().next()
484497
# Can't use index=-1 because self.__atr is not an Indicator type

backtesting/test/_test.py

+1
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,7 @@ class S(TrailingStrategy):
926926
def init(self):
927927
super().init()
928928
self.set_atr_periods(40)
929+
self.set_trailing_pct(.1)
929930
self.set_trailing_sl(3)
930931
self.sma = self.I(lambda: self.data.Close.s.rolling(10).mean())
931932

0 commit comments

Comments
 (0)