Skip to content
LeetQuant
QR01 Python for Quantitative Research

QR01 · Python for Quantitative Research · Lesson 5 of 5

Reproducible Research Workflows

Seeding with numpy's Generator and SeedSequence, pinning environments, sources of hidden nondeterminism, separating data, code and results, notebooks versus modules, and tests that catch look-ahead.

16 min

Objective

A result is reproducible if someone else (including you in six months) can regenerate it from the raw data with one command and get the same numbers. In a research team this is what separates a finding from an anecdote: when a backtest's Sharpe ratio changes, you need to know whether the code, the data, the environment or the random draws changed. This lesson lists the concrete mechanisms that break reproducibility and the habits that prevent each.

Random numbers: the Generator API

Create a generator from a seed and pass it explicitly to every function that draws randomness:

import numpy as np

rng = np.random.default_rng(2024)
print(rng.standard_normal(3).round(4))      # [1.0289 1.6419 1.1467]
rng = np.random.default_rng(2024)
print(rng.standard_normal(3).round(4))      # [1.0289 1.6419 1.1467]  same seed, same draws

def simulate(n, rng):
    return rng.standard_normal(n).mean()

Avoid the legacy global state (np.random.seed(0) then np.random.rand()): any library call that also draws from the global generator shifts every later number, so adding a print statement or an unrelated import can change your results. With an explicit rng argument, the randomness a function uses is visible in its signature.

For parallel work, do not seed workers with seed + i (nearby seeds are fine for the default PCG64 generator in practice, but the pattern invites collisions when two experiments overlap). Use SeedSequence.spawn, which derives statistically independent child streams from one root seed:

children = np.random.SeedSequence(2024).spawn(3)
streams = [np.random.default_rng(c) for c in children]
print([round(float(g.standard_normal()), 4) for g in streams])   # [-0.2117, 2.214, -0.4319]

Two caveats. A seed fixes draws only for a given NumPy version and method: NumPy keeps its bit generators stable but does not promise identical output from every distribution method across releases, which is one more reason to pin versions. And a seed is a tool for reproducibility, not for choosing results: report the distribution across seeds, never the best seed.

Worked example

a parallel Monte Carlo that gives the same answer every run

Price the at-the-money one-year call with σ=0.2\sigma = 0.2, r=0r = 0 and spot 100 by Monte Carlo across 4 worker processes, 8 batches of 200,000 paths each, so that the answer does not depend on how batches are scheduled.

Show solution

Give each batch (not each worker) its own child seed. Then the result depends only on the root seed and the number of batches, not on which process ran which batch or in what order.

import numpy as np
from concurrent.futures import ProcessPoolExecutor

def price_batch(seed_seq, n=200_000):
    rng = np.random.default_rng(seed_seq)
    z = rng.standard_normal(n)
    payoff = np.maximum(100 * np.exp(-0.02 + 0.2 * z) - 100, 0.0)
    return payoff.mean()

if __name__ == "__main__":
    children = np.random.SeedSequence(12345).spawn(8)
    with ProcessPoolExecutor(max_workers=4) as pool:
        batch_means = list(pool.map(price_batch, children))
    print(round(float(np.mean(batch_means)), 4))          # 7.9645
    serial = [price_batch(c) for c in np.random.SeedSequence(12345).spawn(8)]
    print(round(float(np.mean(serial)), 4))               # 7.9645

The parallel and serial runs agree exactly. The Black–Scholes value is 100 (2Φ(0.1)−1)=7.9656100\,(2\Phi(0.1) - 1) = 7.9656, and the estimate is within one standard error (about 13/1.6×106≈0.0113/\sqrt{1.6 \times 10^6} \approx 0.01).

Two details make this deterministic. pool.map returns results in input order regardless of completion order, and the final average is over a fixed-order list. If you instead accumulated results as they completed, the floating-point sum order would vary between runs and the last digits would change, which is harmless numerically but makes exact regression tests fail mysteriously.

Hidden nondeterminism and the environment

Seeds cover only explicit randomness. Other sources:

  • Hash randomisation. Python randomises string hashing per process, so iterating over a set of strings gives a different order in each run. With PYTHONHASHSEED set to 1, 2 and 3, list({"AAPL", "MSFT", "GOOG", "AMZN"}) printed three different orders. Anything order-dependent built from a set (column order, which ticker wins a tie, floating-point sums) then varies. Use sorted(...).
  • File listing order. os.listdir and glob return files in filesystem order, which differs across machines. Sort them.
  • Parallel and BLAS reductions. Multithreaded sums and matrix products can change summation order with the thread count, changing the last bits. Compare results with tolerances, and pin thread counts (OMP_NUM_THREADS) when bitwise reproducibility matters.
  • Wall-clock and live data. datetime.now(), "the last 252 days" and an API that returns the latest vintage of revised data all change silently. Pass the as-of date as a parameter and snapshot the data.
  • Library versions. Default arguments change (pandas 3 changed pct_change filling and made Copy-on-Write the default). Pin exact versions in a lock file (uv lock, pip-compile, pip freeze > requirements.txt, or a conda environment file), record the Python version, and rebuild the environment from the lock file rather than from memory.

Separate data, code and results

A layout that scales from one notebook to a team:

  • data/raw/: immutable inputs exactly as received, never edited by hand, with source and download date recorded.
  • data/derived/: produced only by code from raw data, so it can be deleted and rebuilt.
  • src/: importable modules with the logic (signals, backtester, statistics).
  • configs/: parameters for each experiment (universe, dates, windows, seed) as files, not as edits to code.
  • results/<run-id>/: outputs written together with the config used, the git commit hash, and the environment lock, so every number traces back to the exact code and inputs.

Notebooks versus modules. Notebooks are excellent for exploration and presentation, and poor as the system of record: cells can run out of order, deleted cells leave state in memory, and diffs are unreadable. Move any function you rely on into a module, import it into the notebook, and make sure the notebook passes "restart kernel and run all" before a result is shared.

Testing research code

Research code is rarely wrong in a way that crashes; it is wrong in a way that produces a plausible number. Tests that catch that:

  • Known answers. Check a Monte Carlo pricer against Black–Scholes within a few standard errors; a regression routine against a hand-computed two-point case; a drawdown function on a five-price path.
  • Invariances. A z-score signal should not change if prices are multiplied by a constant; a portfolio's weights should not change if the asset order is permuted (after permuting back). Compare with np.testing.assert_allclose, not ==: scaling prices by 3.7 changed the z-score signal by up to 1.3×10−121.3 \times 10^{-12}, so equals returned False though the code is correct.
  • Causality. Perturb the future and assert that the past does not move (next example). This single test catches center=True, bfill, full-sample normalisation and most alignment bugs.
  • Regression tests. Store the key output of a reference run and assert that later runs match within a tolerance, so refactoring cannot silently change results.

Worked example

a test that catches look-ahead

Write a test that fails for any signal function whose value at time tt depends on prices after tt. Apply it to a correct 20-day z-score and to a buggy version using rolling(..., center=True) and bfill().

Show solution

The defining property of a causal signal: changing prices after a cutoff leaves every signal value up to the cutoff unchanged. So scramble the future and compare.

import numpy as np
import pandas as pd

def zscore_signal(price, window=20):
    m = price.rolling(window).mean()
    s = price.rolling(window).std()
    return (price - m) / s

def zscore_signal_buggy(price, window=20):
    m = price.rolling(window, center=True).mean()   # looks 10 days ahead
    s = price.rolling(window).std()
    return ((price - m) / s).bfill()                # and back-fills from the future

def check_no_lookahead(signal_fn, price, cutoff, seed=0):
    """Scramble everything after cutoff; the signal up to cutoff must not move."""
    rng = np.random.default_rng(seed)
    perturbed = price.copy()
    perturbed.iloc[cutoff + 1:] *= np.exp(rng.normal(0, 0.05, len(price) - cutoff - 1))
    a = signal_fn(price).iloc[: cutoff + 1]
    b = signal_fn(perturbed).iloc[: cutoff + 1]
    return a.equals(b)

rng = np.random.default_rng(42)
idx = pd.bdate_range("2023-01-02", periods=300)
price = pd.Series(100 * np.exp(np.cumsum(rng.normal(0, 0.01, 300))), index=idx)

print(check_no_lookahead(zscore_signal, price, cutoff=150))         # True
print(check_no_lookahead(zscore_signal_buggy, price, cutoff=150))   # False

Here exact equality is the right comparison: a causal function performs identical arithmetic on identical inputs for every row up to the cutoff, so the outputs must be bit-for-bit equal (Series.equals treats NaN in matching positions as equal, which handles the warm-up rows). The buggy version fails because the centred 20-day mean at row ii uses rows i−10i - 10 to i+9i + 9, so rows 142 to 150 already depend on prices after the cutoff.

In a test suite, run it over several cutoffs (including near the start, where bfill leaks) and several seeds, and apply it to every signal function in the library, not just new ones.

Knowledge check

Your script calls np.random.seed(0) at the top, then later imports a library that draws a few numbers from np.random during import. What happens to your results?

Knowledge check

A backtest builds its universe with tickers = set(df['ticker']) and iterates over it to accumulate PnL. Re-running the same code on the same data gives totals that differ in the 15th significant digit. Most likely cause?

Knowledge check

Which test would detect a signal that was normalised with full-sample mean and standard deviation?

Key takeaways

  • Use np.random.default_rng(seed) and pass the generator explicitly; use SeedSequence.spawn for parallel streams, one per task, not per worker.
  • Hidden nondeterminism: set order under hash randomisation, file listing order, parallel reduction order, wall-clock dates and unpinned library versions.
  • Pin the environment with a lock file and record the commit hash and config with every result.
  • Raw data is immutable, derived data is rebuildable, logic lives in modules, and notebooks must pass "restart and run all".
  • Test with known answers, invariances (with tolerances) and a perturb-the-future causality test.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).