FAQ · Getting systematic research right

How do I backtest an opening range breakout strategy in Python?

Use intraday bars, take the high and low of the first minutes of each session, then rest a buy stop above the range and a sell stop below it, with the opposite side of the range as the stop loss. Allow one trade a day and close everything before the session ends. Daily bars cannot test this strategy, because they do not show which came first.

Use intraday bars, take the high and low of the first minutes of each session, then rest a buy stop above the range and a sell stop below it, with the opposite side of the range as the stop loss. Allow one trade a day and close everything before the session ends. Daily bars cannot test this strategy, because they do not show which came first.

The rule

The opening range is the high and low of the first part of the session, commonly 5, 15, 30 or 60 minutes. Toby Crabel's 1990 book on opening range breakouts made it a standard day-trading setup. A typical version:

  1. After the range closes, rest a buy stop at its high and a sell stop at its low.
  2. Whichever fills first is the trade; its stop loss is the other side of the range.
  3. One trade per day.
  4. Close any open position before the session ends.

Variants add a profit target at a multiple of the range, filter on the range's width, or trade only one side.

What the backtest needs

  • Intraday bars. The range and the breakout happen within one day, so the test needs bars of a few minutes or less.
  • Stop orders filled inside the bar. The entry is where price crosses the range, which a close-based fill misses.
  • Correct session times. Bars are often stamped in UTC, and US session times in UTC move by an hour with daylight saving. Get this wrong and the "opening range" is the wrong half hour for part of the year.
  • A close-out rule that fills. The exit before the close must happen on a bar that still exists that day.

How Reamer Research handles it

Reamer Research runs one bar at a time with stop orders filled from the tick path inside each bar. This configured object finds the session's first bars by date, rests both stops for one bar at a time, and flattens at a set time:

import numpy as np
import reamer_research as rr

class OpeningRange:
    lookback = 100                                  # more bars than one session
    def __init__(self, range_bars=6, flat_at=(20, 50), qty=10):
        self.range_bars, self.qty = range_bars, qty
        self.flat_at = flat_at[0] * 3600 + flat_at[1] * 60
        self.traded_day = None
    def on_bar(self, d):
        tv = d[d.tickers[0]]
        day = tv.ts // 86400
        if d.position() != 0:
            self.traded_day = day[-1]
        if tv.ts[-1] % 86400 >= self.flat_at:       # flat before the close
            return rr.orders(rr.cancel_all(), rr.close_all())
        today = np.flatnonzero((day == day[-1]) & (tv.close != 0))
        if len(today) < self.range_bars or d.position() != 0 or self.traded_day == day[-1]:
            return None
        first = today[:self.range_bars]
        hi, lo = tv.high[first].max(), tv.low[first].min()
        return rr.orders(rr.buy_stop(hi, self.qty, tif='IOC', stop_loss=lo),
                         rr.sell_stop(lo, self.qty, tif='IOC', stop_loss=hi))

result = rr.backtest(OpeningRange(range_bars=6, flat_at=(20, 50)), 'data/SPY_5min.bin',
                     spread=0.01, commission_per_unit=0.005)

With 5-minute bars, range_bars=6 is a 30-minute range. flat_at is the bar start time, in the bars' own time stamps, from which the strategy closes everything. Each ticker's window carries its bar times in ts, so the session date is integer arithmetic. The same rule runs as a function on_bar(data) or a class as well. The kit's sample_data/SAMPLE_5min.csv is a 5-minute series this code runs on in Evaluation Mode, with flat_at=(15, 45) because its bars are stamped in New York time.

Limits to know

  • One order cancels the other is yours. Both stops rest for one bar; a single wide bar can fill both, in which case the second closes the first. Count how often that happens in the trade list.
  • Session times are yours. The engine uses the time stamps you give it; adjust flat_at for daylight saving or stamp bars in exchange time.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. That is about a month of 5-minute bars; longer tests need a licence.

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

Next questions

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 an overnight return strategy in Python?Use intraday bars so the backtest can buy near the close and sell at the next session's open, and charge spread and commission on both. Daily bars alone cannot do it, because the order would fill at the next day's open, not the close. Costs matter more here than in most strategies, because the position trades every day.How do I backtest a strategy across several timeframes?Run the strategy on the fastest timeframe it trades on and build the slower ones from it, using only completed higher-timeframe bars. The most common mistake is reading an hourly or daily bar before it has closed, which gives the strategy prices it could not have known.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.

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.