Continuous Futures Contract Backtesting: Roll and Adjust Right
Continuous futures contract backtesting needs a stitched series: use additive (Panama) back-adjustment for point-based P&L and point-distance indicators, ratio adjustment for percentage returns, unadjusted data for price levels, and roll on the prior day's volume or open interest.
- The roll gap is a carry-driven price difference between two contracts, not a tradable return, so an unadjusted splice creates fake returns and false stops.
- Additive back-adjustment preserves point moves and can go negative; ratio adjustment preserves percentage returns and cannot cross zero.
- Compute each gap as new_close minus old_close (or the ratio) on the same session date, the last day you held the old contract.
- Decide the roll from the previous day's volume or open interest and apply it the next session, otherwise the rule uses future information.
- Test the stitched series: adjusted daily changes must equal in-contract changes on the held contract, and fills should be simulated on the real contract.
Why does a continuous futures contract show gaps at every roll?
Every futures contract expires, so a long history is a chain of different instruments. On any single day, the December and March contracts trade at different prices because of carry: storage, interest and expected convenience yield. In contango the later contract is higher, in backwardation it is lower.
When you splice the chain, the series jumps by that difference on the day you switch contracts. Nobody could have earned that jump, because holding one contract through the date earns only that contract's own change. A roll in real trading is a close of one position and an open of another, and its only true cost is the spread and slippage.
In continuous futures contract backtesting these fake jumps leak into everything: returns, ATR, moving averages, breakout levels and stop triggers. A trailing stop can fire on a roll day with no market move at all. The fix is to remove the jump from the signal series while keeping the real contract for fills and P&L.
Which stitching method should I use for which backtest?
There is no single best series. The right choice depends on what the strategy reads from the price and how P&L is computed.
| Goal | Series for signals | Roll rule | Why |
|---|---|---|---|
| Percentage-return or volatility-scaled strategy | Ratio (proportional) back-adjusted | Prior-day volume or OI crossover | Returns and percent stops are preserved; no sign flip |
| Point-based, spread or calendar-spread logic | Difference (additive) back-adjusted | Prior-day volume or OI crossover | Point moves and absolute distances are preserved |
| Indicator on price levels (support, round numbers, price-level checks) | Unadjusted, or as-of forward-anchored series | Same as the live rule | Levels match what actually traded |
| Execution simulation | Adjusted series for signals only | Same as the live rule, applied next session | Fills, fees and roll costs use the real contract |
| Commodities that can go near zero or negative (CL in 2020) | Additive only | Volume or OI | Ratio is undefined when a price is zero or negative |
What do Panama, back-adjusted and ratio mean on vendor sites?
Names are inconsistent. The Panama canal method usually means additive (difference) back-adjustment, and some vendors use the name for the additive variant only. The safest approach is to map a vendor's description to these formulas.
Let k index the rolls, where old_k and new_k are the closes of the outgoing and incoming contract on the same session date, the last day the old contract was held.
gap_k = new_k - old_k (difference / Panama)
ratio_k = new_k / old_k (proportional)
Additive : adj_price(t) = price(t) + sum(gap_k for all rolls k after t)
Ratio : adj_price(t) = price(t) * prod(ratio_k for all rolls k after t)
The newest segment is never adjusted, so the latest price equals the live price.
Unadjusted splice: no adjustment (fake jumps at every roll).How do I choose a roll rule without lookahead?
A roll rule has two jobs: pick a contract that is liquid enough to trade, and be computable from data you would have had at the time. Volume or OI crossover rules are the common choice, but they carry a trap. If you compare today's full-day volume and roll at today's close or open, you used information from after the decision point.
Decide on the previous session's data and apply the switch on the next session. The gap is then measured on the previous session, when both contracts had a close. Also only roll into contracts that actually have data on that date, and never into one past its expiry.
Do not roll on the expiry date itself. Liquidity has left, settlement mechanics apply, and some contracts (CL, grains) have first-notice or last-trade dates well before the nominal expiry.
| Rule | How it works | Liquid (ES, ZN) | Thin or seasonal (grains, NG) |
|---|---|---|---|
| Calendar offset (N days before expiry) | Fixed date from the contract calendar | Stable and predictable; slight liquidity lag | Can roll into an illiquid month or miss the active one |
| Business-day offset | Roll N business days before last trade or notice date | Simple and reproducible | Same risk; check the notice date, not just expiry |
| Volume crossover | Next volume > front volume on the previous day | Clean; liquidity shifts in a few days | Noisy, can flip back and forth; add a no-return rule |
| Open-interest crossover | Next OI > front OI on the previous day | Smooth and slower than volume | Often the best match to where hedgers sit; OI data can be delayed |
How do I build a continuous futures series in pandas?
Input is a DataFrame of closes (index: session date, columns: contracts sorted by expiry) and a matching DataFrame of volume. The code builds the roll schedule from the previous day's volume, measures the gap on the previous day, and applies both adjustments backwards.
The final asserts are the test: after adjustment, the daily change of the stitched series must equal the daily change of the held contract, including on the roll day.
import numpy as np
import pandas as pd
def roll_schedule(close, vol):
cols, dates = list(close.columns), close.index
i, rows = 0, []
for t in range(1, len(dates)):
if i + 1 >= len(cols):
break
prev, d = dates[t-1], dates[t]
held, nxt = cols[i], cols[i+1]
have = pd.notna(close.at[prev, held]) and pd.notna(close.at[prev, nxt])
# decide on PREVIOUS session data, apply on d
if have and vol.at[prev, nxt] > vol.at[prev, held]:
rows.append((d, held, nxt, close.at[prev, held], close.at[prev, nxt]))
i += 1 # one-way: never roll back
return pd.DataFrame(rows, columns=['effective', 'old', 'new', 'old_px', 'new_px'])
def stitch(close, sched):
names = [close.columns[0]] + list(sched.new)
starts = list(sched.effective)
pieces = []
for k, c in enumerate(names):
lo = close.index[0] if k == 0 else starts[k-1]
s = close[c].loc[lo:] if k == len(starts) else close[c].loc[lo:starts[k]].iloc[:-1]
pieces.append(s)
gaps = (sched.new_px - sched.old_px).to_numpy()
ratios = (sched.new_px / sched.old_px).to_numpy()
add = np.append(np.cumsum(gaps[::-1])[::-1], 0.0)
mul = np.append(np.cumprod(ratios[::-1])[::-1], 1.0)
raw = pd.concat(pieces)
additive = pd.concat([p + a for p, a in zip(pieces, add)])
ratio = pd.concat([p * m for p, m in zip(pieces, mul)])
held_chg = pd.concat([close[c].diff().loc[p.index] for c, p in zip(names, pieces)])
held_ret = pd.concat([close[c].pct_change().loc[p.index] for c, p in zip(names, pieces)])
return raw, additive, ratio, held_chg, held_ret
sched = roll_schedule(close, vol)
raw, add, rat, held_chg, held_ret = stitch(close, sched)
# Test: adjusted moves equal in-contract moves, including roll days
assert np.allclose(add.diff().iloc[1:], held_chg.iloc[1:])
assert np.allclose(rat.pct_change().iloc[1:], held_ret.iloc[1:])
assert np.isclose(add.diff().iloc[1:].sum(), held_chg.iloc[1:].sum())
# The raw splice fails the same test on roll days:
print((raw.diff().iloc[1:] - held_chg.iloc[1:]).abs().gt(1e-9).sum(), 'fake jumps')How do the choices change returns, SMA and P&L?
Take three rolls with the closes on the last day of the old contract. Gaps are carried in contango, so each one is positive.
Cumulative adjustment applied to older segments: additive +6, +4, +1, 0; ratio about 1.0587, 1.0380, 1.0091, 1.0.
| Roll | Old close | New close (same day) | Gap | Ratio |
|---|---|---|---|---|
| R1 | 100 | 102 | +2 | 1.0200 |
| R2 | 105 | 108 | +3 | 1.0286 |
| R3 | 110 | 111 | +1 | 1.0091 |
What changes in indicators, stops and execution?
Suppose the new contract closes 103 on the day after R1, a real one-point move from 102. The raw series goes from 100 to 103, a +3 point (+3 percent) move, of which 2 points are the fake roll gap. The additive series shows 106 to 107, a +1 point move. The ratio series shows a 0.98 percent return, matching the real move.
The same idea holds for R2 and R3: a raw series records a cumulative fake climb of 6 points that the held contract never earned.
SMA and EMA crossovers on the raw series pick up step changes and cross at rolls. RSI and returns-based signals see false up days. ATR is inflated on roll days, which widens stops and sizes positions smaller. Percentage stops on raw prices can trigger on a gap.
Additive series preserve ATR in points and point-based distances, but percentage stops and returns are distorted on old history. Ratio series preserve percentage ATR and returns. Under either adjustment, absolute levels in old history differ from the price that traded, so round-number or support logic is wrong there and needs unadjusted data.
Cumulative P&L from an additive series is correct in points, so multiply by the point value (ES 50 USD per point, CL 1,000 USD per 1.00). Ratio-adjusted P&L is correct only as a return on the contract's own notional at that time, so convert using the actual contract price held.
For execution-faithful tests, use the adjusted series only for signals. Place orders, fees and fills on the actual held contract, and on a roll day simulate closing the old contract and opening the new one, charging both spreads plus slippage as an explicit roll cost. Position size should use the actual contract's multiplier and margin, and never mix contract sizes (for example ES versus micro MES) in one chain.
What about vendor continuous symbols and common mistakes?
Vendor continuous series differ mainly in roll rule and adjustment. Symbols like @ES are vendor-defined, so confirm the rule. Databento continuous symbols such as ES.c.0 (calendar, nearest expiry), ES.v.0 (volume) and ES.n.0 (open interest) deliver unadjusted prices at the selected roll, so you still apply the adjustment yourself. Norgate and similar vendors offer adjusted series, and the roll and adjustment method should be read from their description.
Common mistakes are listed below.
- Rolling on the expiry date, when liquidity is gone or notice rules apply.
- Computing the gap from different times of day or across a session boundary instead of the same session close.
- Comparing the expired contract's settlement price with an intraday price of the new contract.
- Mixing contracts with different multipliers or sizes in one chain.
- Deciding a volume or OI roll with same-day data (lookahead).
- Adjusting forward so that the latest prices differ from live quotes.
- Running ratio adjustment through negative prices, such as CL in April 2020.
Common questions
Is back-adjusted or unadjusted continuous futures better for backtesting?
Back-adjusted is better for any signal that depends on returns, moving averages or volatility, because it removes fake roll jumps. Unadjusted is only useful for checking actual price levels, and P&L should still be computed on the real contract.
Why does a back-adjusted futures price differ from the real historical price?
Each older segment is shifted or scaled by every later roll gap, so old values include accumulated carry. The latest segment equals the live price and the offset grows as you go back in time.
Can I use the ratio method for crude oil?
Not safely across periods where prices touch zero or turn negative, as CL did in April 2020. A ratio with a non-positive price gives meaningless or negative factors, so use the additive method there, or exclude the affected rolls.
Should I roll by volume or open interest?
Volume reacts faster and suits liquid contracts like ES, but can flip in thin markets. Open interest is smoother and is often closer to where hedgers sit, though its data can lag. In either case use the previous day and make it one-way.
Does adding new data change my backtest results?
Yes. A new roll changes the adjustment applied to all older prices, so adjusted levels shift while in-contract moves do not. Recompute the whole series after each roll and avoid storing adjusted levels as fixed features.