FAQ · Getting systematic research right

How do I backtest an ATR stop or trailing stop in Python?

Set the initial stop a multiple of the average true range below the entry, then on each closed bar raise it to the close minus the same multiple, never lowering it. The stop must rest as a real order that fills inside the next bar, at the stop price or worse on a gap, rather than being checked against the next close.

Set the initial stop a multiple of the average true range below the entry, then on each closed bar raise it to the close minus the same multiple, never lowering it. The stop must rest as a real order that fills inside the next bar, at the stop price or worse on a gap, rather than being checked against the next close.

Average true range

ATR, another of Wilder's 1978 indicators, measures how far price typically moves in a bar. The true range of a bar is the largest of:

  • high − low;
  • |high − previous close|;
  • |low − previous close|.

ATR is the average of the true range over n bars, usually 14. A stop placed a multiple of ATR away adjusts to each market's volatility: wide when it is volatile, close when it is quiet.

Stop types

  • Fixed ATR stop: entry − k × ATR, set once.
  • Trailing ATR stop: each bar, close − k × ATR, only ever moved up for a long. Multiples of 2 to 3 are common.
  • Chandelier exit: the highest high since entry − k × ATR, which trails from the extreme instead of the close.

The same ATR also sizes the position: risking a fixed amount per trade means qty = risk / (k × ATR), as in position sizing.

Where stop backtests go wrong

  • Checking the stop against the close. A real stop triggers when price trades through it, often well before the close. Checking only closes makes losses smaller than they were.
  • Gaps. A stop below an overnight gap fills at the open, below the stop. Filling at the stop price overstates the result.
  • Moving the stop with future data. The new level may use only bars that have closed.
  • Stop and target in one bar. If both are touched, which filled first depends on the path inside the bar. See stop and target in the same bar.

How Reamer Research handles it

In Reamer Research a stop loss travels with the position as a bracket and fills inside the bar from the tick path, with a gap filling at the first tick after the open. modify_position replaces the brackets, so trailing is a comparison on each bar:

import numpy as np
import reamer_research as rr

def atr(high, low, close, n):
    prev = close[-n - 1:-1]
    tr = np.maximum(high[-n:] - low[-n:],
                    np.maximum(abs(high[-n:] - prev), abs(low[-n:] - prev)))
    return tr.mean()

class AtrTrail:
    lookback = 21
    n, mult, qty = 14, 3.0, 10
    def on_bar(self, d):
        if d.close[0] == 0:
            return None
        a = atr(d.high, d.low, d.close, self.n)
        if d.position() == 0:
            if d.close[-1] > d.high[:-1].max():          # 20-bar breakout
                return rr.buy_market(self.qty, stop_loss=d.close[-1] - self.mult * a)
            return None
        state = d.position_state()
        trail = d.close[-1] - self.mult * a
        if trail > state['stop_loss']:                   # only ever raise the stop
            return rr.modify_position(ticker=d.tickers[0], stop_loss=trail,
                                      take_profit=state['take_profit'])

result = rr.backtest(AtrTrail, 'data/SPY.bin', spread=0.01, commission_per_unit=0.005)

d.position_state() returns the open position's entry price, quantity, current brackets and unrealised profit. modify_position replaces both brackets, so the code passes the current take profit back to keep it. The same rule runs as a function on_bar(data) or as an object configured with the ATR length and multiple. The kit's examples/atr_stop_bracket.py and examples/atr_limit_bracket.py show ATR-based entries with brackets, and the visual trade diagnostics tool shows each trade on its candles with its stop-loss level and whether it exited at the stop.

Limits to know

  • The indicator is yours. ATR is the few lines above; the engine supplies the bars and fills the stop.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to check the stop logic; longer tests need a licence.

A $20 month includes the full kit, so you can test your own stop rules on your own data and cancel if it does not fit.

Next questions

How do I size positions in a backtest?Choose a sizing rule and compute the quantity at each entry. Fixed fractional risks a set share of equity per trade, volatility targeting scales size so each position carries similar risk, and ATR sizing sets quantity so a stop placed a multiple of ATR away loses a fixed amount. Then check the size against your buying power.How should a backtest fill a stop and a target that both fall inside one bar?Reamer Research settles it on a seeded tick path it generates inside the bar: whichever level the path touches first is the exit, the same way on every run. The bar alone cannot say which was hit first, so a backtest should settle it by one stated rule, apply that rule the same way on every run, and let you check how much the result depends on it. A strategy whose result changes when the rule changes depends on something the data does not contain.How do I backtest a Donchian channel breakout strategy in Python?Place a buy stop at the highest high of the last N bars so the entry fills where price actually breaks out, and exit on a stop at the lowest low of a shorter channel. Filling at the breakout bar's close or the next open instead gives a different, usually better, price than a real stop order would get.How do I backtest a momentum or trend following strategy in Python?Measure trend from past closes only, such as the return over the last 12 months or price above a long average, hold long while it is positive and exit when it turns, and size each position by its recent volatility. Test across many years and several markets, because trend following earns most of its return in a few large moves.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.