Howwise RSS
Trading Software7 min read

Vectorized Backtest in Pandas: Template and Lookahead Test

Short answer

A vectorized backtest in pandas computes the signal, a one-bar-lagged position, returns, costs and the equity curve as whole-column operations instead of a row loop, often 100x or more faster than iterrows, as long as you use position = signal.shift(1).

Key takeaways
  • Replace iterrows with column operations: signal, position = signal.shift(1), net = position * ret - turnover * cost, equity = (1 + net).cumprod().
  • Never multiply an unshifted signal by the same bar's return, because that is the classic source of fake profits.
  • Prove correctness with two tests: np.allclose against a slow reference loop, and a truncation test showing past results do not change when future rows are removed.
  • Stateful holds can be vectorized with where/mask plus ffill, but trailing stops, intrabar fills and equity-based sizing need a numba loop or an event-driven engine.
  • The hybrid pattern, vectorized indicators plus a numba loop over numpy arrays for state only, covers most cases that outgrow pure pandas.

Why is a row-by-row backtest so slow in pandas?

Each iteration of iterrows() builds a new Series object, and each df.loc[i, 'col'] inside a Python loop does index lookups, alignment checks and dtype handling. That is microseconds of interpreter overhead per row, multiplied by millions of minute bars. A column operation such as close.pct_change() runs one compiled loop over a contiguous float64 array with no per-row Python objects.

Typical speedups for a moving-average style strategy are 100x to 1000x, and the gap grows with data size. Exact numbers depend on hardware, pandas version and strategy, so measure your own with a snippet like this.

import timeit
import numpy as np, pandas as pd

n = 200_000
rng = np.random.default_rng(0)
df = pd.DataFrame({"close": 100 * np.exp(np.cumsum(rng.normal(0, 5e-4, n)))})

def with_iterrows():
    prev, out = None, []
    for _, row in df.iterrows():
        out.append(0.0 if prev is None else row["close"] / prev - 1)
        prev = row["close"]
    return out

def vectorized():
    return df["close"].pct_change().fillna(0.0)

print("iterrows  :", timeit.timeit(with_iterrows, number=1))
print("vectorized:", timeit.timeit(vectorized, number=20) / 20)

What does a complete vectorized backtest look like?

The template below uses synthetic minute data, a fast/slow SMA crossover as a placeholder signal (any boolean or -1/0/1 Series works), a lagged position, costs, and an equity curve. It also includes a slow reference loop and the two verification tests. The strategy is only a stand-in for the plumbing.

Note that comparisons against NaN evaluate to False, so the warm-up rows of the rolling means automatically give signal 0 and position 0. Still check for NaNs explicitly, because a NaN that reaches cumprod() poisons every later row.

import numpy as np, pandas as pd

def make_prices(n=100_000, seed=0):
    rng = np.random.default_rng(seed)
    idx = pd.date_range("2024-01-01", periods=n, freq="min", tz="UTC")
    close = 100 * np.exp(np.cumsum(rng.normal(0, 5e-4, n)))
    return pd.Series(close, index=idx, name="close")

def vector_backtest(close, fast=20, slow=100, fee=4e-4, slip=1e-4):
    signal = (close.rolling(fast).mean() > close.rolling(slow).mean()).astype(float)
    position = signal.shift(1).fillna(0.0)          # bar t signal trades on bar t+1
    ret = close.pct_change().fillna(0.0)            # simple returns
    gross = position * ret
    turnover = position.diff().abs().fillna(0.0)
    cost = turnover * (fee + slip)                  # per unit of position change
    net = gross - cost
    equity = (1.0 + net).cumprod()
    return pd.DataFrame({"position": position, "net": net, "equity": equity})

def loop_backtest(close, fast=20, slow=100, fee=4e-4, slip=1e-4):
    c = close.to_numpy()
    mf = close.rolling(fast).mean().to_numpy()
    ms = close.rolling(slow).mean().to_numpy()
    eq, equity, prev_pos, sig_prev = np.empty(len(c)), 1.0, 0.0, 0.0
    for t in range(len(c)):
        pos = sig_prev                               # decided on the previous bar
        r = c[t] / c[t - 1] - 1.0 if t > 0 else 0.0
        cost = abs(pos - prev_pos) * (fee + slip) if t > 0 else 0.0
        equity *= 1.0 + pos * r - cost
        eq[t] = equity
        prev_pos = pos
        sig_prev = 1.0 if mf[t] > ms[t] else 0.0
    return eq

close = make_prices()
res = vector_backtest(close)
assert not res["equity"].isna().any()
assert np.allclose(res["equity"].to_numpy(), loop_backtest(close))

def test_no_lookahead(close, cut=70_000):
    full = vector_backtest(close)
    part = vector_backtest(close.iloc[:cut])
    assert np.allclose(full["equity"].iloc[:cut], part["equity"])

test_no_lookahead(close)
print("OK:", res["equity"].iloc[-1])
Tip: The reference loop deliberately shares the rolling means with the vectorized version, so it checks the position, return, cost and compounding logic. If you also want to check the indicator, rewrite it with an explicit running window on a 2,000-row sample.

How do I avoid look-ahead bias with shift?

The signal at bar t is computed from the close of bar t, but the return of bar t is already realized by that close. Multiplying them credits the strategy with a move it could not have traded. The fix is one line: lag the position so the bar t signal earns the bar t+1 return.

Before and after on the same data shows how large the damage can be. The biased version typically looks spectacular because the signal is partly built from the very return it is paid on.

sig = (close.rolling(20).mean() > close.rolling(100).mean()).astype(float)
ret = close.pct_change().fillna(0.0)

biased = (sig * ret)                      # WRONG: same-bar signal x same-bar return
correct = (sig.shift(1).fillna(0) * ret) # signal at t earns return at t+1

# Truncation test idea: results up to row k must not depend on rows after k.
# A negative shift (shift(-1)), a full-sample normalization (z-score using
# the whole series), or a centered rolling window will all fail it.
Warning: Shifting only catches the obvious bug. Whole-sample statistics (global mean/std scaling, fitted parameters, resample() labels that use the bar's closing timestamp) leak the future in less visible ways. The truncation test catches these too, so keep it in your test suite and run it on every new feature.

How do returns, costs and execution price interact?

Use one return convention end to end. Simple returns (pct_change) compound with (1 + r).cumprod() and aggregate across assets by weighting. Log returns (np.log(close).diff()) add over time with cumsum().apply(np.exp) but do not add across assets. Mixing them, for example subtracting a simple-return cost from a log return, introduces errors that grow with volatility.

Costs come from turnover, the absolute change in position. Going from -1 to +1 has turnover 2, so it pays the cost twice. Fill the first diff() NaN with 0 or the whole equity curve becomes NaN.

The execution assumption changes both the code and the result. Every valid row uses a lagged position, signal.shift(1). Only the return series changes. The template above pairs it with close.pct_change(), which assumes a fill at the signal bar's own close.

AssumptionReturn seriesPositionWhat it modelsMain risk
Fill at close of signal barclose.pct_change()signal.shift(1)Signal on bar t-1 filled at that bar's closing price (market-on-close style, the template default)Optimistic: assumes you trade at the exact price that generated the signal
Fill at next openopen.shift(-1) / open - 1signal.shift(1)Signal on the close, order at the next openLast row is NaN (fillna(0)); open prices can be unrealistic for thin sessions
Fill at next bar closeclose.shift(-1) / close - 1signal.shift(1)Signal on bar t-1, order filled one full bar later at the close of bar tLast row is NaN (fillna(0)); the most conservative of the three, and it adds one bar of signal delay
Warning: Never pair an unshifted signal with close.pct_change(). Row t's return is already realized by the close that the signal uses, so it is always same-bar look-ahead and is not valid under any execution assumption.

How do I vectorize stateful signals, per-trade stats and many assets?

Enter on a cross and hold until an exit signal is a state machine, but it collapses to forward-fill: mark the event bars, leave everything else NaN, and ffill. Apply the shift after the fill.

Per-trade statistics need a trade id: the cumulative sum of entries. Grouping by that id is one vectorized groupby, not a loop over trades.

For many assets, keep prices in a wide DataFrame (rows are timestamps, columns are symbols) on a shared index. Operate on the whole frame, normalize weights row-wise with div(axis=0), and sum across columns. Avoid groupby loops over symbols, which reintroduce per-symbol Python overhead.

fast, slow = close.rolling(20).mean(), close.rolling(100).mean()
enter = (fast > slow) & (fast.shift(1) <= slow.shift(1))
exit_ = (fast < slow) & (fast.shift(1) >= slow.shift(1))

state = pd.Series(np.nan, index=close.index)
state[enter] = 1.0
state[exit_] = 0.0
position = state.ffill().fillna(0.0).shift(1).fillna(0.0)

net = position * close.pct_change().fillna(0.0)
trade_id = (position.diff() > 0).cumsum()
on = position > 0
trade_ret = np.expm1(np.log1p(net[on]).groupby(trade_id[on]).sum())

# Multi-asset: prices is a wide DataFrame on one aligned index
# sig = prices.rolling(20).mean() > prices.rolling(100).mean()
# w = sig.shift(1).astype(float)
# w = w.div(w.sum(axis=1).replace(0, np.nan), axis=0).fillna(0.0)
# port_ret = (w * prices.pct_change()).sum(axis=1)
# turnover = w.diff().abs().sum(axis=1).fillna(0.0)

When should I stop vectorizing a backtest?

Vectorization works when position at bar t is a function of past data only, not of the strategy's own earlier fills. Once a decision depends on entry price, running peak, cash, or the equity curve, each row needs the previous row's result, and pandas cannot express that without a loop.

A vectorized stop loss is therefore only an approximation: you can test close-to-close stops with rolling min/max, but intrabar hits (stop touched between open and close) and trailing stops need a sequential pass. The pragmatic design is a hybrid: compute indicators and raw signals in pandas, then run only the stateful part in a numba loop over numpy arrays.

RequirementStay vectorizedHybrid (numba state loop)Event-driven (e.g. backtrader)
Fixed-rule signal, fixed size, proportional costsYesNot neededOverkill
Trailing stop, fixed stop on entry priceApproximation onlyYesYes
Intrabar stop/target using high/lowNoYes, if OHLC is enoughYes
Sizing from running equity, margin, cash limitsNoYesYes
Partial fills, order book, latency, order typesNoHardYes
Reuse live order and event codeNoNoYes
from numba import njit
import numpy as np

@njit(cache=True)
def trailing_stop_position(signal, close, stop_pct):
    n = len(close)
    pos = np.zeros(n)
    holding, peak = False, 0.0
    for t in range(1, n):
        if holding:
            peak = max(peak, close[t - 1])
            if close[t - 1] <= peak * (1.0 - stop_pct):
                holding = False
        elif signal[t - 1] == 1.0:
            holding, peak = True, close[t - 1]
        pos[t] = 1.0 if holding else 0.0
    return pos

# pos = trailing_stop_position(sig.to_numpy(), close.to_numpy(), 0.02)
# position = pd.Series(pos, index=close.index)  # then reuse returns/costs/equity
Tip: Pass .to_numpy() arrays to numba, never Series or DataFrames. Then feed the resulting position into the same returns, costs and equity code, and keep the slow reference test: the numba loop is the new thing to verify.

How do I handle memory, dtypes and metrics on large data?

Minute data over years fits comfortably in float64, but tick data may not. float32 halves memory and is fine for stored prices, but do the cumulative product in float64, because float32 has about 7 significant digits and compounding millions of bars drifts visibly. Avoid copies: use inplace-free expressions on views, drop intermediate columns, and do not call .copy() reflexively.

For files larger than memory, process chunks with overlap. Each chunk needs the last slow - 1 rows of the previous chunk to warm up the indicators, plus the carried-over last position and last equity value. Inside numba, prefer plain numpy arrays and preallocated outputs.

Metrics come straight from the output columns. Max drawdown is (equity / equity.cummax() - 1).min(). Trade count is (position.diff().abs() > 0).sum() for position changes, or (position.diff() > 0).sum() for entries. Annualize with the number of bars per year for your market, for example 252 * 390 for regular US equity session minute bars or 365 * 24 * 60 for round-the-clock markets. The Sharpe ratio and drawdown guides on this site cover those calculations in detail.

Common questions

Is vectorized or event-driven backtesting more accurate?

Neither is inherently more accurate; they model different things. Vectorized code is exact for rule-based signals with simple fills and costs, while event-driven engines can model order types, partial fills, margin and latency. Choose by the realism your logic needs, then verify the vectorized version against a loop.

Why does my vectorized equity differ slightly from the loop version?

Tiny differences around 1e-12 come from floating point order of operations, which is why you compare with np.allclose rather than ==. Larger differences usually mean a convention mismatch: shift direction, first-row cost handling, simple versus log returns, or NaN warm-up rows treated differently.

Can I use log returns in a vectorized backtest?

Yes, if you stay consistent: strategy log return is position * np.log(close).diff(), and equity is np.exp(cumsum). Subtract costs as log(1 - cost) or approximate them in log space, and convert to simple returns before weighting across assets.

Does shift(1) remove all look-ahead bias?

No, it only removes the same-bar mistake. Whole-sample normalization, centered rolling windows, shift(-1) features, survivorship-biased universes and resampled bars labeled at their close can still leak future information. The truncation test is the most general check you can automate.

Related topics:backtestingpandaspythonvectorizationnumba