A reproducible backtest is one that another run can reconstruct from its saved inputs, not merely one that produces an attractive equity chart. You need to know which code ran, which parameter values it used, what data it saw, how orders were filled and which costs were charged. If any of those are ambiguous, a later report can disagree without either screen explaining why.

The practical goal is a traceable chain from source data to signals, fills, trades, equity and summary metrics. This article follows that chain with a small worked example. It also explains how input settings such as A, B and C can keep experiments understandable without treating every analysis phase as a new strategy.

Separate code from its input values

The code defines the trading logic. Inputs choose values within that logic, such as a lookback length, threshold or permission to short. Changing lookback from 20 to 25 need not create a new code version, but it does create a distinct parameter setting. Changing the entry formula itself requires a new code version even when the input names remain identical.

For example, setting A might be lookback 20 and threshold 0.15. Setting B might use 25 and 0.15. Setting C might use 25 and 0.20. A compact letter makes the settings easy to select. Their identity still needs the exact typed values and code version. The letter is a label, not the mathematical definition of the strategy.

A report belongs to its precise setting. Validation of B adds evidence about B on another period. It does not become an unrelated candidate whose parameters must be guessed later. If an input changes, generate or reuse the correctly matching setting rather than attaching B's previous profits to the new values.

Record the whole calculation context

Matching inputs alone is insufficient for reuse. Instrument, bar interval, date boundaries, contract mapping, data version, capital, execution model and costs can all change a result. A run over January through March is not interchangeable with a run over January through May, even if both use setting B.

Use explicit period conventions. An interval starting January 1 and ending April 1 can be represented as start-inclusive and end-exclusive, which avoids double-counting a timestamp shared with the next period. The important point is consistency. Store timezone-aware boundaries and define how trades crossing a boundary are handled.

Randomized procedures need their random seed and algorithm version. Deterministic backtests should not depend on unrelated application state, the last report opened or the order in which the user visited screens. If cached results are reused, their key should describe the calculation rather than a convenient display label.

Same code is not necessarily the same experiment

Code, data, parameters, execution and environment are separate input identities. A result is an output identity. Preserve both, so an unexpected difference can be traced to the domain that changed instead of being attributed to a mysterious engine error.

The minimum record needed for a meaningful comparison
IdentityWhat to retain
CodeExact strategy and runner bytes. Record dependency versions, not only a repository branch name.
DataSource/content version, symbol or dated contract, schema, resolution, timestamp meaning and period.
ParametersExact typed values. The number 20 and the string "20" are not automatically interchangeable.
ExecutionSignal availability, fill/exit timing, stop/target precedence, quantity, costs and slippage.
EnvironmentRuntime implementation/version and relevant libraries, platform or numerical settings.
ResultTrade ledger, declared equity convention, configuration and a fingerprint of the result artifact.

Pin actual data content, not only a filename. A provider may revise history. A query for the same root and dates may select a different contract set. A dependency upgrade may alter an indicator or serialization. A seed helps reproduce a specified randomized algorithm, but it does not freeze those other inputs or guarantee numerical agreement across runtimes.

Reproducibility is therefore a comparison contract: say which artifacts must match byte for byte, which quantities use a declared numerical tolerance, and which changes intentionally create a new experiment. This article’s small example uses exact decimal arithmetic and integer cents, so its economic artifacts have an exact known answer rather than a tolerance.

Make information availability explicit

A strategy cannot use a bar's final high, low or close before that bar has completed. If a signal is calculated from the close, define the earliest subsequent event at which an order may execute. Filling at the same close can be a legitimate convention only under an explicitly modeled order process, not an automatic assumption that a completed bar was known in advance.

Indicators need warm-up data. A 20-bar moving average cannot be computed from five observations without changing its definition. Load sufficient earlier history for calculation, then begin performance measurement at the intended boundary. Do not silently include warm-up trades in the measured sample.

External features have their own availability timestamps. A macro observation dated January may not be published until February and may be revised later. A weekly positioning report describes an earlier date than its release. Join such features according to when the strategy could know them, not simply their observation labels.

Run the three-trade example, rather than trusting its table

The ledger below now has an executable origin. Ten hand-written OHLC bars generate three trades using a tiny Python strategy. This is synthetic teaching data, not a market sample, a profitable-strategy claim, or the EdgeVeris production execution engine. Its deliberately simple model is small enough to inspect line by line.

At each completed close, compare it with the previous completed close. A rise targets one long contract, a fall targets two short contracts, and equality targets flat. The target becomes eligible at the next supplied bar open. The first close has no prior observation and remains flat.

def target_positions(bars, parameters):
    long_quantity = parameters["long_contracts"]
    short_quantity = parameters["short_contracts"]
    if type(long_quantity) is not int or type(short_quantity) is not int:
        raise ValueError("Contract quantities must be integers")
    if long_quantity < 1 or short_quantity < 1:
        raise ValueError("Contract quantities must be positive")
    targets = [0]
    for previous, current in zip(bars, bars[1:]):
        change = Decimal(current["close"]) - Decimal(previous["close"])
        targets.append(long_quantity if change > 0
                       else -short_quantity if change < 0 else 0)
    return targets

The downloadable file imports Decimal from Python’s standard library. The runner validates timestamps, OHLC relationships, tick alignment and whole-contract quantities. No third-party package, account, network access or random number generator is required.

Inspect all ten bars and their completed-close targets

All rows are on January 5, 2026, UTC. Timestamps label the start of one-minute bars. A target shown on the 09:01 row is acted on at the 09:02 open, not before the 09:01 bar closes.

Hand-written OHLC values, not exchange data
Bar start UTCOpenHighLowCloseTarget after close
09:00999999990
09:0199101991011
09:021001021001021
09:031031039999-2
09:041101109898-2
09:0510710798980
09:061061061011011
09:071051051021021
09:081031031021020
09:091021021021020

The execution model is part of the example

  • Period: 09:00 inclusive to 09:10 exclusive on January 5, 2026. All ten supplied bars are admitted. No exchange session calendar or contract roll is inferred.
  • Units: hypothetical USD contract, 0.25-point tick and $20 per point per contract. Parameters are long_contracts=1 and short_contracts=2.
  • Timing: next-open target changes. A reversal closes the old position and opens the opposite one at the same modeled reference open, with both sides charged.
  • Costs: $5 per contract on each entry or exit. Slippage is explicitly zero, an arithmetic convention rather than a claim of realistic fills.
  • Boundaries: no stops, targets, partial fills, queue simulation, margin liquidation or automatic forced close. The supplied fixture finishes flat. An open final position is rejected.
  • Equity: closed-trade net equity, booking each complete trade’s costs at its exit. It is not marked cash balance, bar-close equity or intratrade drawdown.

Download and run

Save these four files in the same folder: strategy.py, run_example.py, bars.csv and config.json. Use Python 3.10 or later. The plain-text instructions explain the model and each output.

python3 run_example.py --output my-results

The command runs the baseline twice, checks byte-identical results and manifests, then changes exactly one cost input. It saves six inspectable JSON artifacts and prints the comparison. Use a new output folder for another execution. The runner refuses to overwrite existing result files.

The resulting trade ledger

For every trade, retain direction, entry and exit times, quantities, actual modeled fill prices, instrument value and each cost component. For partial exits, retain the individual fills instead of compressing them into an average that loses quantity information. The ledger should explain the summary without requiring the chart.

The runner generates the same three-trade arithmetic below. The hypothetical contract is worth $20 per point. Commission is $5 per contract per side and slippage is zero. Every P/L amount in the table is already the total for its stated quantity.

TradeDirection and quantityEntry to exitGross P&LCostsNet P&L
1Long × 1100 to 110$200$10$190
2Short × 2110 to 106$160$20$140
3Long × 1105 to 102−$60$10−$70
Total3 tradesClosed positions$300$40$260

Long gross profit is exit minus entry, multiplied by point value and quantity. For a short, entry minus exit gives the correct sign. Trade two therefore earns (110 − 106) × $20 × 2 = $160 before costs. The three net results sum to $260. This simple test catches sign, quantity and double-cost errors before more complicated analytics are introduced.

Reconcile gross and net equity trade by tradeThe same three trades from $100,000. Gross profit totals $300, costs $40 and net profit $260. Each trade carries its own costs. Gross: 100k, 100.2k, 100.36k, 100.3k. Net after costs: 100k, 100.19k, 100.33k, 100.26kReconcile gross and net equity trade by tradeGrossNet after costs100k100.1k100.2k100.3k100.4k0123Trade numberEquity (USD)
The same three trades from $100,000. Gross profit totals $300, costs $40 and net profit $260. Each trade carries its own costs.

Reconcile equity and metrics

With starting capital of $100,000 and no external cash flows, the closed-trade equity sequence is $100,190, $100,330 and $100,260. The final value is starting capital plus $260. The largest closed-equity drawdown is $70 from the second-trade peak to the final value. It is not proof that intratrade drawdown was only $70.

For this net trade ledger, win rate is two divided by three, or 66.67%. Net-based profit factor is $330 of winning net outcomes divided by $70 of losing net outcomes, or approximately 4.714. Average trade is $260 / 3 = $86.67. A report using gross profit factor would produce a different number and should label the convention.

Do not estimate a meaningful annualized Sharpe ratio from these three trade outcomes without a time model. A Sharpe ratio normally uses returns sampled over defined intervals, with assumptions about annualization and dependence. A missing statistic can be more honest than a number computed from incompatible units.

Drawdown from the running equity peakThe same three trades from $100,000. Gross profit totals $300, costs $40 and net profit $260. Each trade carries its own costs. Gross: 0, 0, 0, -60. Net after costs: 0, 0, 0, -70Drawdown from the running equity peakGrossNet after costs-80-60-40-2000123Trade numberDrawdown (USD)
The same three trades from $100,000. Gross profit totals $300, costs $40 and net profit $260. Each trade carries its own costs.

Run twice, then change exactly one assumption

The two baseline executions must agree on targets, trade timestamps, prices, directions, quantities, costs, closed equity and their serialized result bytes. They must also agree on the input manifest when run in the same environment. Here both baseline result fingerprints are 347a31ec07de0de078464502d8f338095aa96a41becee98bfb816503bd75a787.

Now change only execution.commission_per_contract_per_side_usd from "5.00" to "6.00". There are four round-turn contracts, or eight charged contract-sides. One extra dollar per side therefore removes exactly $8 from net P/L. The signal, price and quantity records remain unchanged, but this is a different execution-cost experiment.

Actual outputs generated by the downloadable runner
CheckBaseline run 1Baseline run 2Higher fee
Gross P/L$300.00$300.00$300.00
Commission$40.00$40.00$48.00
Net P/L$260.00$260.00$252.00
Maximum closed drawdown$70.00$70.00$72.00
Result SHA-256, shortened347a31ec07de347a31ec07de15b5765ba109

The published reference outputs are baseline ledger and equity, higher-fee ledger and equity and the two-run comparison. Inspect the changed configuration to confirm that only one leaf differs from the baseline.

Keep fingerprints separate so they can explain a difference

Input identities lead to an experiment, then a separate resultCode, data, parameters, execution and environment fingerprints form the experiment fingerprint. The generated ledger has its own result fingerprint. The manifest connects them without hashing itself.CODE · strategy + runnerDATA · bytes + declarationPARAMETERS · typed inputsEXECUTION · fills + costsENVIRONMENT · runtimeEXPERIMENT FINGERPRINT4ab808295ca5…LEDGER → RESULT FINGERPRINT347a31ec07de…
Fingerprints from this example. The experiment identifies inputs. The result identifies outputs. Full values are available in the manifests.

The code identity covers exact strategy and runner bytes. Data identity covers the CSV bytes and its declaration. Parameters, execution and environment are serialized as sorted JSON. The experiment fingerprint covers those input identities only. The result fingerprint covers the result JSON only. The manifest stores both, without including itself in either hash.

Download the baseline manifest and higher-fee manifest. In the controlled comparison, only the execution fingerprint changes among input domains. The configuration, experiment and result fingerprints consequently change as well. Identical final profit would not, by itself, establish an identical experiment.

The reference manifests record the Python version, implementation, operating system and architecture used to generate them. A reader using a different environment should expect a different environment and experiment fingerprint. The published integer-cent result was independently reproduced with CPython 3.12.14 and 3.13.5. That is a narrow known-answer check, not a universal promise of bitwise floating-point portability. Verify the supplied answer in your own runtime.

The serializer is explicitly sorted, indented UTF-8 JSON with a final newline. It excludes wall-clock time, output paths and random run IDs. A fingerprint is meaningful only with that declared representation. It detects a content change. It does not prove correct code, genuine market fills, data rights, security, robustness or profitability.

Separate closed equity from marked equity

Closed equity changes when trades realize profit or loss. Marked equity also includes open positions. These curves answer different questions. A strategy can close every trade profitably while suffering large temporary losses. For account-level risk, margin or prop-limit analysis, those temporary losses can matter.

Choose a consistent mark price and timestamp frequency. If only OHLC bars are available, the exact intrabar path may be unknown. Do not make the open-equity curve appear more precise than the data supports. A conservative approximation should be identified as a model rather than described as a reconstructed tick path.

When comparing phases, state whether starting equity resets at each boundary or continues cumulatively. A validation curve normalized to $100,000 is useful for standalone comparison. Concatenating that reset curve directly after development without adjusting the level creates a false jump. Preserve the distinction between segment performance and one continuous portfolio path.

Use chronological data splits

Development data support design and optimization. Validation checks choices on later or otherwise separated data. A final holdout is reserved for a locked decision. The split does not make a strategy good, but it helps distinguish designing a rule from evaluating a rule that was already chosen.

Parameters, filters and objectives should be selected without reading the final holdout. If you inspect the holdout and change the strategy, that data has influenced development. You can still rerun it, but it is no longer fresh independent evidence. Store that history rather than pretending a new code label makes previously inspected observations unseen.

Boundary handling needs care when trades overlap periods. You can assign trades by entry, close positions at a boundary, or use another declared convention. Each creates a different experiment. Ensure metrics and charts use the same convention, and do not accidentally count one trade in two reported segments.

Test the engine before trusting a complex strategy

Use small artificial price sequences with known outcomes. Test one long, one short, a gap through a stop, a target and stop inside the same bar, a partial exit and a trade crossing a session boundary. Verify exactly which event wins when conditions coincide. These fixtures expose assumptions that a large historical backtest can hide.

Also test invariants. Net profit should reconcile with the ledger. Closed quantity should not exceed opened quantity. A flat account should have no unrealized exposure. Repeated runs with identical inputs should agree. Changing a display filter should not mutate saved results. These checks protect the calculation chain rather than one favorable example.

For cached results, test both reuse and invalidation. Identical code, inputs and context can reuse a verified artifact. A change in commission, data content or engine version must not retrieve an incompatible result merely because the strategy name is unchanged. Correct reuse improves speed without mixing evidence.

Compare settings without losing identity

Once the base run is reconciled, compare A, B and C across the same data and cost assumptions. Preserve each setting's separate report. If B is selected for validation, its validation result should refer to B's exact inputs and code, not whichever setting happens to be active on the screen afterward.

Keep analysis-specific settings separate too. Monte Carlo simulation count does not change the historical trade ledger. An alternative exit rule does. A macro filter explored after the run is not automatically a new executable strategy until it is implemented and replayed with the necessary position-state changes.

A practical handoff includes the saved configuration, trade ledger, equity series, metric definitions and software version. The report then becomes a view of reproducible evidence rather than the only place where the evidence exists.

Reproducible backtest checklist

  • Code: exact source bytes or immutable revision, engine version and dependency versions.
  • Parameters: complete typed input values, including defaults that actually applied.
  • Data: content version, source, schema, resolution and timestamp convention, not only a file path.
  • Contract: outright identity, price units, quantity and any explicit mapping or roll rule.
  • Dates: inclusive/exclusive boundaries, warm-up and treatment of positions crossing the measured period.
  • Sessions: named timezone, trading-day boundaries and calendar exceptions used in the run.
  • Execution: information availability, fill timing, gap behavior and ambiguous stop/target policy.
  • Costs: per-side or round-turn units, quantities, slippage treatment and whether P/L is already net.
  • Randomness: generator, algorithm version and seed where used. Do not add a meaningless seed to a deterministic calculation.
  • Outputs: trade/fill ledger, equity convention, metric definitions, configuration and verified artifact fingerprints.
  • Comparison: rerun the baseline, then change one declared input and verify both result change and cache invalidation.

Apply the record to the EdgeVeris workflow

In the current EdgeVeris workflow, a code version and normalized parameter values identify an input set. Data and execution-cost context remain separate. An A or B label makes selection convenient, but it cannot stand in for that complete identity. Stored evidence is checked against its source context before supported results are combined in a downloadable report.

The product reference model and the tiny runner above are not interchangeable. For example, the product implements optional protective exits and its own declared execution-cost modes, while this teaching runner has no stops and zero slippage. Use the futures backtest construction and assumptions checklist to inspect those actual product boundaries. Reproducible arithmetic still needs a defensible execution model.

For another inspectable accounting example, the free futures cost audit separates gross, already-net and alternative-cost scenarios. A randomized analysis needs additional sampling settings. The R03 synthetic resampling study publishes its method and seed so differences in dependence assumptions can be examined, rather than attributed to an unexplained random run. In the public Monte Carlo drawdown tool, keep the input trade sequence, method, block length where applicable, path count and seed with the output. Changing the sampler is a different analysis, not merely another chart of the same calculation.

Finally, distinguish repeatability from trustworthiness. An overfit strategy can reproduce perfectly. A deterministic fill model can be consistently optimistic. Once one run reconciles, follow the strategy validation evidence chain for selection discipline, OOS testing, robustness and holdout limitations.

A reliable first milestone

Before optimizing hundreds of settings, make one setting fully explainable. Reconcile every trade, confirm the period and costs, verify the timing of signals and rerun it from the saved configuration. That small milestone provides a dependable reference for every later phase. Fast optimization on top of an ambiguous base run only produces more ambiguous results.