FAQ · Getting systematic research right

How do I backtest a moving average crossover strategy in Python?

Compute a fast and a slow moving average from closed bars only, buy when the fast one crosses above the slow one, and exit when it crosses back below. Fill each signal at the next bar, not at the close that produced it, and include spread and commission, because a crossover trades often and gives back much of its edge in costs.

Compute a fast and a slow moving average from closed bars only, buy when the fast one crosses above the slow one, and exit when it crosses back below. Fill each signal at the next bar, not at the close that produced it, and include spread and commission, because a crossover trades often and gives back much of its edge in costs.

The rule

A simple moving average (SMA) of length n is the mean of the last n closes. The crossover compares two of them:

  • Entry: the fast average (say 10 bars) moves from below the slow one (say 40 bars) to above it.
  • Exit: the fast average moves back below the slow one.

A cross is a change between two bars, so the rule compares this bar's averages with the previous bar's. Checking only "fast above slow" buys on every bar of an uptrend instead of once.

Common variants use exponential averages (EMA), which react faster, add a short side on the cross down, or use the 50 and 200-day averages, the pair often called the golden cross and death cross.

What makes a crossover backtest wrong

  • Filling at the signal bar's close. The cross is only known once the bar has closed, so the earliest realistic fill is the next bar. Filling at the same close is a small look-ahead bias that adds up over hundreds of trades.
  • No costs. Crossovers whipsaw in sideways markets, entering and exiting repeatedly for small losses. Each round trip pays spread and commission.
  • Picking the lengths on the whole history. Searching every fast and slow pair and keeping the best fits noise. Choose on one period and check on a later one, as in optimising without overfitting.
  • Warmup. The first slow-length bars have no valid slow average. Skip them rather than averaging fewer bars.

How Reamer Research handles it

In Reamer Research the strategy is a function, a class or a configured object with on_bar. Here it is as a function:

import reamer_research as rr

FAST, SLOW, QTY = 10, 40, 10

def ma_cross(d):
    c = d.close
    if c[0] == 0:                                   # window still filling
        return None
    up_now = c[-FAST:].mean() > c[-SLOW:].mean()
    up_before = c[-FAST - 1:-1].mean() > c[-SLOW - 1:-1].mean()
    if up_now and not up_before and d.position() == 0:
        return rr.buy_market(QTY)
    if up_before and not up_now and d.position() > 0:
        return rr.close_position()

result = rr.backtest(ma_cross, 'data/SPY.bin', lookback=SLOW + 1,
                     spread=0.01, commission_per_unit=0.005)
print(result.closed_trades_count, result.profit_factor, result.equity_drawdown_relative)

The window passed to on_bar holds only closed bars, lookback=SLOW + 1 gives room for the previous bar's slow average, and the window is zero-padded until it fills. A market order returned on one bar fills from the next bar's first tick, with the spread and slippage you set. The same rule runs as a class with the lengths as attributes, or as an object built with MaCross(fast=10, slow=40), which makes a parameter sweep a loop over constructor arguments.

result.open_viewer() opens the visual trade diagnostics tool, which shows each crossover entry and exit on the price chart, so a run of whipsaw losses is easy to see.

Limits to know

  • The averages are yours. The engine supplies the bars; the indicator is a few lines of NumPy, as above, or any library you already use.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. That is enough to check the code on the kit's sample data; testing years of daily bars needs a licence.

A $20 month includes the full kit, so you can run your own crossover on your own history and cancel if it does not fit.

Next questions

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.