FAQ · Getting systematic research right

How do I backtest a futures trend following strategy in Python?

Go long when a contract's return over a lookback such as three or twelve months is positive and short when it is negative, size each position so every market risks a similar amount, and test on a continuous series whose roll jumps are not counted as profit. Contract size, roll handling and costs per contract decide whether the result means anything.

Go long when a contract's return over a lookback such as three or twelve months is positive and short when it is negative, size each position so every market risks a similar amount, and test on a continuous series whose roll jumps are not counted as profit. Contract size, roll handling and costs per contract decide whether the result means anything.

The rule

Time-series momentum, the core of most managed-futures funds, is simple:

  • Signal. The sign of the return over the lookback. Positive: long. Negative: short.
  • Size. Divide a fixed dollar risk by the contract's recent volatility in dollars, so a quiet bond future and a volatile crude future carry similar risk.
  • Rebalance. Daily or weekly, flipping when the sign flips.

It is applied across many markets, equity indices, bonds, currencies, energy, metals and grains, because a handful of strong trends a year pay for many small losses.

Three futures details that change the result

  • Roll jumps. A continuous series built from back-to-back contracts jumps at each roll. Counted as returns, those jumps add or remove profit that never happened, and they can flip the signal. See futures rolls and FX swap.
  • Contract size. One E-mini S&P 500 point is worth $50 a contract; one crude oil point $1,000. Profit, costs and sizing must use each contract's point value.
  • Costs per contract. Commission is charged per contract, and each roll trades twice. A rule that holds for months pays little; one that flips weekly pays a lot.

How Reamer Research handles it

Reamer Research rolls an unadjusted continuous series on your calendar: at each roll it rescales the open position and resting orders by the jump, so profit from the roll is not counted, and it records each roll in roll_log. The strategy still reads the raw prices, so this configured object computes the same roll dates and leaves the jump out of its signal:

import calendar
from datetime import date, datetime, timedelta, timezone
import numpy as np
import reamer_research as rr

def roll_boundaries(years, months, before=5):
    """The engine's roll dates: `before` weekdays before each cycle month's last day, UTC."""
    out = []
    for y in years:
        for m in months:
            day, counted = date(y, m, calendar.monthrange(y, m)[1]), 0
            while counted < before:
                day -= timedelta(days=1)
                counted += day.weekday() < 5
            out.append(datetime(day.year, day.month, day.day, tzinfo=timezone.utc).timestamp())
    return np.array(sorted(out))

class FuturesTrend:
    def __init__(self, lookback=63, point_value=50, risk_dollars=1000, max_contracts=5,
                 months=(3, 6, 9, 12), years=range(2000, 2031)):
        self.lookback = lookback + 1
        self.point_value, self.risk, self.cap = point_value, risk_dollars, max_contracts
        self.rolls = roll_boundaries(years, months)
    def on_bar(self, d):
        tv = d[d.tickers[0]]                                # this market's window
        if tv.close[0] == 0:
            return None
        rets = np.diff(np.log(tv.close))
        crossed = np.diff(np.searchsorted(self.rolls, tv.ts, side='right')) > 0
        rets[crossed] = 0.0                                 # the roll jump is not a move
        vol_points = np.std(rets[-20:]) * tv.close[-1]      # daily move, in points
        if vol_points == 0:
            return None
        contracts = min(self.cap, max(1, round(self.risk / (vol_points * self.point_value))))
        target = np.sign(rets.sum()) * contracts * self.point_value
        trade = target - d.position()
        if abs(trade) < self.point_value:                   # within one contract
            return None
        return rr.buy_market(trade) if trade > 0 else rr.sell_market(-trade)

ES = dict(roll_cycle_months=(3, 6, 9, 12), roll_days_before_monthend=5,
          commission_per_unit=2.25 / 50, spread=0.25)
result = rr.backtest(FuturesTrend(point_value=50), {'ES': 'data/ES_daily_unadjusted.bin'},
                     ticker_config={'ES': ES}, initial_capital=100_000, leverage=10)
print(result.net_pnl, result.sharpe_ratio, len(result.json()['roll_log']), 'rolls')

Quantity is in point-value units: one E-mini contract is 50 units, so a 1-point move is $50 and commission per unit is the per-contract fee divided by 50. leverage=10 lets the account hold contracts worth more than its equity, as futures margin does, and max_contracts keeps a calm stretch from sizing past what the account can carry. Each market gets its own entry in ticker_config and its own point value. The same rule could be a plain on_bar(data) function, or a class with class attributes for a single market.

Limits to know

  • Contract size goes in the quantity. There is no point-value field; scale quantities and per-unit costs as above.
  • Margin is equity times leverage. Exchange initial and maintenance margins are yours to model through leverage or position limits.
  • A roll rescales; it does not trade. To charge the roll's two trades, close and reopen in the strategy on the roll bar.
  • Evaluation Mode runs 30 days or 50,000 bars of one ticker. Enough to check one contract's roll; a multi-market portfolio over years needs a licence.

A $20 month includes the full kit, so you can run trend following across your own futures data and cancel if it does not fit.

Next questions

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.Can I backtest futures with roll handling, or FX with swap costs?Yes, but only if the backtest handles two things a plain price series hides. In a continuous futures series, the price jump at each contract roll must not be counted as profit or loss. An FX position held overnight must be charged or credited swap every night it is held. A backtest that skips either can report a result the account would never have produced.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 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.

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.