Backtest Different Results Each Run: Find and Fix the Cause
A backtest that gives different results each run depends on something that changes between runs: an unseeded RNG, hash-randomized ordering, parallel completion order, moving data, floating-point summation order, or the clock. Bisect the trade logs to find which.
- Run the backtest twice in one process and twice in fresh processes, then diff the trade logs. The first diverging row tells you which cause you have.
- Give every component its own seed through numpy SeedSequence.spawn, and key parallel results by job ID instead of completion order.
- Set PYTHONHASHSEED, sort every symbol, file and key list, and break ties with an explicit secondary key.
- Freeze data as a hashed Parquet snapshot with a fixed end date, and pin library versions with a lock file or image digest.
- Prove reproducibility with a run manifest and a SHA-256 of a canonicalized trade log, checked against a golden hash in CI. A fixed seed makes a run repeatable, not valid.
How do I find why my backtest gives different results each run?
Bisect before you fix anything. Run the same config twice inside one process, then twice in fresh processes, and write the trade log of each run to disk. Then find the first row where two logs differ, not just the final PnL.
The first diverging row is the clue. If it is the first trade, suspect data or config. If it is mid-run, suspect an RNG draw, an ordering tie, or a bar that arrived late.
Which runs differ narrows the cause further. Use the table as a decision tree.
| Observation | Likely cause | First fix |
|---|---|---|
| Two runs in the same process differ | Global RNG state advances between runs, or mutable state is reused (cached indicators, a reused broker object) | Build fresh RNGs and objects per run, pass seeds explicitly |
| Same process matches, fresh processes differ | Unseeded RNG, PYTHONHASHSEED set ordering, changing data, datetime.now() | Seed everything, set PYTHONHASHSEED=0, snapshot data |
| Differs only with multiprocessing or threads | Completion-order collection, shared RNG, race on 'best so far' | Sort by job ID, per-job seeds, reduce after collecting |
| Trades identical, metrics differ in the 12th digit | Floating-point summation order, BLAS threads, float32 | Compare metrics with a tolerance, pin thread counts |
| Differs between machines only | CPU instruction set, BLAS build, library versions, OS locale or timezone | Lock file, Docker image digest, explicit timezone |
| Differs day to day, never within a day | Data revisions, an end date of today, an incomplete last bar | Pinned snapshot with a fixed end date |
import pandas as pd
def first_divergence(a: pd.DataFrame, b: pd.DataFrame):
n = min(len(a), len(b))
for i in range(n):
if not a.iloc[i].equals(b.iloc[i]):
return i, a.iloc[i].to_dict(), b.iloc[i].to_dict()
return (n, None, None) if len(a) != len(b) else None
# run_backtest(cfg) -> trades DataFrame
# python run.py > run1.csv ; python run.py > run2.csv (fresh processes)
# then: first_divergence(pd.read_csv('run1.csv'), pd.read_csv('run2.csv')) Why do seeds not fix it? Unseeded and mis-seeded random generators
Randomness hides in slippage models, Monte Carlo and bootstrap resampling, parameter samplers, and ML models. Each needs its own seed. Python's random.seed does not touch NumPy, and np.random.seed does not touch generators created with np.random.default_rng().
Prefer one explicit Generator per component over global state. For parallel workers, spawn child seeds from one SeedSequence so streams are independent and fixed by job index, not by which worker picked the job up.
ML libraries have their own switches: torch.manual_seed (plus torch.use_deterministic_algorithms(True) on GPU), sklearn random_state=, xgboost and lightgbm seed= (and a fixed thread count, because histogram sums are order-sensitive), and optuna.samplers.TPESampler(seed=...).
import os, random
import numpy as np
def seed_everything(seed: int) -> None:
# legacy global state, for libraries that still use it
random.seed(seed)
np.random.seed(seed)
# affects only child processes started after this point
os.environ["PYTHONHASHSEED"] = str(seed)
def component_rngs(seed: int, names: list[str]) -> dict:
children = np.random.SeedSequence(seed).spawn(len(names))
return {n: np.random.default_rng(c) for n, c in zip(names, children)}
rngs = component_rngs(42, ["slippage", "bootstrap", "sampler"])
slip = rngs["slippage"].normal(0, 0.0002, size=1000)
# parallel jobs: one child seed per job ID, fixed before dispatch
job_seeds = np.random.SeedSequence(42).spawn(len(param_grid))
# worker(job_id, params) builds np.random.default_rng(job_seeds[job_id])How does ordering and parallel optimization change results?
String hashes are randomized per process, so iterating a set of symbols gives a different order each launch. Dicts keep insertion order, but the insertion order may itself come from a set, glob.glob, os.listdir, or a SQL query without ORDER BY. Wrap all of these in sorted().
Ties are the second ordering trap. If you rank symbols by score and two have equal scores, a sort that is not stable, or a sort over a set, picks arbitrarily. Always add a secondary key such as the symbol: sort_values(['score','symbol'], ascending=[False, True], kind='mergesort').
Parallel optimization adds completion order. as_completed and imap_unordered return results as workers finish, so 'keep the best so far' with a strict greater-than comparison picks different winners when two parameter sets tie. Collect everything, sort by job ID, then pick the maximum with an explicit tie-break.
Also check shared state. A module-level RNG copied into forked workers makes every worker draw the same numbers. Under the spawn start method, workers re-import the module and a seed set only in the main script is lost.
from concurrent.futures import ProcessPoolExecutor
import numpy as np, pandas as pd
def run_job(args):
job_id, params, seed_seq = args
rng = np.random.default_rng(seed_seq) # seeded inside the worker
return {"job_id": job_id, **params, "sharpe": evaluate(params, rng)}
seeds = np.random.SeedSequence(42).spawn(len(grid))
jobs = [(i, p, seeds[i]) for i, p in enumerate(grid)]
with ProcessPoolExecutor(max_workers=8) as ex:
rows = list(ex.map(run_job, jobs)) # map keeps input order
res = pd.DataFrame(rows).sort_values("job_id")
best = res.sort_values(["sharpe", "job_id"], ascending=[False, True]).iloc[0] Why do my backtest results change when the data hasn't been touched?
Often the data did change. Free APIs such as yfinance return adjusted prices that are rewritten after every split or dividend, vendors correct bad prints, and a range ending at 'today' includes a partial current bar that differs by the minute you download it.
Download once, freeze, and read only the frozen file. Use an explicit end date, drop any bar not yet closed, and store a manifest next to the file so you can show where it came from.
Time handling leaks in the same way. datetime.now(), date.today(), timezone-naive timestamps, and DST transitions all make a run depend on when and where it executes. Store UTC, convert with named zones (America/New_York), and pass an as_of date through the config. Watch parameter defaults derived from data length, such as 'use the last 20% as test'. They shift every time a bar is appended.
import hashlib, json, datetime as dt
import pandas as pd
def sha256_file(path, chunk=1 << 20):
h = hashlib.sha256()
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
def snapshot(df: pd.DataFrame, path: str, source: str, query: dict, end: str):
df = df.loc[:end].sort_index() # fixed end date, no live bar
df.to_parquet(path)
manifest = {
"source": source, "query": query, "end": end,
"downloaded_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"rows": len(df), "sha256": sha256_file(path),
}
json.dump(manifest, open(path + ".manifest.json", "w"), indent=2)
return manifestIs bit-exact reproducibility realistic, or should I use a tolerance?
Floating-point addition is not associative, so (a + b) + c can differ from a + (b + c) in the last bits. Parallel reductions, BLAS with different thread counts, float32 versus float64, different CPU instruction sets (AVX2 versus AVX-512 kernels), and Numba's fastmath=True or parallel=True all change summation order.
For bit-exact output, pin threads before importing NumPy: OMP_NUM_THREADS=1, MKL_NUM_THREADS=1, OPENBLAS_NUM_THREADS=1. Use float64 throughout, avoid fastmath, and run on the same image and CPU family.
Be pragmatic about the rest. Hash the trade log exactly, since trades are decisions, and compare aggregate metrics such as Sharpe or drawdown with np.isclose(a, b, rtol=1e-9). If the log is identical but the metric differs at 1e-12, that is summation order. If the trade log differs, it is a real divergence.
The dangerous case is float equality inside signals. A condition like price == level or a threshold hit exactly on a boundary flips with a one-ulp difference and changes a trade. Round prices to tick size (round(price / tick) * tick) and use explicit inequalities with a tolerance.
export PYTHONHASHSEED=0
export OMP_NUM_THREADS=1 MKL_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1
export NUMEXPR_NUM_THREADS=1 NUMBA_NUM_THREADS=1
python run.py --config configs/base.yaml Where does randomness enter backtrader and vectorbt, and how do I pin the environment?
Neither framework is random by default. Randomness comes from your code, a random-signal generator, or a broker model you configured. Parallelism and library versions are the usual framework-level causes.
Version drift is real: a pandas upgrade can change NaN handling in rolling windows, groupby ordering or default arguments, and a backtrader or numpy release can alter rounding or indicator warm-up. Record versions in every run, and pin them with a lock file (uv.lock, poetry.lock, or pip-compile --generate-hashes). Also record the Python version, and for full control build from a Docker image referenced by digest (image@sha256:...), not by a mutable tag.
| Framework / setting | Where non-determinism enters | Safe setting |
|---|---|---|
| backtrader cerebro.run(maxcpus=N) | Optimization forks processes; results arrive per strategy instance, so position-based matching and shared module state break | maxcpus=1 to debug, then key results by parameter values |
| backtrader optreturn, optdatas | optreturn=True strips results to lightweight objects, so you may lose analyzers you expected; optdatas shares preloaded data across workers | Keep optdatas=True with preload=True, and read analyzers explicitly |
| backtrader preload / runonce | Different code paths (vectorized vs bar-by-bar) can give slightly different indicator values and live-bar behavior | Fix both explicitly, and do not compare runs across settings |
| backtrader broker slippage and fills | slip_perc and slip_fixed are deterministic; custom fillers or slippage code using random are not | Seed your own Generator, injected into the broker class |
| vectorbt random signal generators | Random entries and exits draw from NumPy state unless a seed argument is passed | Pass seed= on each call |
| Numba parallel=True, fastmath=True, prange | Chunk scheduling and reordered arithmetic change reduction order | Disable both for exact reproducibility, or compare metrics with a tolerance |
How do I prove a run is reproducible? Manifest, result hash and CI check
Reproducibility you cannot verify is a belief. Write a manifest for every run, hash a canonical form of the trade log, and fail CI when the hash moves unexpectedly.
Canonicalizing means a fixed row order (stable sort on explicit keys), a fixed column order, floats rounded to about 10 decimals, negative zero normalized, and one fixed serialization. Without this, harmless reordering changes the hash.
- Write the manifest at the start of the run and update it with the end time and result hash at the end.
- Canonicalize the trade log and compute its SHA-256.
- Commit the hash for a small fixed fixture dataset as a golden value.
- Run the pytest below in CI inside the pinned image. If it fails, diff the logs with first_divergence before updating the golden value.
import hashlib, json, subprocess, platform, datetime as dt
from importlib import metadata
from pathlib import Path
import pandas as pd
def canonical_hash(trades: pd.DataFrame, keys=("entry_time", "symbol", "side"), decimals=10) -> str:
df = trades.sort_values(list(keys), kind="mergesort").reset_index(drop=True)
df = df[sorted(df.columns)]
num = df.select_dtypes("number").columns
df[num] = df[num].astype("float64").round(decimals) + 0.0 # +0.0 turns -0.0 into 0.0
csv = df.to_csv(index=False, lineterminator="\n", float_format="%.10f")
return hashlib.sha256(csv.encode()).hexdigest()
def write_manifest(path, cfg, seed, data_hashes, result_hash=None, started=None):
pkgs = ["numpy", "pandas", "backtrader", "numba"]
ver = {}
for p in pkgs:
try: ver[p] = metadata.version(p)
except metadata.PackageNotFoundError: pass
manifest = {
"config": cfg, "seed": seed, "data_sha256": data_hashes,
"git_sha": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
"python": platform.python_version(), "os": platform.platform(),
"cpu": platform.processor() or platform.machine(), "libs": ver,
"started_utc": started, "finished_utc": dt.datetime.now(dt.timezone.utc).isoformat(),
"result_sha256": result_hash,
}
Path(path).write_text(json.dumps(manifest, indent=2, sort_keys=True))
# tests/test_golden.py
GOLDEN = Path("tests/golden_hash.txt").read_text().strip()
def test_trade_log_hash_is_stable():
trades = run_backtest(load_config("tests/fixture.yaml"))
assert canonical_hash(trades) == GOLDEN
def test_same_process_twice():
cfg = load_config("tests/fixture.yaml")
assert canonical_hash(run_backtest(cfg)) == canonical_hash(run_backtest(cfg))Common questions
How do I set a random seed for numpy and pandas in a backtest?
Pandas has no seed of its own. It uses NumPy, and sample() takes random_state=. Create rng = np.random.default_rng(seed) and pass it explicitly, for example df.sample(frac=0.5, random_state=rng). Also call np.random.seed(seed) only if a library you use still reads global state.
Why does my parameter optimization pick a different best result each run?
Usually two parameter sets tie or score within noise, and the winner depends on which worker finished first. Collect all results, sort by job ID, and select the best with an explicit tie-break such as higher score then lower job ID. Also confirm each job gets its own seed from SeedSequence.spawn.
Does a different CPU or machine change backtest results?
It can. BLAS and MKL choose different kernels per instruction set and thread count, so sums can differ in the last bits. Pin the thread variables, use the same container image, and compare metrics with a tolerance while keeping the exact hash for the trade log.
Will setting PYTHONHASHSEED be enough to make runs identical?
No. It only fixes the order of iterating sets and dicts keyed by hash-randomized types such as strings. It does nothing for RNGs, data revisions, thread scheduling or floating-point order, so treat it as one fix among several.
How different is too different when comparing two runs?
If the trade logs differ at all, treat it as a real divergence and find the first differing row. If trades match and metrics differ below roughly rtol=1e-9, that is float rounding. Anything larger with identical trades points to a bug in metric code, such as an unsorted index or a changed annualization input.