FAQ · Getting systematic research right

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.

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.

Two kinds of momentum

  • Time-series momentum compares an asset with its own past: hold it when its return over a lookback period is positive. Moskowitz, Ooi and Pedersen documented this across futures markets in 2012. Managed-futures funds are built on it.
  • Cross-sectional momentum compares assets with each other: hold the ones with the best recent returns and avoid the worst. Jegadeesh and Titman's 1993 study of US stocks is the classic reference. It is a ranking problem, covered in the portfolio backtest guide.

This page covers the time-series kind on one market.

Common signals

Sizing by volatility

Trend followers usually size each position so that every market contributes similar risk: qty = risk budget / (volatility × price). A quiet market gets a larger position, a volatile one a smaller one. Without this, a portfolio's result is dominated by whichever market happens to move most. See position sizing.

What to watch for

  • Short histories. A few years can be all trendless or all trending. Use as long a history as you have.
  • Low win rate. Trend following often loses on more than half its trades and makes it up on a few large ones. A drawdown lasting a year or more is normal.
  • Rebalancing costs. Resizing on every bar adds costs; resize when the signal changes or on a schedule.

How Reamer Research handles it

In Reamer Research the signal and the sizing fit in one class:

import numpy as np
import reamer_research as rr

class Momentum:
    lookback = 120
    capital, risk = 10_000, 0.01
    def on_bar(self, d):
        c = d.close
        if c[0] == 0:
            return None
        trend_up = c[-1] > c[0] and c[-1] > c[-60:].mean()
        if trend_up and d.position() == 0:
            vol = np.diff(np.log(c[-60:])).std()        # per-bar volatility
            qty = int(min(self.capital * self.risk / (vol * c[-1]), 0.95 * self.capital / c[-1]))
            return rr.buy_market(qty) if qty > 0 else None
        if not trend_up and d.position() > 0:
            return rr.close_position()

result = rr.backtest(Momentum, 'data/SPY.bin', spread=0.01, commission_per_unit=0.005)
print(result.win_rate, result.profit_factor, result.equity_drawdown_relative)

The sizing is capped below the account's buying power, because the engine rejects an order that would take open notional past equity times leverage, as a margin account would. The same rule runs as a function on_bar(data) or as an object configured with the lookback and risk. Several markets run in one backtest against one account by passing a dictionary of tickers, and result.monte_carlo() reshuffles the trade sequence to show how deep the drawdowns could have been in another order.

Limits to know

  • Futures need rolls. A continuous futures series needs roll handling, which roll_cycle_months provides; see futures rolls and FX swap.
  • Several markets and long histories need a licence. Evaluation Mode runs one ticker over 30 days or 50,000 bars.

A $20 month includes the full kit, so you can run trend following across your own markets 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 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.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 do I backtest a portfolio of several tickers?Run every ticker in one backtest against one shared account, so positions compete for the same capital and margin. Process bars in time order across all tickers, act on each ticker only when it has a fresh bar, and size each position against total equity. Testing tickers one at a time and adding the results misses the shared capital constraint.

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.