Speed Up a Python Backtest: Profile, Vectorize, Numba
To speed up a Python backtest, profile first, then move data out of pandas row access into numpy arrays, vectorize the signals, and put path-dependent logic like stops into a numba loop. Check each step against a slow reference.
- Profile with cProfile and line_profiler before changing code, because the bottleneck is usually df.iloc, iterrows or per-bar indicator rebuilds, not the strategy math.
- Converting columns to numpy arrays once and looping over them removes most of the pandas overhead with almost no change to the logic.
- Signals (moving averages, crossovers) vectorize cleanly; stops, cash limits and partial fills depend on earlier state and belong in a numba @njit loop.
- A hybrid of vectorized signals plus a numba execution loop is the usual fast design, and a prefix-causality test catches lookahead the speedup might introduce.
- Parameter sweeps get their biggest gains from computing shared indicators once and parallelising over parameters with prange or joblib, chunked to fit memory.
How do I find out why my Python backtest is slow?
Measure before rewriting. Run the whole script under cProfile, sort by cumulative time, and look at which pandas calls dominate. Most slow event-loop backtests spend 80 to 95 percent of their time in a handful of lines that touch the DataFrame, not in the trading logic.
Use time.perf_counter around stages (load, indicators, loop, metrics) for a coarse split, then line_profiler on the loop function for line-level cost.
| Symptom in the profile | Likely cause | Fix |
|---|---|---|
| Time in iterrows, Series.__getitem__, _get_value | Row-wise access builds a Series or does label lookup per bar | Loop over numpy arrays or itertuples |
| Time in iloc/loc/at inside the loop | Per-access overhead of 5 to 50 microseconds | Pull columns out with to_numpy() once |
| rolling/ewm called thousands of times | Indicators rebuilt every bar or every parameter | Compute once outside the loop, slice per parameter |
| concat/append/DataFrame constructor in the loop | Copying the whole frame on each bar | Preallocate numpy arrays, build the DataFrame at the end |
| Object-dtype columns, string comparisons | Python objects instead of float64 | Cast to float64, encode sides as int8 |
# whole-program profile, then browse it
python -m cProfile -o prof.out run_backtest.py
python -c "import pstats; pstats.Stats('prof.out').sort_stats('cumulative').print_stats(15)"
snakeviz prof.out
# line-level: decorate the loop function with @profile
kernprof -l -v run_backtest.pyWhy is row-wise pandas so slow?
Every df.iloc[i, j] or df.loc[ts, 'close'] goes through indexing machinery: key validation, block lookup, and boxing the result into a Python object. That costs microseconds to tens of microseconds per access. A numpy array element read costs tens of nanoseconds, so the gap is two to three orders of magnitude.
iterrows is worse: it constructs a new Series for each row, and mixed dtypes get upcast to object. itertuples avoids the Series and is a good interim fix, but it is still a Python-level loop creating a namedtuple per row.
The cheap wins, in order: convert columns once with df['close'].to_numpy(dtype='float64'); loop over arrays with plain indexing or zip; preallocate arrays such as equity = np.empty(n) instead of appending; and remove object dtype so numpy and numba can use the data at all.
How much can I speed up a Python backtest on a real strategy?
The test case is a moving-average crossover (fast above slow means long) with a fixed percentage stop-loss, and no re-entry after a stop until the signal resets. The figures below are representative orders of magnitude for about 1 million bars on a recent laptop CPU. Your numbers will differ, so time your own stages.
Each row keeps the same logic. Only the data access and loop mechanics change.
| Stage | Approach | Representative runtime (1M bars) | Main limit |
|---|---|---|---|
| 0 | iterrows with iloc lookups | tens of seconds to minutes | Series per row |
| 1 | itertuples | a few seconds | Python loop, namedtuples |
| 2 | Loop over numpy arrays | about 0.3 to 1 s | Python interpreter speed |
| 3 | Fully vectorized (no stop) | tens of milliseconds | Cannot express the stop |
| 4 | Vectorized signal + numba loop | single-digit to low tens of milliseconds after compile | One-time compile, roughly 1 to 3 s |
import numpy as np, pandas as pd
from numba import njit
@njit(cache=True)
def positions(close, sig, stop):
n = len(close)
pos = np.zeros(n, dtype=np.int8)
held = 0
entry = 0.0
blocked = False
for i in range(n):
if sig[i] == 0:
blocked = False
if held == 1:
if sig[i] == 0:
held = 0
elif close[i] < entry * (1.0 - stop):
held = 0
blocked = True
elif sig[i] == 1 and not blocked:
held = 1
entry = close[i]
pos[i] = held # decided at close of bar i
return pos
def run(df, fast, slow, stop, fee=0.0005):
close = df['close'].to_numpy(dtype='float64')
f = df['close'].rolling(fast).mean().to_numpy()
s = df['close'].rolling(slow).mean().to_numpy()
sig = (f > s).astype(np.int8) # NaN compares False
pos = positions(close, sig, stop)
ret = np.zeros_like(close)
ret[1:] = close[1:] / close[:-1] - 1.0
held = np.zeros_like(ret)
held[1:] = pos[:-1] # trade on next bar
turnover = np.abs(np.diff(pos, prepend=0))
net = held * ret - np.r_[0.0, turnover[:-1]] * fee
return np.cumprod(1.0 + net), posHow do I vectorize a backtest without introducing lookahead?
Vectorize whatever depends only on past prices: rolling means, EMAs (ewm(span=n, adjust=False)), ATR, comparisons and crossovers. Booleans from comparisons replace the if statements, and a crossover is just (fast > slow) & (fast.shift(1) <= slow.shift(1)).
The key correctness rule is that a signal computed from bar t's close can only earn bar t+1's return. In pandas that is position = signal.shift(1), or signal.shift(1).ffill() when the signal is only defined on event bars. Then returns = position * close.pct_change(). Costs are position.diff().abs() * fee, charged on the bar the position changes.
Equity and drawdown stay vectorized: equity = (1 + returns).cumprod(); drawdown = equity / equity.cummax() - 1.
Lookahead usually enters through three doors: a missing shift(1), rolling(..., center=True), and resampled bars labelled with the period start (use label='right', closed='right' for bar-close data, and never forward-fill a higher timeframe onto lower bars before it has closed).
fast = close.rolling(20).mean()
slow = close.rolling(50).mean()
signal = (fast > slow).astype(int)
position = signal.shift(1).fillna(0) # fill on next bar
ret = position * close.pct_change().fillna(0)
cost = position.diff().abs().fillna(0) * 0.0005
equity = (1 + ret - cost).cumprod()
drawdown = equity / equity.cummax() - 1 When is vectorization the wrong tool?
Vectorization works when each bar's output is a function of inputs that do not depend on your own earlier decisions. It fails when state carries forward: a stop that depends on entry price, sizing that depends on current cash, margin calls, portfolio caps, limit orders and partial fills.
The practical design is a hybrid: vectorize the signals, then run one numba loop over arrays for execution. Use a full event-driven engine only when you need to share code with live trading or model order books and many instruments interacting.
Does bar t's position depend on your own earlier fills,
entry price, cash, margin or open orders?
|
+-- No -> Fully vectorize: shift(1), cumprod, cummax.
|
+-- Yes -> Is the state per instrument and simple (stop, trail, size)?
|
+-- Yes -> Vectorize signals, numba loop for execution.
|
+-- No (cross-asset cash, partial fills, limit queues)
-> Numba or compiled event loop over arrays;
full event-driven engine if live parity matters.How do I speed up parameter sweeps and keep memory under control?
Sweeps multiply everything, so compute shared pieces once. A rolling mean depends only on the window, not on the stop or the other leg. Build a dict of moving averages per unique window and reuse it across the grid, rather than recomputing inside each combination.
A cumsum rolling mean is fast and allocation-light. It can lose precision on long series with large values, so keep float64 or subtract the series mean first. numpy's sliding_window_view gives rolling min, max or std without a loop, but it makes a strided view, so reductions can still allocate large temporaries.
For parallelism, numba's prange over the parameter axis (with parallel=True) is the lowest overhead. joblib or multiprocessing suit pandas-heavy code but copy data to each worker, so use memory-mapped arrays or load from Parquet in the worker.
Broadcasting a 2D parameter-by-time array is fast but costly: 200 windows by 5 million bars of float64 is 8 GB. Process the grid in chunks of parameters, and keep only summary statistics per combination instead of storing every equity curve.
For data volume, read only needed columns from Parquet, use float32 for features where precision allows (accumulate equity in float64), avoid df.copy(), and pre-aggregate ticks or 1-second data into bars before the sweep.
def sma(x, w):
c = np.cumsum(np.insert(x, 0, 0.0))
out = np.full(len(x), np.nan)
out[w-1:] = (c[w:] - c[:-w]) / w
return out
ma = {w: sma(close, w) for w in set(fasts) | set(slows)} # once
for f in fasts:
for s in slows:
if f < s:
sig = (ma[f] > ma[s]).astype(np.int8)
pos = positions(close, sig, stop) How do I prove the fast backtest matches the slow one?
Keep the slow loop as a reference and test the fast one against it on a small sample, so a speedup never silently changes results. Compare trade counts and equity curves, not just the final number, because compensating errors can hide in a total.
Add a causality test as well: positions computed on a truncated prefix must equal the same prefix of positions from the full run. If any bar's position changes when future data is removed, the code looks ahead.
def reference(df, fast, slow, stop, fee):
c = df['close'].to_numpy(); n = len(c)
pos = [0]*n; held = False; entry = 0.0; blocked = False
f = df['close'].rolling(fast).mean().to_numpy()
s = df['close'].rolling(slow).mean().to_numpy()
for i in range(n):
on = (f[i] > s[i]) # False for NaN
if not on: blocked = False
if held:
if not on: held = False
elif c[i] < entry*(1-stop): held = False; blocked = True
elif on and not blocked:
held = True; entry = c[i]
pos[i] = int(held)
return np.array(pos)
sample = df.iloc[:5000]
slow_pos = reference(sample, 20, 50, 0.02, 0.0005)
eq, fast_pos = run(sample, 20, 50, 0.02)
assert np.array_equal(slow_pos, fast_pos)
assert np.abs(np.diff(fast_pos)).sum() == np.abs(np.diff(slow_pos)).sum()
# lookahead check: prefix of full run == run on prefix
_, full = run(df, 20, 50, 0.02)
_, pref = run(df.iloc[:3000], 20, 50, 0.02)
assert np.array_equal(full[:3000], pref)Common questions
Is itertuples fast enough for a backtest?
It is typically one to two orders of magnitude faster than iterrows, which is enough for a single daily-bar run. It is still a Python loop creating a namedtuple per row, so for intraday data or sweeps, loop over numpy arrays and move to numba.
Why do my vectorized results differ from my loop results?
The usual causes are a missing shift(1) so trades fill on the same bar, different NaN handling in warm-up periods, and stop or fill rules that were silently dropped because they could not be expressed in vector form. Compare the position arrays bar by bar and inspect the first index where they diverge.
Does float32 make a backtest faster?
It halves memory and can help cache use on large 2D arrays, but the gain is modest compared with removing pandas access or compiling the loop. Keep equity and cumulative products in float64, because float32 accumulates visible rounding error over millions of bars.
Should I use prange, joblib or multiprocessing for sweeps?
Use numba prange when the whole simulation is already an njit function over numpy arrays, since threads share memory and have no pickling cost. Use joblib or multiprocessing when each task involves pandas or non-numba code, and load data per worker instead of sending large frames.
Why is the first numba call so slow?
Numba compiles the function the first time it sees a given set of argument types, which can take seconds. Use cache=True to persist the compiled code, keep dtypes consistent, and exclude the first call from timings.