Episode 43 · AI Trading · Building a Complete Trading System

Capstone: ML against a baseline, ablation and shadow mode

Run a baseline and each ablation on the same folds and costs, count every try, shadow the decisions without orders and hand in a six-file dossier.

How do you compare a machine-learning model with a simple rule fairly, and what has to be in the folder you hand in at the end?

This capstone builds the versions side by side on the same data, costs and exits: a baseline, the baseline plus feature A, and A plus B. It counts every version as a try, runs the chosen one in shadow mode without sending orders, and checks that the six files of the dossier exist. The easy mistake: the ML version loses less than the baseline on the sample you’ve looked at, and you write that down as an edge. Write exactly what it is: “loses less, in this sample”. That isn’t an edge.

Terms used below:

  • Baseline: a simple rule with nothing learned, run with the same data, costs and exits as the model. The model has to beat it.
  • Ablation: removing one component at a time and rerunning, everything else unchanged, to see what each part adds on the test data.
  • Shadow mode: the system logs the decision it would make, with the quote and the time, and sends no order.
  • m: the number of tries, one per row of experiment-registry.csv. The baseline and every ablation count.
  • Naive forecast: “the next price equals the current price”. The minimum baseline for anything that forecasts a price.
  • MAE (mean absolute error): the average size of a forecast’s miss.

Lock everything before the run

Before the first run, write down and hash what the run depends on. Anything changed afterwards is a new try and a new row.

Locked How
Data File hash in the registry (data_sha)
Code Commit or file hash
Config Parameters in a committed file
Model Model hash, if a model file exists
Baseline Written as a rule before the model runs
Metric Mean net return per trade, its 95% interval and t; a threshold raised for m
Folds Walk-forward with purging, from the walk-forward post

Then run walk-forward over every fold and ablate one component at a time, with the same costs and fills wherever the versions can be compared. Report the folds that went badly as well. Shadow mode follows in new time: an event ID, a state and a report for every decision, including errors, unfilled orders and stretches without enough data. Putting a system on a live account is a separate process that this capstone doesn’t prove anything about.

Baseline and ablation on the same folds

Four versions, one script, src/ablation.py, in C:\trade-system-lab. It reuses src/walkforward.py from the walk-forward post: the same RSI 14 and 100-bar return, the same 24-bar label, the same rolling folds with purging, the same cost of 0.02% per trade. Only the signal changes:

Version Signal
baseline Sign of the 100-bar return; nothing learned
+A kNN on RSI 14 (B removed)
+B kNN on the 100-bar return (A removed)
+A+B kNN on both

Trades are taken once every 24 bars, so no two trades overlap and the interval isn’t inflated by counting the same move 24 times. Every version writes one row to reports/experiment-registry.csv, and the threshold for t rises with the row count:

# src/ablation.py: baseline, +feature A, +A+B on the same folds, costs and exits. Every version is one row in the
# experiment registry; m = the number of rows; the t threshold rises with m. Trades don't overlap (one every H bars).
#   .venv\Scripts\python src\ablation.py data\xauusd_h1_utc.csv
import csv, hashlib, math, sys
from datetime import date
from pathlib import Path
from statistics import NormalDist

import numpy as np

sys.path.insert(0, str(Path(__file__).parent))
import walkforward as wf                                 # from the walk-forward post

REGISTRY = Path("reports/experiment-registry.csv")
COLS = ["date", "version", "change", "data_sha", "folds", "trades", "mean_net_pct", "ci_low", "ci_high", "t", "run_by", "note"]


def log_row(row):
    REGISTRY.parent.mkdir(exist_ok=True)
    new = not REGISTRY.exists()
    with open(REGISTRY, "a", newline="") as f:
        w = csv.DictWriter(f, fieldnames=COLS)
        if new:
            w.writeheader()
        w.writerow(row)


def m_tries():
    with open(REGISTRY, newline="") as f:
        return sum(1 for _ in csv.DictReader(f))


def t_threshold(m, alpha=0.025):
    return NormalDist().inv_cdf(1 - alpha / m)          # one-sided, Bonferroni, large-sample


def verdict(lo, hi, t, thr):
    if hi < 0:
        return "entirely below 0: evidence of a loss on this data and these costs"
    if lo <= 0:
        return "contains 0: no evidence either way"
    return "above 0 and t >= threshold: a candidate for shadow, not an edge yet" if t >= thr else "above 0 but t below the threshold"


def run_version(c, X, y, ret, ok, cols, learn):
    per_fold, nets = [], []
    first = int(np.argmax(ok))
    for f in wf.folds(len(c), first):
        test = f["test"][::wf.H]                         # one trade every H bars: no overlap
        test = test[ok[test]]
        keep = f["keep"][ok[f["keep"]]]
        if learn:
            p = wf.knn(X[:, cols], y, keep, test)
        else:
            p = np.where(X[test, 1] > 0, 1.0, -1.0)     # baseline: sign of the 100-bar return, nothing learned
        net = (p * ret[test] - wf.COST) * 100
        per_fold.append(net.mean())
        nets.append(net)
    allnet = np.concatenate(nets)
    m, s = allnet.mean(), allnet.std(ddof=1)
    se = s / math.sqrt(len(allnet))
    return dict(folds=len(per_fold), trades=len(allnet), mean=m, lo=m - 1.96 * se, hi=m + 1.96 * se, t=m / se,
                per_fold=per_fold)


def main(path):
    raw = Path(path).read_bytes()
    sha = hashlib.sha256(raw).hexdigest()[:12]
    with open(path, newline="") as f:
        c = np.array([float(r["close"]) for r in csv.DictReader(f)])
    X, y, ret, _ = wf.dataset(c)
    ok = ~np.isnan(X).any(1) & ~np.isnan(y) & (y != 0)
    versions = [("baseline", "sign of the 100-bar return", [1], False),
                ("+A", "kNN on RSI 14 (B removed)", [0], True),
                ("+B", "kNN on the 100-bar return (A removed)", [1], True),
                ("+A+B", "kNN on RSI 14 and the 100-bar return", [0, 1], True)]
    results = {}
    for name, change, cols, learn in versions:
        r = run_version(c, X, y, ret, ok, cols, learn)
        results[name] = r
        log_row(dict(date=date.today().isoformat(), version=name, change=change, data_sha=sha, folds=r["folds"],
                     trades=r["trades"], mean_net_pct=f"{r['mean']:.4f}", ci_low=f"{r['lo']:.4f}",
                     ci_high=f"{r['hi']:.4f}", t=f"{r['t']:.2f}", run_by="script", note="ablation, same folds and costs"))
    m = m_tries()
    thr = t_threshold(m)
    print(f"data {sha} | {len(c)} bars | horizon {wf.H} | cost {wf.COST:.2%} | m = {m} tries | t threshold {thr:.2f}")
    print("version   trades  mean net %   95% interval         t      per fold (mean net %)")
    for name, r in results.items():
        folds = " ".join(f"{x:+.2f}" for x in r["per_fold"])
        print(f"{name:<9} {r['trades']:>5}  {r['mean']:+.4f}    {r['lo']:+.4f} .. {r['hi']:+.4f}  {r['t']:+.2f}   {folds}")
    for name, r in results.items():
        print(f"{name:<9} {verdict(r['lo'], r['hi'], r['t'], thr)}")


if __name__ == "__main__":
    main(sys.argv[1])

Run .venv\Scripts\python src\ablation.py data\xauusd_h1_utc.csv on the random-walk sample from the tuning post:

data 1098236c9a88 | 10994 bars | horizon 24 | cost 0.02% | m = 4 tries | t threshold 2.50
version   trades  mean net %   95% interval         t      per fold (mean net %)
baseline    336  +0.0323    -0.0642 .. +0.1287  +0.66   -0.07 +0.13 +0.22 +0.04 -0.14 -0.08 +0.18 -0.01
+A          336  +0.0123    -0.0843 .. +0.1088  +0.25   +0.24 +0.24 -0.13 -0.08 -0.07 -0.02 -0.04 -0.03
+B          336  -0.0005    -0.0971 .. +0.0961  -0.01   +0.03 -0.03 +0.19 +0.07 -0.01 -0.03 -0.32 +0.09
+A+B        336  -0.0099    -0.1065 .. +0.0867  -0.20   +0.10 +0.19 -0.18 -0.04 +0.15 -0.00 -0.14 -0.15
baseline  contains 0: no evidence either way
+A        contains 0: no evidence either way
+B        contains 0: no evidence either way
+A+B      contains 0: no evidence either way

The registry it wrote, one row per try:

date,version,change,data_sha,folds,trades,mean_net_pct,ci_low,ci_high,t,run_by,note
2026-12-04,baseline,sign of the 100-bar return,1098236c9a88,8,336,0.0323,-0.0642,0.1287,0.66,script,"ablation, same folds and costs"
2026-12-04,+A,kNN on RSI 14 (B removed),1098236c9a88,8,336,0.0123,-0.0843,0.1088,0.25,script,"ablation, same folds and costs"
2026-12-04,+B,kNN on the 100-bar return (A removed),1098236c9a88,8,336,-0.0005,-0.0971,0.0961,-0.01,script,"ablation, same folds and costs"
2026-12-04,+A+B,kNN on RSI 14 and the 100-bar return,1098236c9a88,8,336,-0.0099,-0.1065,0.0867,-0.20,script,"ablation, same folds and costs"

How to read it:

  • m = 4. Four tries, so the one-sided threshold is 2.50 instead of 1.96. Add a fifth version and it rises again. Use the same trial log as in the luck-or-skill post if you keep one already.
  • Every interval contains 0. No version has evidence of anything, the baseline included. On a random walk that’s the right answer.
  • The ML versions did worse than the baseline here. Write that down too. Ablation tells you what helped on this test data; it doesn’t prove cause or that it will hold in future.
  • The folds disagree. +A made +0.24% in folds 1 and 2 and lost in the next six. Keeping only the best folds is the mistake from the walk-forward post.

The case to rehearse is the opposite one. The baseline is negative after costs, and the ML version is less negative on the sample you’ve seen. Record “less negative in sample”, then read the sample size, the costs, the drawdown and the folds. If the interval contains 0, there’s no evidence yet; if it sits entirely below 0, that’s evidence of a loss on that data and those costs. Neither is an edge. The conclusion can stay at research, with a hypothesis and the next test.

Interval of mean net per trade What you can write
Contains 0 No evidence either way, even if the ML loses less than the baseline
Entirely below 0 Evidence of a loss on this data and these costs
Above 0, t below the threshold for m Not enough after counting the tries
Above 0, t at or above the threshold A candidate for shadow mode; still not an edge

The script reports mean net return per trade in % of price, because its exit is a fixed 24 bars. If your exits use a stop, report mean R the same way.

A price forecast must beat “no change”

If your model forecasts a price instead of giving orders, its minimum baseline is the naive forecast: the next close equals this close. A moving average looks smarter and usually isn’t. src/naive_mae.py:

# src/naive_mae.py: a price forecast must beat "no change" before it's worth anything.
#   .venv\Scripts\python src\naive_mae.py data\xauusd_h1_utc.csv
import csv, sys


def ema(values, n):
    k, out, e = 2 / (n + 1), [], None
    for v in values:
        e = v if e is None else e + k * (v - e)
        out.append(e)
    return out


def mae(closes, forecast, start=20):
    """Forecast for bar t+1's close, made at bar t's close."""
    errs = [abs(closes[t + 1] - forecast[t]) for t in range(start, len(closes) - 1)]
    return sum(errs) / len(errs), len(errs)


if __name__ == "__main__":
    with open(sys.argv[1], newline="") as f:
        c = [float(r["close"]) for r in csv.DictReader(f)]
    naive, n = mae(c, c)                       # next close = this close
    e20, _ = mae(c, ema(c, 20))
    print(f"{n} forecasts of the next H1 close | naive MAE {naive:.2f} | EMA 20 MAE {e20:.2f} ({e20 / naive:.1f}x worse)")

On the random-walk sample:

10973 forecasts of the next H1 close | naive MAE 4.58 | EMA 20 MAE 10.98 (2.4x worse)

On a random walk “no change” is the best forecast by construction, so this sample only shows the check working. On historical XAUUSD H1 candles (10,811 forecasts of the next close, checked 2026-11-23) the result has the same shape: naive MAE 8.17 USD, EMA 20 MAE 20.66 USD, 2.5 times worse. For a system that gives orders, the baseline is still a simple rule with the same costs, as above.

Shadow mode: log the decision, send no order

Step Who What
1 Agent or AI Logs the intended decision with the quote, the time and an event ID
2 Blocked Sends no order
3 You, or you review Compare with a separate demo flow that’s allowed to trade
4 You, or you review Measure latency and fill; never assume the chart’s Close
5 Report Errors, no fill and missing data too

Ten shadow decisions, data/shadow_decisions.csv. Made-up sample data; the prices are placeholders:

event_id,bar_close_utc,decided_at_utc,decision,reason,chart_close,quote_bid,quote_ask,model_hash
S-0001,2026-11-30T09:00:00Z,2026-11-30T09:00:01.4Z,buy,,4121.35,4121.20,4121.52,9c41e0
S-0002,2026-11-30T13:00:00Z,2026-11-30T13:00:01.1Z,skip,spread 0.61 above 0.50,4128.90,4128.55,4129.16,9c41e0
S-0003,2026-11-30T16:00:00Z,2026-11-30T16:00:01.3Z,sell,,4133.10,4132.98,4133.27,9c41e0
S-0004,2026-12-01T08:00:00Z,2026-12-01T08:00:01.2Z,buy,,4110.40,4110.31,4110.60,9c41e0
S-0005,2026-12-01T10:00:00Z,2026-12-01T10:00:01.5Z,sell,,4115.75,,,9c41e0
S-0006,2026-12-01T14:00:00Z,2026-12-01T14:00:01.0Z,buy,,4104.05,4103.88,4104.19,9c41e0
S-0007,2026-12-01T19:00:00Z,2026-12-01T19:00:01.6Z,skip,news window,4098.60,4098.41,4098.73,9c41e0
S-0008,2026-12-02T09:00:00Z,2026-12-02T09:00:01.2Z,sell,,4119.30,4119.18,4119.47,9c41e0
S-0009,2026-12-02T12:00:00Z,2026-12-02T12:00:01.4Z,buy,,4126.85,4126.70,4127.02,9c41e0
S-0010,2026-12-02T15:00:00Z,2026-12-02T15:00:01.3Z,sell,,4131.20,4131.04,4131.37,9c41e0

What the separate demo flow recorded, data/demo_fills.csv:

event_id,status,filled_at_utc,fill_price,note
S-0001,filled,2026-11-30T09:00:02.6Z,4121.58,
S-0003,filled,2026-11-30T16:00:02.2Z,4132.91,
S-0004,filled,2026-12-01T08:00:03.9Z,4110.74,
S-0006,rejected,,,requote; no retry by rule
S-0008,filled,2026-12-02T09:00:02.1Z,4119.12,
S-0009,filled,2026-12-02T12:00:02.4Z,4127.05,
S-0011,filled,2026-12-02T13:40:11.0Z,4129.60,

src/shadow.py joins them by event ID. Cost is positive when the fill was worse than the reference: above it for a buy, below it for a sell.

# src/shadow.py: compare what the system meant to do (shadow log, no orders) with what the separate demo flow did.
# Latency and slippage come from measured times and fills, never from the chart's Close.
#   .venv\Scripts\python src\shadow.py data\shadow_decisions.csv data\demo_fills.csv
import csv, sys
from datetime import datetime


def t(s):
    return datetime.fromisoformat(s.replace("Z", "+00:00"))


def load(p):
    with open(p, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def compare(decisions, fills):
    by_id = {f["event_id"]: f for f in fills}
    out = []
    for d in decisions:
        e, f = d["event_id"], by_id.pop(d["event_id"], None)
        if d["decision"] == "skip":
            out.append((e, "skipped", f"rule said no trade: {d['reason']}" + ("; but the demo flow filled it" if f else "")))
            continue
        if d["quote_bid"] == "" or d["quote_ask"] == "":
            out.append((e, "no quote", "decision logged without a quote: can't measure the fill against it"))
            continue
        if f is None:
            out.append((e, "missing", "no demo record for this event"))
            continue
        if f["status"] != "filled":
            out.append((e, f["status"], f["note"] or "-"))
            continue
        quote = float(d["quote_ask"]) if d["decision"] == "buy" else float(d["quote_bid"])
        sign = 1 if d["decision"] == "buy" else -1
        slip_quote = sign * (float(f["fill_price"]) - quote)
        slip_close = sign * (float(f["fill_price"]) - float(d["chart_close"]))
        lat = (t(f["filled_at_utc"]) - t(d["decided_at_utc"])).total_seconds()
        out.append((e, "filled", f"latency {lat:.1f} s | cost vs quote {slip_quote:+.2f} | vs chart close {slip_close:+.2f}"))
    for e in by_id:
        out.append((e, "stray", "demo record with no shadow decision"))
    return out


if __name__ == "__main__":
    rows = compare(load(sys.argv[1]), load(sys.argv[2]))
    for e, state, text in rows:
        print(f"{e:<10} {state:<9} {text}")
    states = [s for _, s, _ in rows]
    print(" | ".join(f"{s} {states.count(s)}" for s in dict.fromkeys(states)))

Run .venv\Scripts\python src\shadow.py data\shadow_decisions.csv data\demo_fills.csv:

S-0001     filled    latency 1.2 s | cost vs quote +0.06 | vs chart close +0.23
S-0002     skipped   rule said no trade: spread 0.61 above 0.50
S-0003     filled    latency 0.9 s | cost vs quote +0.07 | vs chart close +0.19
S-0004     filled    latency 2.7 s | cost vs quote +0.14 | vs chart close +0.34
S-0005     no quote  decision logged without a quote: can't measure the fill against it
S-0006     rejected  requote; no retry by rule
S-0007     skipped   rule said no trade: news window
S-0008     filled    latency 0.9 s | cost vs quote +0.06 | vs chart close +0.18
S-0009     filled    latency 1.0 s | cost vs quote +0.03 | vs chart close +0.20
S-0010     missing   no demo record for this event
S-0011     stray     demo record with no shadow decision
filled 5 | skipped 2 | no quote 1 | rejected 1 | missing 1 | stray 1

What it shows:

  • The chart’s Close understates the cost. Against the quote logged at the decision, the five fills cost 0.03 to 0.14. Against the chart’s Close they cost 0.18 to 0.34, because the Close is a bid price and buys fill at the ask. A backtest priced at the Close has this gap in every trade.
  • S-0004 waited 2.7 s where the others took about a second. Measure latency on every event; one slow fill costs more than the median says.
  • S-0005 has no quote. The decision can’t be checked against a fill; fix the logger before counting the event.
  • S-0006 was rejected with a requote and not retried, as the rule says.
  • S-0010 has no demo record and S-0011 has no decision. Both need an explanation before the next run, as in the reconciliation post.

The dossier: six files

C:\trade-system-lab\capstone\
├── source-manifest.json     # URL, version, hash, licence for every source
├── data-contract.md         # symbol, timeframe, UTC, what counts as a bar
├── causal-timeline.csv      # when each series was known, from the when-known post
├── parity-report.csv        # Pine against Python, per function
├── experiment-registry.csv  # one row per try (m)
└── demo-runbook.md          # shadow only, live OFF, kill switch, resume

Anything missing is written down as missing. src/dossier_check.py lists what’s there and, above all, what isn’t:

# src/dossier_check.py: is the capstone dossier complete? Prints what's there and, above all, what's missing.
#   .venv\Scripts\python src\dossier_check.py capstone
import csv, json, sys
from pathlib import Path

REGISTRY_COLS = {"date", "version", "change", "data_sha", "trades", "mean_net_pct", "ci_low", "ci_high", "t"}
PARITY_COLS = {"function", "bars_compared", "max_abs_diff", "tolerance", "explained"}
TIMELINE_COLS = {"series", "event_time", "available_at_utc", "used_from_bar"}


def rows(p):
    with open(p, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def check(folder):
    d, out = Path(folder), []
    def need(name):
        if not (d / name).exists():
            out.append(f"MISSING  {name}")
            return False
        return True
    if need("source-manifest.json"):
        for s in json.loads((d / "source-manifest.json").read_text(encoding="utf-8")):
            gaps = [k for k in ("url", "version", "sha256", "license") if not s.get(k)]
            out.append(f"{'missing ' + ', '.join(gaps) if gaps else 'ok':<8} source {s.get('name', '?')}")
    if need("data-contract.md"):
        text = (d / "data-contract.md").read_text(encoding="utf-8").lower()
        out.append(f"{'ok' if 'utc' in text else 'no UTC':<8} data-contract.md states the time zone")
    if need("causal-timeline.csv"):
        r = rows(d / "causal-timeline.csv")
        missing = TIMELINE_COLS - set(r[0]) if r else TIMELINE_COLS
        out.append(f"{'ok' if not missing else 'missing ' + ', '.join(sorted(missing)):<8} causal-timeline.csv, {len(r)} series")
    if need("parity-report.csv"):
        for r in rows(d / "parity-report.csv"):
            bad = float(r["max_abs_diff"]) > float(r["tolerance"]) and r["explained"].strip().lower() in ("", "no")
            out.append(f"{'FAIL' if bad else 'ok':<8} parity {r['function']}: max diff {r['max_abs_diff']} vs tolerance {r['tolerance']}")
    if need("experiment-registry.csv"):
        r = rows(d / "experiment-registry.csv")
        missing = REGISTRY_COLS - set(r[0]) if r else REGISTRY_COLS
        out.append(f"{'ok' if not missing else 'missing ' + ', '.join(sorted(missing)):<8} experiment-registry.csv: m = {len(r)} tries")
    if need("demo-runbook.md"):
        text = (d / "demo-runbook.md").read_text(encoding="utf-8").lower()
        for phrase in ("live: off", "kill switch", "resume"):
            out.append(f"{'ok' if phrase in text else 'missing':<8} demo-runbook.md mentions '{phrase}'")
    return out


if __name__ == "__main__":
    lines = check(sys.argv[1])
    print("\n".join(lines))
    bad = [l for l in lines if not l.startswith("ok")]
    print(f"{len(bad)} item(s) to fix or to list as missing" if bad else "complete")

On a sample dossier with gaps left in on purpose (the hashes are shortened):

ok       source xauusd_h1_utc.csv
ok       source rsi_cross.pine
missing url, version, sha256, license source cpi_release_times.csv
ok       data-contract.md states the time zone
MISSING  causal-timeline.csv
ok       parity rsi_14: max diff 0.0000 vs tolerance 0.0001
ok       parity ema_20: max diff 0.0003 vs tolerance 0.0001
FAIL     parity cross_signal: max diff 1 vs tolerance 0
ok       experiment-registry.csv: m = 4 tries
ok       demo-runbook.md mentions 'live: off'
ok       demo-runbook.md mentions 'kill switch'
ok       demo-runbook.md mentions 'resume'
3 item(s) to fix or to list as missing

Three things to fix or list as missing. The release-time file has no source or licence, the causal timeline doesn’t exist yet, and the Pine and Python cross signals disagree on at least one bar with no explanation. The ema_20 row passes although it’s above the tolerance, because the difference is traced to one cause: Pine seeds the average differently for the first bars. A tolerance is passed by an explained difference, never by widening it until the signals stop disagreeing.

The tests, tests/test_capstone.py:

# tests/test_capstone.py: the verdicts, the threshold, the naive forecast, the shadow comparison and the dossier check.
import json

from src.ablation import t_threshold, verdict
from src.dossier_check import check
from src.naive_mae import ema, mae
from src.shadow import compare


def test_verdicts():
    assert verdict(-0.20, -0.01, -2.5, 2.4).startswith("entirely below 0")
    assert verdict(-0.10, 0.05, -0.8, 2.4).startswith("contains 0")
    assert verdict(0.01, 0.20, 2.1, 2.4).startswith("above 0 but t below")


def test_threshold_rises_with_m():
    assert round(t_threshold(1), 2) == 1.96 and t_threshold(3) > t_threshold(1) and t_threshold(10) > t_threshold(3)


def test_naive_beats_a_lagging_average_on_a_trend():
    c = [float(i) for i in range(100)]                 # a steady trend: EMA lags it
    assert mae(c, c)[0] == 1.0 and mae(c, ema(c, 20))[0] > 1.0


def test_dossier_lists_what_is_missing(tmp_path):
    (tmp_path / "source-manifest.json").write_text(json.dumps([{"name": "script", "url": "u", "version": "1",
                                                                "sha256": "", "license": "MIT"}]))
    (tmp_path / "parity-report.csv").write_text("function,bars_compared,max_abs_diff,tolerance,explained\n"
                                                "rsi,500,0.3,0.01,no\n")
    out = check(tmp_path)
    assert "missing sha256 source script" in out
    assert any(l.startswith("FAIL") and "rsi" in l for l in out)
    assert "MISSING  demo-runbook.md" in out and "MISSING  experiment-registry.csv" in out


def test_shadow_measures_against_the_quote_and_reports_gaps():
    d = [dict(event_id="S1", decided_at_utc="2026-12-01T08:00:01Z", decision="buy", reason="", chart_close="100.00",
              quote_bid="100.10", quote_ask="100.30"),
         dict(event_id="S2", decided_at_utc="2026-12-01T09:00:01Z", decision="sell", reason="", chart_close="101.00",
              quote_bid="", quote_ask="")]
    f = [dict(event_id="S1", status="filled", filled_at_utc="2026-12-01T08:00:03.5Z", fill_price="100.40", note=""),
         dict(event_id="S9", status="filled", filled_at_utc="2026-12-01T10:00:00Z", fill_price="99.00", note="")]
    out = {e: (s, text) for e, s, text in compare(d, f)}
    assert out["S1"] == ("filled", "latency 2.5 s | cost vs quote +0.10 | vs chart close +0.40")
    assert out["S2"][0] == "no quote" and out["S9"][0] == "stray"

Run .venv\Scripts\python -m pytest -q tests; you should see 5 passed.

The full dossier holds the spec, the versioned code, the input manifest, the leak and duplicate tests, the reconciliation report, the pause rules and the error log. The aim of the capstone is a system you can explain, reproduce and stop in a learning environment. It doesn’t certify a profit, and it doesn’t give you permission to move to real money on your own.

Try it: plan the capstone

Plan a research capstone for a beginner from this snapshot and rulebook: [snapshot and rulebook]. The output is 6 files in a private learning folder: source-manifest.json (URL, version, hash, license), data-contract.md, causal-timeline.csv, parity-report.csv, experiment-registry.csv, demo-runbook.md. Only write independent code once the rights are verified; don't copy a dependency whose license is unclear. Port each Pine calculation to Python one at a time and check the seed, RMA, NaN, time zone and rounding first. Define a pass as a difference that is explained; don't choose a tolerance that hides a signal mismatch. Run the baseline and one ablation per component on a sealed time split, then shadow mode with no orders sent. Report everything not checked or not runnable. There is no live mode, only shadow and demo; don't read credentials, don't deploy and don't send real Telegram messages; only create a redacted report template.

Fill the [brackets] with your own details. Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.

The order to work in:

  1. Pick one small rule you can explain in words, and record its rights and licence before you port it.
  2. Compare the feature, signal and order series between Pine and Python, including warm-up, NaN, the cutoff, rounding and gaps; trace any difference back to the first bar where it appears.
  3. Hand in the baseline and ablation, the locked folds, 10 timestamped shadow events and one rollback or kill-switch case. Live stays off.

Key takeaways

  • The dossier holds the spec, versioned code, the data manifest, leak and duplicate tests, the reconciliation report, the stop rules and the error log; whatever is missing is listed as missing.
  • Ablation shows what helped on the test data, not what causes anything; report every fold and every try, not only the best version.
  • Passing the capstone means the system can be explained, reproduced and stopped in a learning environment; it doesn’t prove a profit and isn’t enough to use real money.

Comments