stock-bot/docs/guide/backtest-walkthrough.md

17 KiB
Raw Blame History

Follow one backtest from the browser to the ledger

Guide home · System map · Writing strategies

The browser configures research; TypeScript organizes the work and makes strategy decisions; Rust decides what those decisions do to money and positions. PostgreSQL keeps the durable record. Redis delivers work to the orchestrator.

This walkthrough follows the current canonical research path. Its admitted runs use one retained strategy version and one eligible asset/series, with cash-funded long-only execution. Historical results and experimental code elsewhere in the repository do not expand that supported scope.

The guide glossary explains templates, runs, attempts, intents and fills.

1. Configure a run

Open a backtest, choose an immutable strategy version, select a prepared dataset, and configure capital, fees, slippage and risk. The browser checks execution eligibility before enabling submission. Missing dataset metadata or an unavailable retained build is an execution problem to resolve, not something the UI silently substitutes.

Start reading at BacktestDetailPageV2, CanonicalSetup, and backtestApiV2. The browser submits through /api/v2/backtests/:id/runs and later reads /api/v2/runs/:id and /api/v2/runs/:id/results.

The dataset records both when a bar describes the market and when the completed bar becomes available. A 09:03–09:04 bar cannot provide its close at 09:03. Delayed availability can be later than 09:04. Rust exposes observations according to availability, with explicit warmup and trading boundaries. See historical-dataset-v2.ts and how stored data becomes research input.

2. Admission freezes the request and schedules it durably

admitCanonicalRequest() validates the retained strategy package, dataset, parameters, policies and installed build identity. BacktestServiceV2.createRun() saves the immutable request_snapshot and a backtest_dispatch row in the same PostgreSQL transaction.

The dispatch row is an outbox: a durable promise to enqueue the run. If Redis is unavailable after the SQL commit, the saved request still exists. BacktestDispatcher retries publication to the existing BullMQ queue. Queue messages carry the run ID; workers load the authoritative request from SQL.

sequenceDiagram
    participant UI as Browser
    participant API as Web API / dispatcher
    participant DB as PostgreSQL
    participant Q as Redis / BullMQ
    participant Run as Orchestrator runner
    participant Child as Native worker / TS strategy
    participant Rust as Rust engine
    UI->>API: Submit saved configuration + submission key
    API->>DB: Save frozen run + dispatch intent atomically
    API-->>UI: Run ID
    API->>Q: Publish run ID
    Q->>Run: Deliver job to a pool slot
    Run->>DB: Claim attempt and load frozen request/dataset
    Run->>Child: Start disposable worker with exact inputs
    Child->>Rust: Load replay session through native binding
    loop Eligible decision barriers
        Rust-->>Child: Available observations + financial view
        Child->>Rust: Validated strategy intent
        Rust->>Rust: Risk checks, next-open matching, accounting
    end
    Rust-->>Child: Terminal financial report
    Child-->>Run: Validated result envelope
    Run->>DB: Commit result under attempt ownership
    UI->>API: Read saved status and result
    API->>DB: Read durable run
    API-->>UI: Financial report + analysis + provenance

3. A runner owns the attempt; a child process owns the replay

ResearchBacktestPool reserves independent runner slots. Each slot has its own BacktestRunner, which claims a database lease, renews it, reports progress, checks cancellation and commits only while it owns the attempt. This prevents an abandoned worker from overwriting its replacement's result.

RustBacktestAdapter.runCanonical() loads the frozen dataset and calls NativeBacktestWorker.execute(). The native simulation runs in a disposable child process, so cancellation or a deadline can terminate it. That child has no database/service-container access.

native-worker.ts verifies the retained package and build before loading code. Approved built-ins execute as TypeScript callbacks there. Candidate code instead runs through the isolated candidate controller in its restricted container; it receives available observation prefixes, not the supervisor's full future dataset. Both paths submit decisions to the same Rust financial engine.

4. Follow a concrete SMA trade

The existing SMA oracle and regression test provide a small example you can calculate by hand. This synthetic fixture uses initial capital 10,000, fast/slow periods 2/3, strategy sizing budget 40, a 1% fee, and zero spread/slippage. These are test inputs, not recommended trading parameters.

Bar Open Close Key event
1 3 3 Start the history.
2 3 2 Still gathering history.
3 2 1 Enough for an average, but no crossover yet.
4 1 4 Fast average crosses above slow; request a target of 10 shares.
5 5 5 The entry fills at this open: 10 × 5, plus a 0.50 fee.
6 5 1 Fast average crosses below slow; request a target of zero.
7 2 1 The exit fills at this open: 10 × 2, less a 0.20 fee.

createSmaStrategy().decide() retains its observed close history and emits a desired quantity. At bar 4's close, 40 / 4 gives ten whole shares. That sizing budget is a strategy input; Rust still checks actual cash, reservations and portfolio limits. It does not promise the future fill price will equal 4.

StrategyController validates callback state and intent against the current decision barrier. runReplaySession() drives the native session until another decision is needed or the run ends. Rust's Replay owns event order and information availability; MatchingAccount, risk and ledger own admissibility, fills and money.

The entry decision cannot fill at bar 4's open of 1: that price was already past when the close became known. It fills at bar 5's eligible open of 5. The exit similarly fills at bar 7's open of 2. Available volume and execution policy can restrict fills in other cases; a target is never proof that the whole position was filled.

Final cash and equity are 10,000 − 50 − 0.50 + 20 − 0.20 = 9,969.30. Fees total 0.70, and this example ends flat. The test checks exact fills, fees and equity, including identical financial output across different replay step budgets.

If a run ends with an open position, Rust values the remaining position using its terminal marks. It does not invent a closing sale or closing commission. Pending orders are cancelled at finish. Open positions, fills and terminal equity therefore belong in separate result views.

5. Save and inspect the result

Rust returns financial facts, including orders, fills, positions and valuation. buildCanonicalBacktestReport() derives statistical analysis from those facts without replacing the ledger. Unavailable metrics retain an explicit reason; an absent win rate or benchmark comparison is not zero performance.

BacktestRunner validates the result and commits it through PostgresBacktestRunRepository. Completion notifications follow persistence. The browser's CanonicalResults and ResultProvenance render this saved record. Reloading the page reads the same run; it does not rerun the simulation. WebSocket updates help refresh the display, but the database owns status and results.

Take the result into a notebook or local AI workflow

Open a completed canonical run and choose Download run result. The file, run-<runId>.json, contains the complete result already displayed, including the original request. Changing the backtest's editable settings does not change an earlier run's file. Downloading makes no additional API request and neither saves settings nor submits a run.

Useful fields for exploration:

Field Contents
request Original dataset hash, strategy package/parameters, execution policy and engine/build identity.
financial.projection Native fills and terminal valuation.
financial.view Native orders, account and strategy-owned position views.
financial.reporting Evaluation bounds, session samples and reporting policy.
analytics Metrics, unavailable-value reasons and statistical assumptions.

For a quick inspection with Bun:

const result = await Bun.file('/path/to/run-<runId>.json').json();
console.log(result.runId, result.request.datasetHash);
console.table(result.financial.projection.fills);
console.log(result.financial.projection.valuation, result.analytics.unavailable);

Financial decimal strings and null metric values remain unchanged; chart rounding is not exported. Keep null reasons when comparing runs instead of treating missing metrics as zero. Pair the result with its retained dataset download to explore observations and outcomes in VS Code, notebooks or local AI tools.

This is an analysis record, not a self-contained replay archive or an upload format. Bars and engine binaries are separate; use Reproduce original run for the existing retained execution path. The JSON includes the retained strategy JavaScript as text and never executes it during download or JSON inspection. A local download failure offers Retry run result download.

6. Retry, cancel and reproduce are different operations

Operation What to expect
Retry an uncertain submission Resend the same submission key and body to recover the same run. Do not invent another key just because the HTTP response was lost.
Recover a lost worker The dispatcher detects an expired lease and may schedule a new attempt within the retry/deadline policy. Old ownership is fenced out.
Retry a failed experiment trial Review its recorded failure, then use the trial retry action. It preserves the frozen trial inputs and records retry history.
Cancel The API records cancellation; the runner stops work and records the terminal state. Request accepted and worker stopped are separate moments.
Run the current configuration Submit a new snapshot of the editable template, which may now differ from earlier runs.
Reproduce a saved run Use the reproduction action to preserve original input/build identity and compare financial hashes. Missing retained builds block reproduction rather than falling back to current code.

See RunReproduction, ExperimentTrialRecovery, and the reproduction methods in BacktestServiceV2. Reproduction verifies economic output; elapsed wall time and new run IDs need not match. Arbitrary candidate JavaScript still needs deterministic authoring: retaining its code and seed does not make nondeterministic code deterministic.

Grow one run into a research workflow

When a linked backtest cannot be loaded, the setup page keeps other successfully loaded catalog choices available and reports the lookup failure. The unavailable selection stays selected until you choose another; your experiment name and parameter grid are preserved. Retry saved backtests retries loading without automatically choosing a different template. Selecting a valid template does not save anything or submit runs; use the normal preview and confirmation steps.

  1. Create a research project and hypothesis, link a strategy, and save the backtest configuration. Keep the proposed explanation separate from measured evidence.
  2. Create an experiment with a bounded parameter grid. Each trial uses the same durable run path above. Compare completed results alongside errors and incomplete trials.
  3. Use chronological validation to select on training data, then evaluate the selected parameters on held-out validation/test data. A saved sealed report links the evidence. Walk-forward applies this over windows; its current windows reset state and capital, so do not interpret them as one continuously traded account.
  4. Run cost sensitivity on the selected configuration and compare ordinary experiments with compatible inputs. Save findings with explicit run/report references.
  5. Reopen those saved IDs to inspect or reproduce the work. The browser is the normal research interface; authorized AI clients use the same backend capabilities with separate grants and budgets.

Project, hypothesis, note and finding creation also verifies the returned content before opening a saved record or showing success. If that acknowledgement cannot be verified, the original draft stays blocked. Use Check saved projects or Check saved records to review what committed; checking does not resubmit. Start a new request only after that review, or deliberately discard the draft and open the existing record.

When editing a saved hypothesis, note or finding, Save new revision clears the draft only after the returned revision matches its entry, submitted text and retained citations. An unverifiable acknowledgement may follow a committed write: the form preserves and blocks the draft without retrying. Review it, then deliberately choose Discard draft and reload history to inspect the saved revisions before deciding whether another edit is needed.

Open a hypothesis, note or finding and choose Download saved revision to take its narrative and citations into local analysis. When viewing history, the file contains that exact older revision. While editing, it exports the saved version and leaves your draft untouched. Archived entries can still be downloaded.

The file research-<entryId>-<revisionId>.json has kind: "research-revision-export/v1", projectId, an entry identity/kind (including an artifact's linked hypothesis-revision ID), and the complete saved revision. Authorship, source/report hashes, raw cited values, unavailable reasons and limitations are preserved. Downloading uses the loaded record and makes no additional API request. A local failure offers Retry saved revision download. Pair it with the separate run-result and dataset files above for notebook or AI analysis. The file is an analysis record; replay uses the retained execution path.

Useful entry points are ResearchProjectPage, ExperimentDetailPage, ChronologicalValidationDetailPage, and WalkForwardDetailPage.

The AI research-cycle example submits prepared candidate packages, bounded searches, held-out validation and cost studies, then creates evidence-linked findings. It records request intents and receipts for recovery. It does not independently generate code, supply a model SDK or activate trading; AI-written findings remain distinguishable from validated results.

How paper trading differs

Paper trading uses the same Rust financial kernel with fresh quote inputs, rather than replaying frozen historical opens. A human must review the required held-out/cost evidence and create a separate immutable deployment. PaperDeploymentHost then requires explicit binding, readiness and activation; creating a deployment does not start trading. Candidate catalog approval alone is insufficient, and research agents cannot promote or activate deployments. Paper account/checkpoint recovery is separate from disposable research runs. Live broker deployment is not available through this workflow.