FAQ · Getting systematic research right

How do I backtest a Bollinger Band strategy in Python?

Build the bands from a moving average and the standard deviation of the same closed bars, then choose a side. For reversion, buy below the lower band and short above the upper one, exiting at the middle. For breakouts, trade in the direction of the band that was crossed. Both need next-bar fills and realistic costs to be trusted.

Build the bands from a moving average and the standard deviation of the same closed bars, then choose a side. For reversion, buy below the lower band and short above the upper one, exiting at the middle. For breakouts, trade in the direction of the band that was crossed. Both need next-bar fills and realistic costs to be trusted.

The bands

Bollinger Bands, developed by John Bollinger in the 1980s, have three lines:

  • Middle: the n-bar simple moving average, usually n = 20.
  • Upper and lower: the middle plus and minus k standard deviations of the same n closes, usually k = 2.

The bands widen when prices are volatile and narrow when they are quiet. A close outside a band is a large move relative to recent volatility.

Two opposite strategies

  • Reversion: a close below the lower band is treated as stretched. Buy, and exit when price returns to the middle. Short above the upper band in the same way.
  • Breakout: a close above the upper band, especially after the bands have narrowed (the "squeeze"), is treated as the start of a move. Buy and trail a stop.

Which one suits an instrument is an empirical question. Test both on one period and confirm the winner on a later one.

Details that change results

  • Population or sample deviation. NumPy's std divides by n by default; pandas' divides by n − 1. The bands differ slightly, so match whatever you compare against.
  • Include the current bar or not. Bands computed from a window that includes the signal bar react to that bar. Either is valid if used consistently, as long as no future bar is included.
  • Shorts cost money. The short side pays borrow fees on stocks, which a basic backtest leaves out.

How Reamer Research handles it

In Reamer Research the reversion version is a small class. With lookback = 20, the window passed to on_bar is exactly the bands' 20 closed bars:

import reamer_research as rr

class BollingerReversion:
    lookback = 20
    k = 2.0
    qty = 10
    def on_bar(self, d):
        c = d.close
        if c[0] == 0:
            return None
        mid, sd = c.mean(), c.std()
        pos = d.position()
        if pos == 0 and c[-1] < mid - self.k * sd:
            return rr.buy_market(self.qty)
        if pos == 0 and c[-1] > mid + self.k * sd:
            return rr.sell_market(self.qty)
        if (pos > 0 and c[-1] >= mid) or (pos < 0 and c[-1] <= mid):
            return rr.close_position()

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

sell_market while flat opens a short, and close_position closes whichever side is open. The same rule runs as a function on_bar(data) or as an object configured with k and the length. The visual trade diagnostics tool shows each entry against the price, so you can see whether losses come from trends that kept going past the band.

Limits to know

  • Borrow fees are yours to add. swap_per_unit models overnight financing as a charge on longs and a credit on shorts, so a stock borrow fee on the short side is subtracted in your own code.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to check the code; a full test needs a licence.

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

Next questions

How do I backtest an RSI mean reversion strategy in Python?Compute RSI with Wilder's smoothing from closed bars, buy when it falls below an oversold level, usually only while price is above a long moving average, and sell when RSI recovers. Use the same smoothing your charting tool uses, fill at the next bar, and include costs, because mean reversion trades are short and their average gain is small.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 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.How realistic do slippage and spread need to be in a backtest?Realistic enough that the result survives them. Set spread, slippage and commission per instrument from what your broker actually charges, let spread and slippage widen when the market moves fast, and then rerun at one and a half and two times those costs. A strategy whose edge disappears under slightly higher costs was never a reliable edge.

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.