backtesting.py icon indicating copy to clipboard operation
backtesting.py copied to clipboard

Trailing pct instead of ATR

Open riodda opened this issue 4 years ago • 7 comments

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).

riodda avatar Jan 08 '21 09:01 riodda

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.

kernc avatar Jan 08 '21 14:01 kernc

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.

riodda avatar Jan 08 '21 14:01 riodda

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

kernc avatar Jan 08 '21 15:01 kernc

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.

riodda avatar Jan 10 '21 09:01 riodda

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]

kernc avatar Jan 11 '21 02:01 kernc

I am working on this enhancement.

zlpatel avatar Jun 12 '21 20:06 zlpatel

@kernc can you review this change?

zlpatel avatar Jun 13 '21 20:06 zlpatel