Skip to content

Commit

Permalink
ENH: lib.TrailingStrategy: set trailing SL by percent
Browse files Browse the repository at this point in the history
Fixes #223
Closes #377
  • Loading branch information
kernc committed Feb 20, 2025
1 parent 0853e96 commit 9b4efb5
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
15 changes: 14 additions & 1 deletion backtesting/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,11 +474,24 @@ def set_atr_periods(self, periods: int = 100):

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

def set_trailing_pct(self, pct: float = .05):
"""
Set the future trailing stop-loss as some percent (`0 < pct < 1`)
below the current price (default 5% below).
.. note:: Stop-loss set by `pct` is inexact
Stop-loss set by `set_trailing_pct` is converted to units of ATR
with `mean(Close * pct / atr)` and set with `set_trailing_sl`.
"""
assert 0 < pct < 1, 'Need pct= as rate, i.e. 5% == 0.05'
pct_in_atr = np.mean(self.data.Close * pct / self.__atr) # type: ignore
self.set_trailing_sl(pct_in_atr)

def next(self):
super().next()
# Can't use index=-1 because self.__atr is not an Indicator type
Expand Down
1 change: 1 addition & 0 deletions backtesting/test/_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,7 @@ class S(TrailingStrategy):
def init(self):
super().init()
self.set_atr_periods(40)
self.set_trailing_pct(.1)
self.set_trailing_sl(3)
self.sma = self.I(lambda: self.data.Close.s.rolling(10).mean())

Expand Down

0 comments on commit 9b4efb5

Please sign in to comment.