backtesting.py
backtesting.py copied to clipboard
Trailing pct instead of ATR
Expected Behavior
Allow trailing with PRC instead of ATR
Actual Behavior
Currently the backtesting allow trailing sels only based on ATR, most of crypto bots works in pct trailing (pct for trailing activation and then pct trailing for position close).
This is the whole of TrailingStrategy:
https://github.com/kernc/backtesting.py/blob/1ee5670d03b26680d9add5c96a9f98e44fc722a2/backtesting/lib.py#L406-L450
It should be fairly simple to adapt/duplicate one for percent values.
Yup, the trailing strategy only supports ATR multiples, but most of the cyrpto bots trail in percentage would be nice to implement as option for trailing strategy so you can choose between ATR or pct for backtesting the best trailing.
As a quick workaround, something like this might work:
def pct_to_atr(pct: float, data: pd.DataFrame):
"""Express `pct` change in units of ATR."""
assert 0 < pct < 1
h, l, c_prev = data.High, data.Low, pd.Series(data.Close).shift(1)
tr = np.max([h - l, (c_prev - h).abs(), (c_prev - l).abs()], axis=0)
atr = np.nanmean(tr)
return (pct * data.Close.iloc[-1]) / atr
Actually i would need the oppsite, as with backtesting i can find the optimal atr value for trailing the will have to calculate the equivalent pct for program the bot. I'll find a solution, thanks anyway.
Should be rather easy to invert, something like:
def atr_to_pct(n_atr: float, data: pd.DataFrame):
"""Express `n_atr` in units of ATR as percentage of current price."""
h, l, c_prev = data.High, data.Low, pd.Series(data.Close).shift(1)
tr = np.max([h - l, (c_prev - h).abs(), (c_prev - l).abs()], axis=0)
atr = np.nanmean(tr)
return n_atr * atr / data.Close.iloc[-1]
I am working on this enhancement.
@kernc can you review this change?