Episode 17 · AI Trading · Building a Complete Trading System

Shadow mode: test an agent's decisions before it proposes trades

Run an agent in shadow on post-cutoff data: fixed JSON checked by code, a baseline rule to compare, repeat runs, and a Brier score for its confidence.

How do you know an agent applies your rules correctly, and answers the same way twice, before you let it propose demo trades? Run it in shadow: it logs a decision at each checkpoint, places nothing, and code checks every answer.

This post runs a shadow batch on XAUUSD M15 candles from October 2026, validates each JSON decision with code, compares it with a baseline rule written in code, and measures repeatability. One trap up front: a high overall match rate is misleading, because both sides usually stay out. Read the checkpoints where someone traded.

Terms used below:

  • Shadow mode: the agent only logs a decision with the price at decision time and places no order. Level 1 on an autonomy ladder.
  • Baseline: a simple rule written in code, run on the same data with the same assumptions, as a ruler for the agent.
  • Out-of-sample: data never used to choose a prompt or parameter. Once you look at results and edit accordingly, it isn’t out-of-sample any more.
  • Training cutoff: the date after which the model has no training data; providers publish it on the model’s page.
  • Schema violation: an answer that breaks the required structure: not bare JSON, missing or extra fields, odd values, SL on the wrong side.
  • Repeatability: whether the same input sent several times gets the same decision.
  • Pinning a model: calling it by the full name of a fixed snapshot rather than an alias that can move to a newer one.
  • R: profit or loss in units of the SL distance: hitting SL is −1R, twice the SL distance is +2R.
  • Calibration: how well stated confidence matches observed frequency: of the times the agent says about 70%, the event should happen about 70% of the time.
  • Brier score: the mean of (forecast probability − outcome)², where the outcome is 1 if the event happened and 0 if not. 0 is best; always saying 50% scores 0.25.

Why testing an agent is harder than testing a rule

A rule written in code gives the same result on the same data every time. An agent’s “parameters” include the prompt, the model name, the enabled tools, the data you feed it, and project instruction files such as CLAUDE.md and AGENTS.md. claude -p (one turn, no back-and-forth, then exit) still loads those files like a normal session. Change any one and you have a new system, so every row below has to be recorded.

Agent parameter In this post Recorded in
Prompt prompts/decision-v1.md, unchanged for the whole batch prompt_version and prompt_hash (first 8 characters of the SHA-256; one changed letter changes it)
Model claude-sonnet-5-5, called by full name model_pinned; model_actual lists the models in the result’s modelUsage, so you see if Claude Code falls back to another model. It may also show a Haiku model, which Claude Code uses for background work
Tools All off: the agent reads no files and has no web --tools "" and --disallowedTools "mcp__*" in src/run_shadow.py; noted in the criteria file
Data 48 closed M15 candles up to the checkpoint; ema20, ema50, atr14 computed by code time_utc; data/xauusd_m15_utc.csv unchanged for the batch
Project context CLAUDE.md, AGENTS.md, .claude/settings.json, which claude -p also loads; unchanged for the batch. Auto memory (notes Claude saves on its own) lives outside the project folder, so git can’t record it: the script turns it off with CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 git_commit; auto memory off noted in the criteria file
Claude Code version Printed by claude --version; native installs update in the background, so it can change between runs claude_code; note any change in the conclusion
Number of tries Each prompt version is a try Criteria file and log; never delete old versions’ rows

Three consequences follow.

Data used to choose can’t be used to grade. Editing the prompt after seeing results on a stretch of data means you used that stretch to choose. It’s no longer out-of-sample. Try many versions and keep the best, and the best looks good partly by luck. You don’t need formulas: record how many versions you tried and grade on data you never used to choose. MT5’s Strategy Tester has a Forward mode (split 1/2, 1/3, 1/4 or a custom date) for testing chosen parameters on the later part of a period.

Models remember. Test on data after the model’s training cutoff. A model may have seen the very period you test during training, and then it answers correctly because it remembers what happened, not because it read the data: look-ahead through the model’s memory. Verbatim memorisation grows with model size, with how often a passage repeats in training data, and with longer prompts. On financial data, models have reproduced pre-cutoff economic and market figures even when told to respect the date, and showed no such recall after the cutoff. Backtests of LLM news scoring on US stocks can be skewed this way; out-of-sample the look-ahead goes away, but a distraction effect can remain, where general knowledge about a named company bends the score. That evidence comes from equities, indices, company news and macro data, not gold, FX or crypto specifically, so for those markets treat it as a strong caution.

Telling the agent not to use outside knowledge is still worth doing, but it doesn’t replace choosing post-cutoff data. Claude Fable 5.2, Opus 5.5, Sonnet 5.5 and Haiku 5.5 have a training cutoff of June 2026 (for other providers, check the model card). This post uses October 2026 candles.

Latency and cost. Every agent call takes time and plan quota or token money, and the agent decides at one price while a real order fills at a later one. On historical data the script logs the open of the candle right after the checkpoint as the price at the point, and records seconds per call. When you run forward in real time, log the real price when the decision arrives.

Period What it is
Before June 2026 Before the training cutoff: the model may remember what happened
June 2026 Training cutoff of the current Claude models
October 2026 candles Shadow batch v1: 5 Thursdays × 4 fixed times, plus points right after EMA signals
After you’ve seen the results Those 5 Thursdays are now used data, no longer out-of-sample
From mid-November 2026, say Test prompt v2 forward on a new, unused set of checkpoints

Write the criteria and pick checkpoints before running

Level 2 on the ladder is: the agent proposes, you approve, orders only on demo, through a code check layer. Move up only when you meet criteria written in advance, never because “it’s in profit”. A few dozen decisions say nothing about profit, but they’re enough to see whether the agent follows rules.

  1. Write the criteria to reports/criteria-level-2.md before the first run. The thresholds below are examples; the numbers are yours. Nothing is graded on profit or win rate.
  2. Commit it with git for a timestamp. Don’t edit it after that. If a criterion turns out unreasonable, say so in the conclusion and use the lesson for the next batch.

Checkpoints (moments where the agent must decide) come from a calendar rule, not from looking at charts:

  • Part one: the five Thursdays of October 2026 (1, 8, 15, 22, 29), each at four fixed times: 02:00, 06:00, 10:00, 14:00 UTC.
  • Part two: at fixed times the rule usually has no signal, so make_checkpoints.py adds at most two checkpoints a day, right after the first times EMA20 and EMA50 swap order. Code finds them, using data only up to that point.

That gives three kinds of case: no signal, a signal inside trading hours, a signal outside them. Thursday is a simple calendar rule, not an easy day. Once run, those five days are used data; a v2 prompt must be tested on new checkpoints, for example forward from mid-November.

Criterion Example threshold (set your own first) Where the number comes from
Shadow decisions At least 20 valid decisions on the chosen checkpoints logs/shadow.csv
Schema violations 0 in the last 10 decisions schema_violation column
Risk-rule violations 0: the agent fills in no lot; every proposal goes through the check layer schema_violation and check_layer
Match with the baseline on trade checkpoints The sample plan equals the baseline, so it must match at every point; with your own plan, every difference needs a reason you can check on the chart reports/compare.csv
Repeatability 5 checkpoints × 5 runs: at least 4 give the same action all 5 times; every varying one is reviewed src/repeatability.py
Technical and cost No unresolved errors; estimated cost per decision under your limit est_cost_usd and the terminal
cd C:\trading-agent-lab
notepad reports\criteria-level-2.md
# Criteria for level 2 · written [DATE], not edited after running
Prompt: prompts/decision-v1.md · Model: claude-sonnet-5-5 · Agent tools: all off · Auto memory: off
Data: XAUUSD M15 from MT5 demo, UTC · Plan: sample EMA-cross plan with ATR stop
Checkpoints: 5 Thursdays of 10/2026 × 02:00, 06:00, 10:00, 14:00 UTC
     + at most 2 a day right after the first EMA20/50 signals (chosen by code)
1. At least [20] valid decisions.
2. 0 schema violations in the last [10] decisions.
3. 0 proposals with a lot filled in by the agent; every proposal goes through the check layer.
4. Trade checkpoints: match the baseline at [every] point; each mismatch has a reason seen on the chart.
5. 5 checkpoints × 5 runs: at least [4] give the same action all 5 times.
6. No unresolved technical errors; estimated cost per decision under [0.05] USD.
No criterion on profit or win rate.
git add reports\criteria-level-2.md
git commit -m "Lock level 2 criteria before shadow run"

Git prints a short hash and 1 file changed. nothing to commit means the file wasn’t saved: go back to Notepad and press Ctrl + S. If Notepad can’t find the path, run mkdir reports and reopen it.

A fixed JSON decision, checked by code

The agent may return only one JSON object with 10 fields, exactly the fields the check layer accepts. action has three values: BUY, SELL or STAY_OUT (a valid decision with no trade). The agent never fills in a lot: code computes it and rounds down to 0.01, so JSON containing lot is a violation.

The plan in the prompt is a simple EMA-cross rule written out in words, with trading hours and a TP so every field is defined: EMA20 crossing EMA50 on M15; SL 2 × ATR14 from entry (ATR is the average true range, here over 14 candles); TP twice the SL distance. Entry is the last candle’s close, since the agent hasn’t seen the next candle. EMA and ATR are computed by code and handed in, the same principle as levels computed by code in a morning report.

Because the plan is fully measurable, code knows the right answer at every checkpoint. That’s deliberate: before you give an agent a plan with judgment calls in it, see how accurately it applies a clear one.

check_decision tests each answer for six things:

  1. It’s bare JSON.
  2. All 10 fields, no extras.
  3. action is valid.
  4. STAY_OUT has entry, sl, tp = null.
  5. BUY needs sl < entry < tp; SELL the reverse.
  6. Symbol, timeframe, checkpoint and prompt version are right.

Fail any one and it’s a schema violation. Don’t repair the agent’s answer, not even a small slip like wrapping the JSON in ```. The violation count is a metric to track.

Many APIs can force output to match a schema. Claude’s structured outputs use constrained decoding to make the answer fit, with two exceptions: a refusal or hitting max_tokens can produce non-matching output, and the case of enum values isn’t guaranteed. Claude Code has --json-schema for claude -p; a run without a valid result has no structured_output field. Forcing a schema still can’t check that the SL is on the right side or follows the plan. Define the output format and check it with deterministic code. This post doesn’t force a schema, so it counts exactly how often the agent gets it wrong on its own.

cd C:\trading-agent-lab
notepad prompts\decision-v1.md
notepad src\check_decision.py
.venv\Scripts\python src\check_decision.py

prompts/decision-v1.md is the prompt at the end of this post, copied verbatim and not changed by a single letter for the whole batch. Keep the bracketed placeholders ([SYMBOL], [POINT_UTC], [CANDLES_CSV] and so on): run_shadow.py fills them in at each checkpoint. Save as UTF-8.

src/check_decision.py:

# src/check_decision.py: check the agent's JSON decision with deterministic code. Never repairs the agent's answer.
import json

REQUIRED = ["time_utc", "symbol", "timeframe", "action", "entry", "sl", "tp",
            "short_reason", "data_until", "prompt_version"]   # exactly the 10 fields the check layer accepts


def _is_number(v):
    return isinstance(v, (int, float)) and not isinstance(v, bool)


def check_decision(text, expected):
    """text: what the agent returned. expected: required values of time_utc, symbol, timeframe,
    data_until, prompt_version. Returns (decision or None, list of violations; empty means valid)."""
    try:
        d = json.loads(text.strip())
    except (json.JSONDecodeError, AttributeError):
        return None, ["not bare JSON (text or ``` around it?)"]
    if not isinstance(d, dict):
        return None, ["JSON is not an object"]
    v = []
    missing = [k for k in REQUIRED if k not in d]
    extra = [k for k in d if k not in REQUIRED]
    if missing:
        v.append(f"missing fields {missing}")
    if extra:
        v.append(f"unexpected fields {extra}")           # including "lot": code computes the lot
    for k, val in expected.items():
        if d.get(k) != val:
            v.append(f"{k} must be {val}")
    act, e, sl, tp = d.get("action"), d.get("entry"), d.get("sl"), d.get("tp")
    if act == "STAY_OUT":
        if (e, sl, tp) != (None, None, None):
            v.append("STAY_OUT needs entry, sl, tp = null")
    elif act in ("BUY", "SELL"):
        if not (_is_number(e) and _is_number(sl) and _is_number(tp)):
            v.append("entry, sl, tp must be numbers")
        elif act == "BUY" and not sl < e < tp:
            v.append("BUY needs sl < entry < tp")
        elif act == "SELL" and not tp < e < sl:
            v.append("SELL needs tp < entry < sl")
    else:
        v.append(f"invalid action: {act}")
    if not isinstance(d.get("short_reason"), str) or len(d["short_reason"]) > 200:
        v.append("short_reason must be text, at most 200 characters")
    return d, v


if __name__ == "__main__":                               # self-test on 5 cases, no agent call
    exp = {"time_utc": "2026-10-08T10:00:00Z", "symbol": "XAUUSD", "timeframe": "M15",
           "data_until": "2026-10-08T10:00:00Z", "prompt_version": "decision-v1"}
    base = {**exp, "action": "STAY_OUT", "entry": None, "sl": None, "tp": None,
            "short_reason": "ema20 still below ema50"}
    cases = [(json.dumps(base), True),                                         # valid
             ("```json\n" + json.dumps(base) + "\n```", False),                # wrapped in ```
             (json.dumps({**base, "lot": 0.5}), False),                        # agent filled in a lot
             (json.dumps({**base, "action": "BUY", "entry": 100.0, "sl": 101.0, "tp": 104.0}), False),
             (json.dumps({**base, "action": "SELL", "entry": 100.0, "sl": 102.0, "tp": 96.0}), True)]
    ok = 0
    for text, want in cases:
        _, v = check_decision(text, exp)
        ok += (not v) == want
        print("valid" if not v else v)
    print(f"{ok}/{len(cases)} cases as expected")

Expected output:

valid
['not bare JSON (text or ``` around it?)']
["unexpected fields ['lot']"]
['BUY needs sl < entry < tp']
valid
5/5 cases as expected

Fewer than 5/5? Compare line by line with the file above; IndentationError means the indentation shifted when pasting.

Post-cutoff data and a baseline rule in code

You need an M15 candle file in UTC. export_m15.py reads from an open MT5 terminal logged in to a demo account; the investor (read-only) password is enough. It fetches candles from 17 August to 2 November 2026, so the indicators have more than 200 warm-up candles before 1 October. copy_rates_range returns candles whose open time falls in that range. The output has five columns: time_utc, open, high, low, close. The MetaTrader5 package is Windows 64-bit only; on a Mac use a Windows VM or VPS.

OFFSET_HOURS is how many hours the file’s times run ahead of UTC. MT5 stores candle times as broker server time, so measure it on October data, since brokers often change clocks seasonally:

  1. Run with OFFSET_HOURS = 0. Open the file in Notepad and pick a long-bodied, easy-to-recognise candle on 1 October.
  2. Find the same candle on a chart set to UTC (TradingView with its time zone set to UTC works). Don’t compare with the MT5 chart: it shows server time, so it can’t tell you the offset from UTC.
  3. File time minus the candle’s UTC time is the offset.
  4. Repeat with a candle on 29 October.
  5. If the two match, set OFFSET_HOURS. If not, the broker changed clocks mid-month: put the 1 October number in OFFSET_HOURS and the 29 October number in OFFSET_HOURS_AFTER.
  6. Only if you set OFFSET_HOURS_AFTER: SWITCH is Sunday 25 October 2026, the European clock change. Check a 22 October candle too; if it’s already off like 29 October, move SWITCH to the Sunday before the first Thursday that’s off.
  7. Rerun export_m15.py.

src/candles.py is the deterministic core. It computes EMA20 and EMA50 (seeded with a simple mean) and a Wilder ATR14, then rounds the indicators to exactly the digits the agent will see, so the baseline and the agent use the same numbers. baseline returns the sample plan’s answer at a checkpoint. after_n records what happened in the 16 M15 candles (4 hours) after it: SL first, TP first, neither, or undetermined. Why undetermined? OHLC candles don’t say which level was touched first when both SL and TP sit inside one candle, so that case is recorded as undetermined instead of guessed.

src/make_checkpoints.py applies the checkpoint rule and writes reports/checkpoints.csv. Read that list in Notepad, not on a chart. Then commit the code and the list: that commit hash is the version of the whole context, and the shadow script writes it to every log row.

cd C:\trading-agent-lab
notepad src\export_m15.py
notepad src\candles.py
notepad src\make_checkpoints.py
.venv\Scripts\python src\export_m15.py
.venv\Scripts\python src\make_checkpoints.py
notepad reports\checkpoints.csv

export_m15.py prints the candle count (several thousand), the first candle time (around 17 August 2026) and the last (around 30 October to 1 November). A much later first candle means the terminal hasn’t downloaded enough history: open an M15 chart of the symbol, scroll back to August 2026, and rerun. make_checkpoints.py usually prints 20 to 30 checkpoints.

src/export_m15.py:

# src/export_m15.py: export M15 candles from an MT5 demo to a UTC CSV. Read only, sends no orders.
# Run with the MT5 terminal open and logged in to a demo (the investor password is enough).
import csv
import os
from datetime import datetime, timedelta, timezone

import MetaTrader5 as mt5

SYMBOL = os.environ.get("TL_SYMBOL", "XAUUSD")    # the broker's name may carry a suffix
OUT = "data/xauusd_m15_utc.csv"                   # rename if you export another symbol
OFFSET_HOURS = 0       # hours the file's clock runs ahead of UTC, measured on a 1 October candle
OFFSET_HOURS_AFTER = None   # fill in only if a 29 October candle is off by a different amount
SWITCH = datetime(2026, 10, 25, tzinfo=timezone.utc)   # Sunday of the European clock change; market closed
FROM = datetime(2026, 8, 17, tzinfo=timezone.utc)  # early, so indicators get 200+ warm-up candles
TO = datetime(2026, 11, 2, tzinfo=timezone.utc)

path = os.environ.get("TL_MT5_PATH", "").strip('"')   # only needed with several terminals installed
if not (mt5.initialize(path) if path else mt5.initialize()):
    raise SystemExit(f"initialize() error: {mt5.last_error()}")
try:
    acc = mt5.account_info()
    if acc is None or acc.trade_mode != mt5.ACCOUNT_TRADE_MODE_DEMO:
        raise SystemExit("STOP: the terminal is not logged in to a demo account.")
    mt5.symbol_select(SYMBOL, True)               # show the symbol in Market Watch if hidden
    rates = mt5.copy_rates_range(SYMBOL, mt5.TIMEFRAME_M15, FROM, TO)
    err = mt5.last_error()
finally:
    mt5.shutdown()
if rates is None or len(rates) == 0:
    raise SystemExit(f"Could not get {SYMBOL} candles: {err}")

rows = []
for r in rates:
    t = datetime.fromtimestamp(int(r["time"]), timezone.utc)
    off = OFFSET_HOURS if OFFSET_HOURS_AFTER is None or t < SWITCH else OFFSET_HOURS_AFTER
    t -= timedelta(hours=off)
    rows.append([t.strftime("%Y-%m-%dT%H:%M:%SZ"), float(r["open"]), float(r["high"]),
                 float(r["low"]), float(r["close"])])
os.makedirs("data", exist_ok=True)
with open(OUT, "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f)
    w.writerow(["time_utc", "open", "high", "low", "close"])
    w.writerows(rows)
print(len(rows), "M15 candles written to", OUT, "| first", rows[0][0], "| last", rows[-1][0])

src/candles.py:

# src/candles.py: read UTC M15 candles, compute EMA20, EMA50, ATR14, the baseline EMA-cross rule,
# and what happened in the N candles after a checkpoint. No network, no orders.
import csv
from datetime import datetime, timedelta

MINUTES = 15                       # M15
FMT = "%Y-%m-%dT%H:%M:%SZ"


def _ema(prices, n):
    out = [None] * len(prices)
    if len(prices) >= n:
        out[n - 1] = sum(prices[:n]) / n                # seeded with the simple mean of the first n
        for i in range(n, len(prices)):
            out[i] = out[i - 1] + 2 / (n + 1) * (prices[i] - out[i - 1])
    return out


def _atr(c, n=14):
    tr = [c[0]["h"] - c[0]["l"]] + [
        max(x["h"] - x["l"], abs(x["h"] - p["c"]), abs(x["l"] - p["c"])) for p, x in zip(c, c[1:])]
    out = [None] * len(tr)
    if len(tr) >= n:
        out[n - 1] = sum(tr[:n]) / n
        for i in range(n, len(tr)):
            out[i] = (out[i - 1] * (n - 1) + tr[i]) / n  # Wilder smoothing
    return out


def read_candles(path, decimals=2):
    """List of candles; ema20, ema50, atr14 rounded exactly as the agent will see them."""
    with open(path, encoding="utf-8-sig") as f:
        c = [{"time_utc": r["time_utc"], "o": float(r["open"]), "h": float(r["high"]),
              "l": float(r["low"]), "c": float(r["close"])} for r in csv.DictReader(f)]
    closes = [x["c"] for x in c]
    ind = {"ema20": _ema(closes, 20), "ema50": _ema(closes, 50), "atr14": _atr(c)}
    for i, x in enumerate(c):
        opened = datetime.strptime(x["time_utc"], FMT)
        x["closed_at"] = (opened + timedelta(minutes=MINUTES)).strftime(FMT)
        for name, series in ind.items():
            x[name] = None if series[i] is None else round(series[i], decimals + 1)
    return c


def baseline(c, i, decimals=2, hours=(7, 17)):
    """Deterministic answer of the sample plan at just-closed candle i."""
    p, x = c[i - 1], c[i]
    out = {"action": "STAY_OUT", "entry": None, "sl": None, "tp": None}
    if None in (p["ema50"], x["ema50"], x["atr14"]) or x["atr14"] <= 0:
        return out
    hm = (int(x["closed_at"][11:13]), int(x["closed_at"][14:16]))
    if not (hours[0], 0) <= hm <= (hours[1], 0):
        return out                                    # outside the plan's hours
    if p["ema20"] <= p["ema50"] and x["ema20"] > x["ema50"]:
        k = 1
    elif p["ema20"] >= p["ema50"] and x["ema20"] < x["ema50"]:
        k = -1
    else:
        return out
    e = x["c"]
    return {"action": "BUY" if k == 1 else "SELL", "entry": round(e, decimals),
            "sl": round(e - k * 2 * x["atr14"], decimals), "tp": round(e + k * 4 * x["atr14"], decimals)}


def after_n(c, i, d, n=16):
    """What happened in the n candles after the checkpoint for decision d's SL and TP. Returns (text, R or None)."""
    if d.get("action") not in ("BUY", "SELL"):
        return "", None
    k = 1 if d["action"] == "BUY" else -1
    e, sl, tp = d["entry"], d["sl"], d["tp"]
    nxt = c[i + 1:i + 1 + n]
    if len(nxt) < n:
        return "missing data", None
    for x in nxt:
        hit_sl = x["l"] <= sl if k == 1 else x["h"] >= sl
        hit_tp = x["h"] >= tp if k == 1 else x["l"] <= tp
        if hit_sl and hit_tp:
            return "undetermined: SL and TP in the same candle", None
        if hit_sl:
            return "SL first", -1.0
        if hit_tp:
            return "TP first", round(abs(tp - e) / abs(e - sl), 2)
    return f"neither after {n} candles", round(k * (nxt[-1]["c"] - e) / abs(e - sl), 2)

src/make_checkpoints.py:

# src/make_checkpoints.py: build the checkpoint list from the rule written in the criteria. No chart needed.
import csv
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))                    # so src.* imports work when run as python src/...
from src.candles import read_candles, baseline

DAYS = ["2026-10-01", "2026-10-08", "2026-10-15", "2026-10-22", "2026-10-29"]   # 5 Thursdays
HOURS = ["02:00", "06:00", "10:00", "14:00"]                                     # fixed UTC times
MAX_SIGNALS = 2                                  # per day, at most 2 extra checkpoints right after the first signals
DECIMALS = 2                                     # price decimals; EURUSD is 5

c = read_candles(ROOT / "data" / "xauusd_m15_utc.csv", DECIMALS)
points = {f"{d}T{h}:00Z": "fixed_time" for d in DAYS for h in HOURS}
for d in DAYS:
    taken = 0
    for i in range(200, len(c)):                 # skip the first 200 candles so indicators settle
        if taken == MAX_SIGNALS or not c[i]["closed_at"].startswith(d):
            continue
        if baseline(c, i, DECIMALS, hours=(0, 24))["action"] != "STAY_OUT":   # EMA20/50 just swapped order
            points.setdefault(c[i]["closed_at"], "after_signal")
            taken += 1
(ROOT / "reports").mkdir(exist_ok=True)
with open(ROOT / "reports" / "checkpoints.csv", "w", newline="", encoding="utf-8-sig") as f:
    w = csv.writer(f)
    w.writerow(["time_utc", "kind"])
    w.writerows(sorted(points.items()))
print(len(points), "checkpoints written to reports/checkpoints.csv")
git add -A
git commit -m "Add shadow code and pre-chosen checkpoints"

Running the shadow batch

For each checkpoint the script:

  1. Cuts the candles closed up to the checkpoint (48 M15 candles) and skips checkpoints with no candle closing exactly then.
  2. Fills in prompts/decision-v1.md, unchanged for the whole batch.
  3. Calls claude -p with the pinned model, all tools off and auto memory off. The agent can’t open the data file containing candles after the checkpoint, can’t go online, and can’t read notes kept outside git.
  4. Checks the answer with check_decision. One failed condition is a schema violation; no repairs.
  5. Sends valid BUY or SELL proposals through the check layer, which computes the lot from an assumed 2,000 USD demo balance.
  6. Writes one row to logs/shadow.csv: price at the point, decision, violations, check-layer result, prompt version and hash, model, commit, estimated cost and seconds. Raw output of each call goes to logs/raw.

You need: Windows with an MT5 demo, the .venv environment, Claude Code logged in with a subscription plan, and src/lot.py and src/check_proposal.py (the round-down lot function and the check layer). No API key and no order connection.

Before running, make sure ANTHROPIC_API_KEY isn’t set: -p runs always use it when present, which bills the API instead of your plan. The script stops if it sees the variable. Run claude -p only in your own folder: -p runs show no folder-trust dialog, yet still run hooks and connect MCP servers declared in the project.

est_cost_usd comes from total_cost_usd, Claude Code’s own local estimate, which may differ from the invoice. On a subscription, runs draw from your plan quota; check with /usage in Claude Code.

On a technical error (network down, not logged in, quota reached) the script prints the reason and stops; no retry loop. Fix the cause and rerun the same command: checkpoints already in the log are skipped.

cd C:\trading-agent-lab
notepad src\run_shadow.py
Test-Path Env:ANTHROPIC_API_KEY
.venv\Scripts\python src\run_shadow.py

Test-Path should print False. If it prints True, remove the variable first. Each checkpoint prints a line such as 2026-10-01T10:00:00Z run 1 -> STAY_OUT, -> BUY passed, lot 0.01, or -> VIOLATION: .... A first batch has 20 to 30 checkpoints; each call takes a while (the seconds column records it). Don’t close the window while it runs.

src/run_shadow.py:

# src/run_shadow.py: shadow mode. The agent only logs decisions; NO order is ever placed.
# First run (all checkpoints):   .venv/Scripts/python src/run_shadow.py
# Repeat 5 checkpoints 5 times:  .venv/Scripts/python src/run_shadow.py --repeat 5 --kind after_signal --limit 5
import argparse
import csv
import hashlib
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))                    # so src.* imports work when run as python src/...
from src.candles import read_candles
from src.check_decision import check_decision
from src.check_proposal import check_proposal    # the check layer: code computes the lot

SYMBOL, TIMEFRAME, DECIMALS = "XAUUSD", "M15", 2
DATA = ROOT / "data" / "xauusd_m15_utc.csv"
CHECKPOINTS = ROOT / "reports" / "checkpoints.csv"
PROMPT = ROOT / "prompts" / "decision-v1.md"
VERSION = "decision-v1"
MODEL = "claude-sonnet-5-5"      # full pinned name; not the alias "sonnet"
N_CANDLES = 48                   # closed candles given to the agent
BALANCE = 2000                   # assumed demo balance for the check layer's lot
LOG = ROOT / "logs" / "shadow.csv"
COLS = ["time_utc", "kind", "run", "price_at_point", "action", "entry", "sl", "tp", "short_reason",
        "schema_violation", "check_layer", "prompt_version", "prompt_hash", "model_pinned",
        "model_actual", "claude_code", "git_commit", "est_cost_usd", "seconds", "raw_file"]
CLAUDE = shutil.which("claude")
ENV = {**os.environ, "CLAUDE_CODE_DISABLE_AUTO_MEMORY": "1"}   # auto memory lives outside git: turn it off


def run(cmd, stdin=None):
    return subprocess.run(cmd, input=stdin, capture_output=True, text=True,
                          encoding="utf-8", timeout=600, cwd=ROOT, env=ENV)


def cut_to_point(c, point):
    """Only candles CLOSED by the checkpoint. Returns (index of the last candle, CSV block) or (None, reason)."""
    idx = [j for j, x in enumerate(c) if x["closed_at"] <= point]
    if not idx or c[idx[-1]]["closed_at"] != point:
        return None, "no candle closes exactly at the checkpoint (market closed or missing data)"
    i = idx[-1]
    if i < 200 or i + 1 >= len(c):
        return None, "not enough warm-up candles, or no candle after the checkpoint"
    block = ["time_utc,open,high,low,close,ema20,ema50,atr14"]
    for x in c[i - N_CANDLES + 1:i + 1]:
        block.append(",".join([x["time_utc"]] + [str(x[k]) for k in ("o", "h", "l", "c", "ema20", "ema50", "atr14")]))
    return i, "\n".join(block)


def log_row(row):
    new = not LOG.exists()
    with open(LOG, "a", newline="", encoding="utf-8-sig") as f:
        w = csv.DictWriter(f, fieldnames=COLS)
        if new:
            w.writeheader()
        w.writerow(row)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--repeat", type=int, default=1, help="runs per checkpoint")
    ap.add_argument("--kind", default="", help="only checkpoints of this kind, e.g. after_signal")
    ap.add_argument("--limit", type=int, default=0, help="only the first N checkpoints; 0 means all")
    a = ap.parse_args()
    if os.environ.get("ANTHROPIC_API_KEY"):
        sys.exit("ANTHROPIC_API_KEY is set: claude -p would use it and bill the API. Remove the variable first.")
    if CLAUDE is None:
        sys.exit("claude command not found. Open a new terminal; if it persists, fix PATH.")
    template = PROMPT.read_text(encoding="utf-8-sig")
    prompt_hash = hashlib.sha256(template.encode("utf-8")).hexdigest()[:8]
    cc_version = run([CLAUDE, "--version"]).stdout.strip()
    try:
        git = run(["git", "rev-parse", "--short", "HEAD"]).stdout.strip() or "not-committed"
    except OSError:
        git = "no-git"
    c = read_candles(DATA, DECIMALS)
    with open(CHECKPOINTS, encoding="utf-8-sig") as f:
        points = [r for r in csv.DictReader(f) if not a.kind or r["kind"] == a.kind]
    if a.limit:
        points = points[:a.limit]
    done = set()
    if LOG.exists():
        with open(LOG, encoding="utf-8-sig") as f:
            done = {(r["time_utc"], r["run"], r["prompt_version"]) for r in csv.DictReader(f)}
    (ROOT / "logs" / "raw").mkdir(parents=True, exist_ok=True)
    for n in range(1, a.repeat + 1):
        for p in points:
            point = p["time_utc"]
            if (point, str(n), VERSION) in done:
                continue                         # already logged: skip, so a rerun is safe
            i, block = cut_to_point(c, point)
            if i is None:
                print("Skipping", point, "-", block)
                continue
            text = template
            for k, v in {"[SYMBOL]": SYMBOL, "[TIMEFRAME]": TIMEFRAME, "[DECIMALS]": str(DECIMALS),
                         "[POINT_UTC]": point, "[SOURCE]": DATA.name, "[VERSION]": VERSION,
                         "[CANDLES_CSV]": block}.items():
                text = text.replace(k, v)
            start = time.time()
            try:                                 # --tools "": no tools at all, the agent can't read files or go online
                res = run([CLAUDE, "-p", "Follow the instructions in the attached content exactly. Return only one JSON object.",
                           "--model", MODEL, "--output-format", "json", "--tools", "",
                           "--disallowedTools", "mcp__*", "--permission-mode", "default"], text)
            except subprocess.TimeoutExpired:
                sys.exit(f"No answer after 600 seconds at {point}: stop, check the network, then rerun.")
            secs = round(time.time() - start, 1)
            raw = ROOT / "logs" / "raw" / f"{point.replace(':', '-')}_run{n}.json"
            raw.write_text(res.stdout, encoding="utf-8")
            try:
                out = json.loads(res.stdout)
            except json.JSONDecodeError:
                out = {}
            if res.returncode != 0 or out.get("is_error") or "result" not in out:
                print("Technical error at", point, "- stopping, no retry loop.")
                print(str(out.get("result") or res.stderr or res.stdout)[:400])
                sys.exit(1)
            d, violations = check_decision(out["result"], {"time_utc": point, "symbol": SYMBOL, "timeframe": TIMEFRAME,
                                                           "data_until": point, "prompt_version": VERSION})
            layer = ""
            if not violations and d["action"] != "STAY_OUT":
                ok, reasons, lot = check_proposal(d, BALANCE)
                layer = f"passed, lot {lot}" if ok else "blocked: " + "; ".join(reasons)
            valid = d if (d and not violations) else {}
            log_row({"time_utc": point, "kind": p["kind"], "run": n, "price_at_point": c[i + 1]["o"],
                     "action": valid.get("action", ""), "entry": valid.get("entry"),
                     "sl": valid.get("sl"), "tp": valid.get("tp"), "short_reason": valid.get("short_reason", ""),
                     "schema_violation": "; ".join(violations), "check_layer": layer, "prompt_version": VERSION,
                     "prompt_hash": prompt_hash, "model_pinned": MODEL,
                     "model_actual": ",".join(out.get("modelUsage") or {}) or "unknown",
                     "claude_code": cc_version, "git_commit": git,
                     "est_cost_usd": out.get("total_cost_usd", ""), "seconds": secs,
                     "raw_file": raw.relative_to(ROOT).as_posix()})
            print(point, "run", n, "->", valid.get("action") or "VIOLATION: " + "; ".join(violations), layer)
    print("Done. Log in logs/shadow.csv. Simulation on historical data, not investment advice.")


if __name__ == "__main__":
    main()
You see Cause Fix
claude command not found This PowerShell window doesn’t have Claude Code’s PATH Open a new window; if it persists, add the install folder to PATH
ANTHROPIC_API_KEY is set ... The variable is still in this window Remove it, open a new window, rerun Test-Path Env:ANTHROPIC_API_KEY until it prints False
No module named 'src.check_proposal' or 'src.lot' Those files are missing, or you’re in the wrong folder Create them; cd C:\trading-agent-lab and rerun
No module named 'MetaTrader5' Not installed in .venv .venv\Scripts\python -m pip install MetaTrader5
initialize() error MT5 not open or not logged in Open MT5, log in to the demo, rerun
STOP: the terminal is not logged in to a demo account A live account is open, or the script attached to the wrong terminal Log in to the demo; with several terminals set $env:TL_MT5_PATH
Could not get XAUUSD candles The broker’s symbol has a suffix, or history isn’t downloaded $env:TL_SYMBOL = "the right name" and rerun in the same window; open an M15 chart and scroll back to August 2026
FileNotFoundError for xauusd_m15_utc.csv or checkpoints.csv The previous section wasn’t run Run export_m15.py, then make_checkpoints.py
Skipping ... no candle closes exactly at the checkpoint Market closed or data missing at that time Note it in the conclusion; don’t substitute another checkpoint
Technical error at ... mentioning login or limits Claude Code not logged in, or plan quota reached Run claude once to log in, or wait for the quota to reset; then rerun the same command
Many VIOLATION: not bare JSON The agent adds text or ``` around the JSON Don’t edit the log or the prompt mid-batch; note it and fix it in v2

Compare with the baseline

src/compare.py computes the baseline decision at each checkpoint, pairs it with the agent’s run-1 decision, writes reports/compare.csv and prints a summary. Read it in this order:

  1. Schema violations first.
  2. Then the match count, but don’t stop at the total. At fixed times both sides usually stay out, so an agent that always stays out matches almost everything.
  3. The number that matters: checkpoints with a trade on at least one side, and how many of those match.
  4. Every mismatch. With the sample plan, every mismatch is a rule-application error: open the chart and see which column the agent misread or whether it ignored the trading hours. With your own plan, every difference needs a reason you can check on the chart.

The script prints mean R and maximum drawdown of the hypothetical trades only when there are some. With a handful of trades those are almost pure noise; the trade count needed before a mean R means anything is a separate question. No win rate.

Three evaluation questions. Does the agent follow your own rules, such as the trading hours and never filling in a lot? Where it differs from the baseline, can you verify the reason on the chart? If it’s no better than a simple rule on compliance and risk, what does it add: time saved, record keeping, or nothing yet?

cd C:\trading-agent-lab
notepad src\compare.py
.venv\Scripts\python src\compare.py
notepad reports\compare.csv

Open the CSV in Excel to look only; don’t save over it, since Excel can change time and number formats.

src/compare.py:

# src/compare.py: compare the agent's decisions (run 1) with the baseline rule and what happened after N candles.
# Reads data/ and logs/ only, writes reports/compare.csv. Calls no agent, sends no orders.
import csv
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src.candles import read_candles, baseline, after_n

DECIMALS, N = 2, 16                              # 16 M15 candles = 4 hours
VERSION = "decision-v1"
c = read_candles(ROOT / "data" / "xauusd_m15_utc.csv", DECIMALS)
pos = {x["closed_at"]: i for i, x in enumerate(c)}
with open(ROOT / "logs" / "shadow.csv", encoding="utf-8-sig") as f:
    log = [r for r in csv.DictReader(f) if r["run"] == "1" and r["prompt_version"] == VERSION]


def num(v):
    return float(v) if v not in ("", None) else None


def max_drawdown(rs):
    """Largest drawdown of the cumulative R series, in time order."""
    peak = cum = dd = 0.0
    for r in rs:
        cum += r
        peak = max(peak, cum)
        dd = max(dd, peak - cum)
    return dd


table, r_agent, r_base = [], [], []
for r in log:
    i = pos[r["time_utc"]]
    base = baseline(c, i, DECIMALS)
    valid = r["schema_violation"] == ""
    ag = {"action": r["action"], "entry": num(r["entry"]), "sl": num(r["sl"]), "tp": num(r["tp"])}
    text_a, ra = after_n(c, i, ag, N) if valid else ("", None)
    text_b, rb = after_n(c, i, base, N)
    sl_diff = ""
    if valid and ag["action"] == base["action"] and base["sl"] is not None:
        sl_diff = round(ag["sl"] - base["sl"], DECIMALS)
    table.append({"time_utc": r["time_utc"], "kind": r["kind"], "price_at_point": r["price_at_point"],
                  "agent": r["action"] if valid else "VIOLATION", "baseline": base["action"],
                  "match": ("yes" if r["action"] == base["action"] else "no") if valid else "no",
                  "sl_diff": sl_diff, "agent_reason": r["short_reason"] or r["schema_violation"],
                  f"after_{N}_agent": text_a, f"after_{N}_baseline": text_b})
    if ra is not None:
        r_agent.append(ra)
    if rb is not None:
        r_base.append(rb)

with open(ROOT / "reports" / "compare.csv", "w", newline="", encoding="utf-8-sig") as f:
    w = csv.DictWriter(f, fieldnames=list(table[0]))
    w.writeheader()
    w.writerows(table)

traded = [t for t in table if t["agent"] in ("BUY", "SELL") or t["baseline"] in ("BUY", "SELL")]
print("Checkpoints:", len(table), "| schema violations:", sum(t["agent"] == "VIOLATION" for t in table))
print("Match baseline:", sum(t["match"] == "yes" for t in table), "/", len(table))
print("Checkpoints with a trade on either side:", len(traded), "| matching among them:",
      sum(t["match"] == "yes" for t in traded))
print("Proposals blocked by the check layer:", sum(r["check_layer"].startswith("blocked") for r in log))
for name, rs in (("agent", r_agent), ("baseline", r_base)):
    if rs:
        print(f"Hypothetical trades, {name}: {len(rs)}, mean R {sum(rs) / len(rs):.2f}, "
              f"max drawdown {max_drawdown(rs):.2f}R")
cost = [float(r["est_cost_usd"]) for r in log if r["est_cost_usd"]]
if cost:
    print(f"Mean estimated cost per decision: {sum(cost) / len(cost):.4f} USD")
print("Detail: reports/compare.csv. Simulation on historical data, not investment advice.")
Column Meaning
time_utc Checkpoint in UTC
kind fixed_time or after_signal
price_at_point Open of the candle right after the checkpoint: the earliest possible fill
agent, baseline Each side’s decision; VIOLATION is an answer that broke the schema
match yes or no; a schema violation counts as no
sl_diff Agent SL minus baseline SL when both trade the same way; non-zero means the agent miscalculated
agent_reason The agent’s short reason, or the violation
after_16_agent, after_16_baseline SL first, TP first, neither, or undetermined when SL and TP share a candle

To see a mismatch with your own eyes, open the checkpoint on any chart set to UTC, or a bar-replay tool, after the whole batch has run. Stop at the last M15 candle before the checkpoint (for a 10:00 UTC checkpoint, the candle that opened at 09:45). Optionally, play third player: decide by the plan yourself and write it to reports/my-decisions.txt before going on. Then step forward 16 candles and compare with the two after_16 columns. A replay tool’s price feed can differ slightly from your demo broker: use the chart to look, and the CSV numbers to grade.

Reading the comparison
Misleading Total match count: at fixed times both sides usually stay out, so an always-out agent matches almost everything
Read this Schema violations first; checkpoints with a trade on either side and the matches among them; every mismatch on the chart; a non-zero sl_diff means a miscalculation
Don’t conclude from Win rate; mean R of a few trades, which is almost noise; the feeling of “being in profit”

Repeatability, pinning the model, and temperature

Repeatability is whether the same input gets the same decision. To measure it:

  1. The repeat command below resends the exact prompt of the first five after_signal checkpoints four more times (fewer if there are fewer such checkpoints). Each is a fresh claude -p run with no memory of the last.
  2. src/repeatability.py counts actions per checkpoint.
  3. For any checkpoint that varies, open its files in logs/raw and read each run’s reason.

Fixes: state the rule more clearly in the plan, tighten the schema, or take a majority vote over several runs, which costs more quota. Every fix creates a new version (of the prompt or of how the agent is called) and must be tested on new checkpoints.

Sampling parameters such as temperature are no longer the main way to make answers stable. On Claude API version 2026-10-21, a request sending temperature, top_p or top_k gets a 400 error, even at default values, and models from Claude 4.7 on only ever accepted the defaults. For models that still take other values, such as Claude Sonnet 4.6, lowering temperature to stabilise answers stops working, with no replacement setting. Gemini 4 and Gemini 3.6 and later ignore custom temperature, top_p and top_k. Stability has to come from clear data, clear rules and a schema.

Pin the model by full name, such as claude-sonnet-5-5. In Claude Code, aliases such as sonnet or opus point to the recommended version and change over time. Every Claude model ID is a fixed snapshot. The same advice holds for other providers: pin a snapshot and keep a test suite for when you change versions.

Recheck in two cases: the provider changes or retires a model, or model_actual shows a model other than the pinned one and the background Haiku. Then go back to shadow and rerun this test suite on new checkpoints before continuing. That’s model drift: models changing over time.

cd C:\trading-agent-lab
notepad src\repeatability.py
.venv\Scripts\python src\run_shadow.py --repeat 5 --kind after_signal --limit 5
.venv\Scripts\python src\repeatability.py

The repeat command prints about 20 more lines (runs 2 to 5; run 1 is already logged and skipped). The last command prints one line per checkpoint: the checkpoint, prompt version, the count of each action, then stable or a variation such as varies: 4/5 the same.

src/repeatability.py:

# src/repeatability.py: same input, same action? Reads the log only; calls no agent.
import collections
import csv
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
groups = collections.defaultdict(list)
with open(ROOT / "logs" / "shadow.csv", encoding="utf-8-sig") as f:
    for r in csv.DictReader(f):
        key = (r["time_utc"], r["prompt_version"], r["model_pinned"])
        groups[key].append(r["action"] if r["schema_violation"] == "" else "VIOLATION")
for (point, prompt, model), res in sorted(groups.items()):
    if len(res) < 2:
        continue                                  # run only once: nothing to measure yet
    count = collections.Counter(res)
    top = count.most_common(1)[0][1]
    print(point, prompt, dict(count), "stable" if top == len(res) else f"varies: {top}/{len(res)} the same")
Where What it says about sampling or versions What you do
Claude API, version 2026-10-21 temperature, top_p, top_k give a 400 error, even at defaults; Claude 4.7 and later only accepted defaults Don’t rely on temperature; stabilise with data, rules, schema
Gemini 4 and 3.6 or later Custom temperature, top_p, top_k are ignored; older Gemini 3 versions should keep defaults Remove these parameters from your config
Claude Code sonnet, opus aliases change over time; full names pin Use --model with the full name and log it
Other providers Pin a model snapshot and keep evals for version changes A model change means rerunning this test suite

A second case: an open-source agent team

Some tools build a whole agent team: analysts, bull and bear researchers who debate, a research manager who settles the debate, a trader, three risk debaters and a portfolio manager. TradingAgents is an open-source example under Apache-2.0; its README says it’s designed for research and isn’t financial, investment or trading advice.

Putting an agent team in shadow follows the same steps: lock parameters, pick post-cutoff checkpoints, log decisions, compare with a baseline, measure repeatability. The table below is what reading the source of version 0.7.1 (released 27 October 2026) shows. I haven’t installed or run it.

Item What the source and README show What it means here
Purpose Apache-2.0; research only, not advice Shadow only; never wire it into a demo order flow
Install Python 3.11+; yfinance is a hard dependency Vet it before installing
Pinning deep_think_llm for the research and portfolio managers, quick_think_llm for the rest; or TRADINGAGENTS_DEEP_THINK_LLM, TRADINGAGENTS_QUICK_THINK_LLM Full snapshot names, recorded in the criteria file
Local model llm_provider = ollama, default http://localhost:11434/v1 With Ollama on your own machine and a model without a :cloud suffix, prompts stay local; data sources still go to the internet
Model login A provider API key; or ChatGPT Plus/Pro via tradingagents login chatgpt (Sign in with ChatGPT, preview). Each run draws on the plan; the token sits in ~/.tradingagents/chatgpt-auth.json, and any program that can read that file can use your plan Prefer an API key with a spend cap, or Ollama. If you use the plan, block agents from that file as you would .env, and tradingagents logout chatgpt when done
Broker Only a simulated exchange; no broker module Leave it that way; don’t add an order path
Output Five-step scale Buy, Overweight, Hold, Underweight, Sell, or REVIEW; entry, stop and target are optional; no % confidence Nothing to Brier-score; log the level as is
Memory Always on; each run reads past decisions with their P&L One log file per batch via TRADINGAGENTS_MEMORY_LOG_PATH; run days in time order
Data Daily prices via Alpha Vantage use TIME_SERIES_DAILY_ADJUSTED, a premium endpoint; the market snapshot tool always uses yfinance; XAUUSD becomes GC=F (gold futures), not your CFD No route for XAUUSD that avoids yfinance
Keys Alpha Vantage only takes the key as an apikey URL parameter Acceptable only when your own code reads the key from the environment and never prints or logs the URL; third-party code must be audited for every place it prints a URL
Sentiment analyst (on by default) Reads Reddit through search RSS and StockTwits’ unauthenticated stream on every run Reddit’s terms forbid automated collection without written consent, and StockTwits only allows it with permission or an approved API. Dropping the news analyst isn’t enough
News and social Content changes over time, even for past dates; sources keep only recent posts; runs are per day (data to the end of day D, UTC, including day D’s candle) Inputs can’t be locked, so repeatability can’t be measured. Keep only market in selected_analysts, or run forward only and save each run; for intraday checkpoints use the previous day
Built-in scoring Excess return vs SPY after 5 sessions Doesn’t fit this post’s grading. Write a mapping into the criteria file first, e.g. Buy/Overweight → BUY, Underweight/Sell → SELL, Hold → STAY_OUT, REVIEW → violation; entry at the next D1 close; SL 2 × D1 ATR14; TP twice the SL; graded over the next 5 D1 candles

Because prices go through yfinance (an unofficial library over Yahoo data), the sentiment analyst scrapes Reddit against its terms, and the news analyst reads prediction markets, I don’t run this framework. Reading the source to learn where the data really comes from is exactly the vetting step to do before installing anything.

Scoring “confidence 70%” with a Brier score

When an agent writes “confidence 70%”, the number only means something if, of the times it says about 70%, the event happens about 70% of the time. Language models stating confidence in words tend to be overconfident.

The Brier score is simple: the mean of (probability − outcome)², outcome 1 if the event happened and 0 if not. By hand for one forecast: the agent says 70%. If the event happens, the score is (0.7 − 1)² = 0.09; if not, (0.7 − 0)² = 0.49. Always saying 50% scores 0.25 either way.

Also compare with always stating the sample’s overall rate. If the agent’s Brier is above that, using its percentages is worse than saying one fixed number, so don’t let them influence any decision. Skill score = 1 − agent Brier ÷ overall-rate Brier: positive is better, negative worse. In the example below the agent scores 0.35 against 0.2444 for always saying 42.5%, so skill = 1 − 0.35 ÷ 0.2444 ≈ −0.43.

A bucket table shows where it’s off. Each bucket gets a 95% Wilson interval, because with a few forecasts per bucket the frequency swings a lot. The t-interval for mean R doesn’t fit a yes/no frequency, and the simple p ± 1.96 × √(p(1 − p)/n) can go below 0% or above 100% with small n.

How it works here. Write down the event before running: price hits TP before SL within 16 M15 candles after the checkpoint. Code takes the outcome from after_16_agent in reports/compare.csv: TP first is 1; SL first or neither is 0; undetermined is dropped and counted. The agent puts the number at the end of short_reason as “confidence 70%”, so the JSON keeps exactly 10 fields.

This scoring batch is a new version, decision-confidence-v1, run on new checkpoints:

  1. prompts/decision-confidence-v1.md = your current prompt plus rule 8 right under rule 7, with three sentences adjusted so they don’t contradict it (table below).
  2. reports/criteria-confidence-v1.md records the event, the scoring and the minimum number of forecasts.
  3. In export_m15.py: FROM = 2 November 2026 (after both clock changes on 25 October and 1 November, still 200+ warm-up candles before 5 November), TO = 21 November 2026, OUT = data/xauusd_m15_utc_confidence.csv. Re-measure the offset on a 5 November candle and leave OFFSET_HOURS_AFTER = None. In make_checkpoints.py: DAYS = ["2026-11-05", "2026-11-12", "2026-11-19"], the new data path, and output reports/checkpoints-confidence-v1.csv (fix the print line too).
  4. In run_shadow.py change DATA, CHECKPOINTS, PROMPT, VERSION; in compare.py the data path and VERSION. Then git add -A and commit before running.
  5. Run run_shadow.py, then compare.py, then calibration.py.

The frequency here only scores calibration; it says nothing about profit, which needs R, costs and a trade count. A batch of a few dozen checkpoints has only a few trades, so read the 95% interval before concluding the agent is over- or well-calibrated: if the interval still contains the stated level, you can’t conclude yet.

Add to the prompt, right under rule 7:

8. For BUY or SELL: end short_reason with "confidence NN%", NN an integer from 0 to 100:
   your estimated probability that price hits tp before sl within 16 M15 candles after the point. Not for STAY_OUT.
Where v1 decision-confidence-v1
<role> You don’t predict beyond the data and don’t use knowledge of prices at other times. Apart from the confidence number in rule 8, you don’t predict; you don’t use knowledge of prices at other times.
<constraints> Use only the rows in data; don’t infer what happened after the point. Use only the rows in data; don’t use knowledge of prices after the point. The number in rule 8 is also estimated from these rows only.
<output>, short_reason at most 200 characters, state ema20 and ema50 of the last 2 candles at most 200 characters including the closing “confidence NN%”, state ema20 and ema50 of the last 2 candles
cd C:\trading-agent-lab
notepad src\calibration.py
notepad tests\test_calibration.py
.venv\Scripts\python -m pytest -q tests\test_calibration.py
.venv\Scripts\python src\calibration.py --example

pytest prints 5 passed. After the confidence batch, run compare.py (with the data path and VERSION updated), then .venv\Scripts\python src\calibration.py to score your own run.

src/calibration.py:

# src/calibration.py: score the agent's "confidence NN%" with the Brier score and a bucket table.
# Reads reports/compare.csv only; calls no agent, sends no orders.
#   Your run:     .venv\Scripts\python src\calibration.py
#   Example set:  .venv\Scripts\python src\calibration.py --example
import csv
import math
import re
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
PATTERN = re.compile(r"confidence\s*(\d{1,3})\s*%", re.IGNORECASE)
# Event written before the run: price hits TP before SL within 16 M15 candles after the checkpoint.
EVENT_COL = "after_16_agent"
# Example numbers, not real results: (confidence stated, times the event happened, forecasts).
EXAMPLE = [(0.6, 5, 10), (0.7, 6, 15), (0.8, 4, 10), (0.9, 2, 5)]


def read_confidence(reason):
    """The number in the last "confidence NN%" as a 0-1 probability; None if absent or above 100."""
    found = PATTERN.findall(reason or "")
    if not found or int(found[-1]) > 100:
        return None
    return int(found[-1]) / 100


def event_outcome(text):
    """1: TP first. 0: SL first or neither. None: undetermined or missing data."""
    if text == "TP first":
        return 1
    if text == "SL first" or text.startswith("neither"):
        return 0
    return None


def brier(probs, outcomes):
    """Mean of (probability - outcome)^2: 0 is best, always saying 50% scores 0.25.
    Binary-event form; the original two-sided definition gives double."""
    if not probs or len(probs) != len(outcomes):
        raise ValueError("need two non-empty lists of the same length")
    return sum((p - y) ** 2 for p, y in zip(probs, outcomes)) / len(probs)


def wilson(k, n, z=1.96):
    """Wilson 95% interval for a frequency k/n; works even for small n."""
    if n <= 0:
        raise ValueError("n must be positive")
    p, z2 = k / n, z * z
    centre = (p + z2 / (2 * n)) / (1 + z2 / n)
    half = z * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n)
    return max(0.0, centre - half), min(1.0, centre + half)


def bucket_table(probs, outcomes):
    """Group into 10-point buckets (60-69%, 70-79%...). Each row: bucket, n, mean confidence, frequency, 95% interval."""
    groups = {}
    for p, y in zip(probs, outcomes):
        groups.setdefault(min(round(p * 100) // 10, 9), []).append((p, y))
    rows = []
    for i, items in sorted(groups.items()):
        n, k = len(items), sum(y for _, y in items)
        rows.append({"bucket": f"{i * 10}-{i * 10 + 9}%" if i < 9 else "90-100%", "n": n,
                     "mean_conf": sum(p for p, _ in items) / n, "freq": k / n,
                     "ci_95": wilson(k, n)})
    return rows


def read_compare(path):
    """(probability, outcome) pairs from reports/compare.csv; counts BUY/SELL rows that were dropped."""
    probs, outs, dropped = [], [], 0
    with open(path, encoding="utf-8-sig") as f:
        for r in csv.DictReader(f):
            if r["agent"] not in ("BUY", "SELL"):
                continue                                   # STAY_OUT, VIOLATION: no forecast
            p, y = read_confidence(r["agent_reason"]), event_outcome(r[EVENT_COL])
            if p is None or y is None:
                dropped += 1
                continue
            probs.append(p)
            outs.append(y)
    return probs, outs, dropped


def expand(example):
    """(confidence, hits, forecasts) into two lists: probabilities and 0/1 outcomes."""
    probs, outs = [], []
    for p, k, n in example:
        probs += [p] * n
        outs += [1] * k + [0] * (n - k)
    return probs, outs


def report(probs, outs, dropped):
    n = len(probs)
    if n == 0:
        print("No scorable forecast with 'confidence NN%' yet; dropped", dropped, "rows.")
        return
    freq = sum(outs) / n
    b, b_base = brier(probs, outs), brier([freq] * n, outs)
    print(f"Scored forecasts: {n} | dropped: {dropped} (no 'confidence NN%', undetermined or missing data)")
    print(f"Agent Brier: {b:.4f} | always 50%: 0.2500 | always the overall rate {freq:.1%}: {b_base:.4f}")
    if b_base > 0:
        print(f"Skill vs the overall rate: {1 - b / b_base:+.2f} (negative: worse than always saying one number)")
    print("bucket       | forecasts | mean conf. | observed rate | 95% interval")
    for d in bucket_table(probs, outs):
        lo, hi = d["ci_95"]
        print(f"{d['bucket']:<12} | {d['n']:>9} | {d['mean_conf']:>10.0%} | {d['freq']:>13.0%} | {lo:.0%}-{hi:.0%}")
    print("This rate only scores calibration; it says nothing about profit. Small samples give very wide intervals.")


if __name__ == "__main__":
    if "--example" in sys.argv:
        print("Example numbers, not real results.")
        report(*expand(EXAMPLE), 0)
    else:
        report(*read_compare(ROOT / "reports" / "compare.csv"))

tests/test_calibration.py:

import pytest

from src.calibration import EXAMPLE, brier, bucket_table, event_outcome, expand, read_confidence, wilson


def test_read_confidence():
    assert read_confidence("ema20 crossed above ema50; confidence 70%") == 0.7
    assert read_confidence("Confidence 100 %") == 1.0
    assert read_confidence("confidence 40%, revised: confidence 55%") == 0.55   # the last one counts
    assert read_confidence("confidence 140%") is None
    assert read_confidence("ema20 above ema50") is None


def test_event_outcome():
    assert event_outcome("TP first") == 1
    assert event_outcome("SL first") == 0
    assert event_outcome("neither after 16 candles") == 0
    assert event_outcome("undetermined: SL and TP in the same candle") is None
    assert event_outcome("missing data") is None


def test_brier_anchors():
    assert brier([0.5] * 4, [1, 0, 1, 0]) == 0.25      # always 50%
    assert brier([1.0, 0.0], [1, 0]) == 0.0            # certain and right
    assert brier([1.0, 0.0], [0, 1]) == 1.0            # certain and wrong
    with pytest.raises(ValueError):
        brier([], [])


def test_wilson():
    lo, hi = wilson(5, 10)
    assert round(lo, 4) == 0.2366 and round(hi, 4) == 0.7634
    assert wilson(0, 5)[0] == 0.0


def test_example_set():
    probs, outs = expand(EXAMPLE)
    assert len(probs) == 40 and sum(outs) == 17
    assert brier(probs, outs) == pytest.approx(0.35)                  # 14 / 40
    assert brier([17 / 40] * 40, outs) == pytest.approx(0.244375)     # 0.425 x 0.575
    rows = bucket_table(probs, outs)
    assert [(d["bucket"], d["n"], d["freq"]) for d in rows] == [
        ("60-69%", 10, 0.5), ("70-79%", 15, 0.4), ("80-89%", 10, 0.4), ("90-100%", 5, 0.4)]
    assert rows[1]["ci_95"][1] < 0.7       # says 70% but the interval's upper bound is below 70%

Output with the example numbers:

Example numbers, not real results.
Scored forecasts: 40 | dropped: 0 (no 'confidence NN%', undetermined or missing data)
Agent Brier: 0.3500 | always 50%: 0.2500 | always the overall rate 42.5%: 0.2444
Skill vs the overall rate: -0.43 (negative: worse than always saying one number)
bucket       | forecasts | mean conf. | observed rate | 95% interval
60-69%       |        10 |        60% |           50% | 24%-76%
70-79%       |        15 |        70% |           40% | 20%-64%
80-89%       |        10 |        80% |           40% | 17%-69%
90-100%      |         5 |        90% |           40% | 12%-77%
This rate only scores calibration; it says nothing about profit. Small samples give very wide intervals.

Reading it: a Brier of 0.35 is worse than the 0.25 of always saying 50%, and skill is −0.43. In the 70%, 80% and 90% buckets the observed rate is only 40%, and the upper ends of the 95% intervals (64%, 69%, 77%) are all below the stated level: signs of overconfidence. The 60% bucket’s interval, 24% to 76%, contains 60%, so no conclusion there yet.

You see Cause Fix
No scorable forecast with 'confidence NN%' yet reports/compare.csv is still the v1 batch, or the agent didn’t follow the format Check PROMPT points to decision-confidence-v1.md and VERSION is decision-confidence-v1 in both scripts (prompt_hash should differ from v1); read agent_reason; never hand-edit the log
FileNotFoundError for compare.csv compare.py hasn’t run Run it first
KeyError: '2026-11-…' in compare.py It still reads the old candle file Point it at the same data file as run_shadow.py
KeyError: 'after_16_agent' N was changed in compare.py, so the column name changed and no longer matches rule 8’s 16 candles Set N = 16 again and rerun compare.py, then calibration.py. To change the horizon, make a new prompt version: change rule 8, N, EVENT_COL and its comment together, change VERSION, write the event into a new criteria file, commit, and run on new checkpoints
Many dropped rows Lots of undetermined checkpoints (SL and TP in one candle), or the agent forgot the confidence phrase Record the count in the conclusion; don’t change the scoring after seeing results

Try it: the shadow decision prompt

Save as prompts/decision-v1.md and don’t change a letter during the batch:

<role>
You apply the trading plan below to the data given. You don't predict beyond the data and don't use knowledge of prices at other times. You don't place orders; your decision is only logged for checking.
</role>

<plan>
Sample plan: an EMA-cross rule with an ATR stop. Symbol [SYMBOL], timeframe [TIMEFRAME].
1. Look only at the last candle in the data (just closed) and the candle before it.
2. BUY when on the last candle ema20 > ema50 and on the candle before ema20 <= ema50.
3. SELL when on the last candle ema20 < ema50 and on the candle before ema20 >= ema50.
4. BUY or SELL only if the last candle's close time is within 07:00-17:00 UTC, both ends included. Outside those hours, STAY_OUT.
5. If neither rule 2 nor rule 3 holds, STAY_OUT.
6. BUY: entry = close of the last candle; sl = entry - 2 x atr14 of the last candle; tp = entry + 4 x atr14 of the last candle. SELL: sl = entry + 2 x atr14; tp = entry - 4 x atr14. Round to [DECIMALS] decimals.
7. Don't fill in a lot. Code computes the size.
</plan>

<data source="[SOURCE]" until="[POINT_UTC]">
[CANDLES_CSV]
</data>

<constraints>
Decision point: [POINT_UTC]. Use only the rows in data; don't infer what happened after the point.
Column time_utc is the candle OPEN time in UTC. The last candle closes exactly at [POINT_UTC].
ema20, ema50, atr14 were computed by code; use those numbers, don't recompute them.
If no condition clearly holds, STAY_OUT.
</constraints>

<self_check>
Before answering, check silently, writing nothing outside the JSON: (1) compare ema20 with ema50 on the last candle and the one before; (2) is the last candle's close time within the hours; (3) if BUY or SELL, recompute sl and tp by rule 6.
</self_check>

<output>
ONLY one JSON object, no text outside it, not wrapped in ```.
Exactly the 10 fields below. STAY_OUT: entry, sl, tp are null; BUY or SELL: they are numbers.
{"time_utc": "[POINT_UTC]", "symbol": "[SYMBOL]", "timeframe": "[TIMEFRAME]", "action": "BUY or SELL or STAY_OUT", "entry": null, "sl": null, "tp": null, "short_reason": "at most 200 characters, state ema20 and ema50 of the last 2 candles", "data_until": "[POINT_UTC]", "prompt_version": "[VERSION]"}
</output>

The order to work in:

  1. Lock parameters first: a versioned prompt, the model by full name, every agent tool off, a git commit.
  2. Write the level-2 criteria and the checkpoint rule before running; don’t edit them after seeing results.
  3. Run shadow on post-cutoff data; the agent sees only candles closed up to the checkpoint and places no orders.
  4. Check every answer with code; count schema violations and never repair them; the lot is always computed by code, rounded down to 0.01.
  5. Compare with a baseline rule in code on the same data; read the trade checkpoints separately and look at every mismatch on the chart.
  6. Measure repeatability on identical input; rerun the suite when the provider changes the model or model_actual differs from the pinned model.
  7. Conclude pass or not by the criteria. If you change the prompt, make a new version and test it on new checkpoints before considering level 2 on demo with human approval.
  8. If the agent states a % confidence, score it with Brier and a bucket table (event written first, outcome decided by code) before that number influences anything.

Key takeaways

  • Write and commit the level-2 criteria before running. A v2 prompt must be tested on a new, unused set of checkpoints.
  • Call claude -p with --tools "" and --disallowedTools "mcp__*" so the agent can’t open the file holding candles after the checkpoint.
  • A high overall match with the baseline is misleading when both sides mostly stay out; read the checkpoints with a trade.
  • Pin the model by full name, such as claude-sonnet-5-5. Temperature no longer buys stability; clear data, clear rules and a schema do.

Comments