Episode 32 · AI Trading · Building a Complete Trading System

Reading a backtest report against its trade ledger

Rebuild trade count, net R, fees and drawdown from the trade list, hand-check a few trades, and drop any AI claim that doesn't trace back to a row.

How do you check a backtest report, and an AI’s comments on it, using the list of individual trades?

This post rebuilds the trade count, net result, fees and drawdown from the ledger, then checks a few trades by hand. The easy mistake: a fluent AI summary doesn’t replace the ledger. Any number that can’t be traced back to trade rows gets dropped.

Terms used below:

  • Ledger: the list of every event or trade, used to check the totals a report shows.
  • R: a trade’s result divided by the money it risked at entry (its initial risk). +2R made twice what was risked; −1R lost exactly the risk.
  • N: the number of trades a figure is computed on. Say what counts: closed trades only, or every opportunity.
  • Equity drawdown: the fall from a peak of the account value, including open positions. A drawdown on closed-trade R is a different number.

A report is only trusted once it can be traced

Export the trade list with account details removed. Write down the R denominator, the commission, the time zone, and how timeouts and break-evens are counted. Ask the AI to rebuild the totals, the sample size, and the split by year and by direction, and to pick the first trade by time so you can compare it with the chart. A drawdown on closed-trade R isn’t an equity drawdown; ask for each under its right name. Don’t accept a metric nobody can reproduce.

Gate Question If not
Input The report plus a CSV with account details removed
1 Is N defined: closed trades, or every opportunity? Define it first, then compute
2 Do the totals rebuilt from the ledger match? Trace row by row and record every adjustment
3 Is the drawdown named correctly: on R or on equity? Ask for each under its right name
4 Can each metric be reproduced? Don’t accept that metric
Passed Read the report alongside the ledger, and say what’s still unreconciled

Each comment the AI makes has to trace back to ledger rows, a unit and a calculation. If the data is missing, it says it’s missing and doesn’t fill in a number.

A summary that doesn’t match the CSV

The summary says 100 trades. The CSV has 95 closed trades and 5 pending orders that expired without filling.

  • Define N first: closed trades, or every opportunity.
  • Don’t count an unfilled pending order as a win or a loss.
  • Recompute on the 95 and report the 5 expired orders separately.
  • Record every adjustment and the data source. Never edit the CSV to match the summary.
What the summary’s “100” is made of Count What to do
Closed trades 95 Recompute N and the net result on these; check a few by hand
Pending orders that expired 5 Never filled, so neither win nor loss; report them separately

A made-up ledger shows how it works. Each row is one opportunity; exits holds one or more fills as price@lots, so a trade closed in two parts stays one row. The header, the first three rows and three rows worth a look:

id,rule_version,direction,status,open_time_utc,close_time_utc,entry,exits,qty,fees_usd,initial_risk_usd
T001,xau-brk-v2,sell,closed,2025-06-04T14:00Z,2025-06-05T22:00Z,2951.64,[email protected],0.08,1.12,58.32
T002,xau-brk-v2,sell,closed,2025-06-06T20:00Z,2025-06-09T00:00Z,3012.76,[email protected],0.05,0.7,65.8
T003,xau-brk-v2,buy,closed,2025-06-10T02:00Z,2025-06-11T17:00Z,3035.14,[email protected],0.08,1.12,57.52
T012,xau-brk-v2,sell,expired,2025-07-15T06:00Z,,3066.32,,0,0.0,
T021,xau-brk-v2,buy,closed,2025-08-19T06:00Z,2025-08-20T22:00Z,3117.34,[email protected];[email protected],0.05,0.7,63.45
T047,xau-brk-v2,sell,closed,2025-11-13T18:00Z,2025-11-14T02:00Z,3349.45,[email protected],0.08,1.12,

T012 expired with nothing filled, T021 closed in two parts, and T047 has no initial risk, so its R can’t be computed. The report for this ledger says 100 trades, +12.0R.

A script that rebuilds the report from the rows, src/reconcile.py. It reads files only, takes 100 oz per lot for XAUUSD (check your symbol’s contract size), and treats fees_usd as commission for both sides:

# src/reconcile.py: rebuild a backtest report's headline numbers from the trade ledger, line by line.
# Reads files only; changes nothing. Run: .venv\Scripts\python src\reconcile.py data\trades.csv data\report_summary.json
import csv, json, statistics, sys
from collections import defaultdict

CONTRACT = 100   # XAUUSD: 100 oz per lot; check your symbol's contract size


def fills(text):
    """'[email protected];[email protected]' -> [(2650.40, 0.05), (2661.90, 0.05)]"""
    return [(float(p), float(q)) for p, q in (part.split("@") for part in text.split(";"))]


def gross_usd(row):
    sign = 1 if row["direction"] == "buy" else -1
    entry = float(row["entry"])
    return sum((p - entry) * q * CONTRACT * sign for p, q in fills(row["exits"]))


def load(path):
    with open(path, newline="") as f:
        return list(csv.DictReader(f))


def split(rows):
    closed = [r for r in rows if r["status"] == "closed"]
    expired = [r for r in rows if r["status"] == "expired"]
    other = [r for r in rows if r["status"] not in ("closed", "expired")]
    no_risk = [r for r in closed if not r["initial_risk_usd"]]
    with_r = [r for r in closed if r["initial_risk_usd"]]
    return closed, expired, other, no_risk, with_r


def r_multiple(row, fee_sides=2):
    """Net R. fee_sides=2: fees_usd as logged (both sides). 1: only half of it, 0: none."""
    fees = float(row["fees_usd"]) * fee_sides / 2
    return (gross_usd(row) - fees) / float(row["initial_risk_usd"])


def max_drawdown(rs):
    peak = cum = dd = 0.0
    for r in rs:
        cum += r
        peak = max(peak, cum)
        dd = min(dd, cum - peak)
    return dd


def longest_losing_streak(rs):
    best = run = 0
    for r in rs:
        run = run + 1 if r < 0 else 0
        best = max(best, run)
    return best


def main(ledger, summary_path):
    rows = load(ledger)
    report = json.load(open(summary_path))
    closed, expired, other, no_risk, with_r = split(rows)
    with_r.sort(key=lambda r: r["close_time_utc"])
    rs = [r_multiple(r) for r in with_r]

    print(f"rows {len(rows)} | closed {len(closed)} | expired, never filled {len(expired)} | other {len(other)}")
    for r in no_risk:
        print(f"  R not computable: {r['id']} (initial_risk_usd empty) - left out of every R figure")
    net_usd = sum(gross_usd(r) - float(r["fees_usd"]) for r in closed)
    fees = sum(float(r["fees_usd"]) for r in closed)
    print(f"N = {len(rs)} closed trades with R | net {net_usd:,.2f} USD after {fees:,.2f} USD fees (both sides)")
    print(f"net {sum(rs):+.1f}R | mean {statistics.mean(rs):+.2f}R | median {statistics.median(rs):+.2f}R"
          f" | winners {sum(r > 0 for r in rs)}/{len(rs)}")
    print(f"longest losing streak {longest_losing_streak(rs)} | max drawdown {max_drawdown(rs):.1f}R"
          f" on closed-trade R (not equity drawdown: open positions aren't in this ledger)")
    groups = defaultdict(list)
    for row, r in zip(with_r, rs):
        groups[row["close_time_utc"][:4]].append(r)
        groups[row["direction"]].append(r)
    print("  " + " | ".join(f"{k} N={len(v)} {sum(v):+.1f}R" for k, v in sorted(groups.items())))

    print(f"report says: {report['trades']} trades, {report['net_R']:+.1f}R")
    if report["trades"] != len(closed):
        print(f"  trades: {report['trades']} = {len(closed)} closed + {len(expired)} expired;"
              f" an order that never filled is neither a win nor a loss")
    tries = {"fees on both sides": 2, "fees on one side only": 1, "no fees": 0}
    for name, sides in tries.items():
        total = sum(r_multiple(r, sides) for r in with_r)
        mark = "  <- matches the report" if round(total, 1) == report["net_R"] else ""
        print(f"  net R with {name}: {total:+.1f}R{mark}")

    print("hand check (redo these on a calculator):")
    tests = {"first by time": lambda r: True,
             "a winner": lambda r: r_multiple(r) > 0 and ";" not in r["exits"],
             "a loser": lambda r: r_multiple(r) < 0,
             "a partial": lambda r: ";" in r["exits"]}
    used = set()
    for label, test in tests.items():
        r = next((r for r in with_r if test(r) and r["id"] not in used), None)
        if r is None:
            print(f"  {label}: none in the ledger")
            continue
        used.add(r["id"])
        print(f"  {label}: {r['id']} {r['direction']} {r['qty']} lot @ {r['entry']} exits {r['exits']}"
              f" | gross {gross_usd(r):+.2f} - fees {r['fees_usd']} = {gross_usd(r) - float(r['fees_usd']):+.2f} USD"
              f" / risk {r['initial_risk_usd']} = {r_multiple(r):+.2f}R")


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

Run it with .venv\Scripts\python src\reconcile.py data\trades.csv data\report_summary.json:

rows 100 | closed 95 | expired, never filled 5 | other 0
  R not computable: T047 (initial_risk_usd empty) - left out of every R figure
N = 94 closed trades with R | net 844.28 USD after 83.02 USD fees (both sides)
net +11.3R | mean +0.12R | median -1.01R | winners 36/94
longest losing streak 6 | max drawdown -5.9R on closed-trade R (not equity drawdown: open positions aren't in this ledger)
  2025 N=57 +8.0R | 2026 N=37 +3.3R | buy N=47 +16.1R | sell N=47 -4.8R
report says: 100 trades, +12.0R
  trades: 100 = 95 closed + 5 expired; an order that never filled is neither a win nor a loss
  net R with fees on both sides: +11.3R
  net R with fees on one side only: +12.0R  <- matches the report
  net R with no fees: +12.7R
hand check (redo these on a calculator):
  first by time: T001 sell 0.08 lot @ 2951.64 exits [email protected] | gross -58.32 - fees 1.12 = -59.44 USD / risk 58.32 = -1.02R
  a winner: T006 buy 0.05 lot @ 3018.01 exits [email protected] | gross +83.80 - fees 0.7 = +83.10 USD / risk 55.85 = +1.49R
  a loser: T002 sell 0.05 lot @ 3012.76 exits [email protected] | gross -65.80 - fees 0.7 = -66.50 USD / risk 65.8 = -1.01R
  a partial: T021 buy 0.05 lot @ 3117.34 exits [email protected];[email protected] | gross +88.83 - fees 0.7 = +88.13 USD / risk 63.45 = +1.39R

Read it top to bottom:

  • N: the report’s 100 is 95 closed plus 5 expired. T047 has no initial risk, so the R figures use 94 trades and say so.
  • The +12.0R: it’s only reproduced with commission on one side. With both sides, as the broker charges it, the net is +11.3R. Note that adjustment; don’t round your way to the report’s figure.
  • Mean against median: the mean is +0.12R, the median −1.01R. A few large winners carry the mean; the typical trade loses. Always report both, with N.
  • Drawdown: −5.9R is on closed-trade R. An equity drawdown needs open positions, which this ledger doesn’t have, so the script doesn’t print one.
  • The split: buys made +16.1R and sells lost 4.8R. That’s a question for the next test, not a conclusion.

The counting rules as tests, tests/test_reconcile.py:

# tests/test_reconcile.py: the counting rules, on four hand-made rows.
from src.reconcile import gross_usd, r_multiple, split, max_drawdown

ROWS = [
    dict(id="A", direction="buy", status="closed", entry="2650.00", exits="[email protected]", qty="0.06",
         fees_usd="0.84", initial_risk_usd="60.00", close_time_utc="2025-02-03T10:00Z"),
    dict(id="B", direction="sell", status="closed", entry="2700.00", exits="[email protected];[email protected]",
         qty="0.06", fees_usd="0.84", initial_risk_usd="60.00", close_time_utc="2025-02-04T10:00Z"),
    dict(id="C", direction="buy", status="expired", entry="2710.00", exits="", qty="0",
         fees_usd="0", initial_risk_usd="", close_time_utc=""),
    dict(id="D", direction="buy", status="closed", entry="2720.00", exits="[email protected]", qty="0.06",
         fees_usd="0.84", initial_risk_usd="", close_time_utc="2025-02-05T10:00Z"),
]


def test_expired_orders_are_not_trades():
    closed, expired, _, no_risk, with_r = split(ROWS)
    assert [r["id"] for r in closed] == ["A", "B", "D"]
    assert [r["id"] for r in expired] == ["C"]
    assert [r["id"] for r in no_risk] == ["D"] and len(with_r) == 2


def test_partial_exit_adds_both_fills():
    # sell 0.06 at 2700: 0.03 out at 2690 (+30 USD) and 0.03 at 2680 (+60 USD)
    assert round(gross_usd(ROWS[1]), 2) == 90.00


def test_fees_change_r():
    # 10 USD x 0.06 lot x 100 oz = 60 USD gross; 60 - 0.84 = 59.16 USD; / 60 = 0.986R
    assert round(r_multiple(ROWS[0]), 3) == 0.986
    assert round(r_multiple(ROWS[0], fee_sides=0), 3) == 1.0


def test_drawdown_on_closed_r():
    assert max_drawdown([1, -1, -1, 2, -0.5]) == -2

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

Worked example: make the AI trace a report number to the trade list

The report says +12R in total. Don’t start with “is the system any good?”. Hand over the export with sensitive details removed, and ask for the total rebuilt from each row: timestamp, entry and exit, quantity, fees, P/L, initial risk and rule version. Ask it to list the rows that are missing data or whose R can’t be computed.

Pick one winning trade, one losing trade and one partial by hand. Work out their P/L yourself and compare it with the AI’s. For T021 above: buy 0.05 lot at 3117.34; 0.03 lot out at 3130.03 is 12.69 × 0.03 × 100 = 38.07 USD, and 0.02 lot at 3142.72 is 25.38 × 0.02 × 100 = 50.76 USD. That’s 88.83 USD gross, minus 0.70 USD fees, divided by 63.45 USD of risk: +1.39R.

If the total is off, trace currency conversion, fees on both sides and how fills were matched. Don’t round each step early to force a match with the report. Deposits and withdrawals have to be separated from trading profit.

Step Who What
1 The report says +12R in total
2 You Hand over the export with sensitive details removed
3 AI Rebuild the total from each row: timestamp, entry/exit, quantity, fees, P/L, initial risk, rule version
4 AI List the rows with missing data or no computable R
5 You Work out 1 winner, 1 loser and 1 partial yourself; compare with the AI
6 You If the total is off, trace currency conversion, fees on both sides, fill matching; no early rounding

A summary table only means something for the full cohort. The AI may not drop outliers on its own, leave out unmatched trades, or add assumptions it didn’t state up front. The conclusion has to say what’s still unreconciled; a confident tone isn’t ledger evidence.

Optional: reading a QuantStats report alongside the ledger

Outside this post’s main path. The backtest post built this report with src/qs_report.py; here it’s read next to the ledger. QuantStats (an open-source Python library, Apache-2.0) reads a series of per-period returns and writes one HTML file: the equity curve, drawdowns, monthly returns and a table of metrics. Facts checked on 2026-11-23 with QuantStats 0.0.86.

  • Daily returns: take the backtest’s equity after costs and turn it into returns per trading day closing at 22:00 UTC (shift the timestamps by +2 hours, then take the last value of each day). Candles opening at 22:00 and 23:00 UTC count towards the next day, so Sunday evening belongs to Monday. Grouping by raw UTC date adds about 52 “Sundays” a year and gives different numbers.
  • Benchmark: pass a pandas Series built from your own CSV, such as buy-and-hold gold over the same period. Don’t pass a ticker as text: then QuantStats downloads data through yfinance, an unofficial library in a grey area under Yahoo’s terms. With a Series and the network blocked, the report built with 0 network calls; with a ticker it tried 9.
  • periods_per_year: set it to your data’s own trading days per year instead of the default 252. On an XAUUSD sample that’s about 260.
  • The icon line: QuantStats 0.0.86’s HTML has an icon line pointing to qtpylib.io, fetched every time the file is opened (it carries none of your data). Remove the <link rel="shortcut icon" …> line, as in the backtest post, to open it fully offline.

An example on historical XAUUSD H1 candles (01/2025–10/2026): EMA 20 crossing EMA 100, spread 0.02% of price, 137 trades. The mean return per trade is +0.27%, but the median is −0.45%: a few big winners lift the mean while the typical trade loses. The 95% confidence interval for the mean runs from −0.17% to +0.71% and contains 0, so there’s no evidence of an edge yet. Mean, median and confidence interval per trade come from the backtest’s trade list (the ReturnPct column); the QuantStats report doesn’t have them. How many trades are enough, and how to read a confidence interval, is in the luck-or-skill post. A simulation on historical data, not investment advice.

Win Days and Win Month (and Win Quarter, Win Year) are the share of periods with a positive return among periods whose return isn’t 0. QuantStats drops zero periods, usually days with no position, from the denominator. They’re not the share of winning trades: one trade held for several days counts as several winning or losing days. Read them with Time in Market, because a strategy that sits out most days can show high Win Days while very few days actually make money.

Row in the table Easy misreading On the example above
Win Days The share of winning trades 230 of 455 non-zero days (printed 50.55%); 39 of 137 trades (28%) won
Win Days, counting flat days 17 flat days from 03 to 27 Jan 2025 before the first trade: 230/472 = 48.7%; with a benchmark, QuantStats trims them and starts on 28 Jan 2025
Win Year A steady system 100% is 2 out of 2 years (2025 and the first 10 months of 2026)
Mean return The typical trade +0.27% mean, −0.45% median; always report both, with the trade count
Max Drawdown One fixed number −21.1% on daily returns; −23.1% on the same backtest’s H1 equity. Name the frequency

The winning-trade share is only for your own check; always put it beside the mean, the median and the confidence interval.

Try it: an independent review of a backtest report

Analyse the attached backtest report as an independent reviewer. Don't base a conclusion on total profit alone. Build a table with: number of trades, max drawdown, mean and median per trade, losing streak, costs, distribution by month and by session, the difference between equity and balance, unusual trades, and data limits. State the formula or definition you used, and which items can't be computed from the file. Suggest 5 trades to open on the chart and check. Don't forecast the future or call any configuration the best.

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. Export the original report; write down the configuration and the code version or hash.
  2. Open the winning trades, the losing ones and those near the SL on the chart to check the fill logic.
  3. Run again on the same data and configuration to make sure the report can be reproduced.

Key takeaways

  • The summary says 100 trades but the CSV has 95 closed trades and 5 pending orders that expired: compute on the 95 and report the 5 separately.
  • A drawdown on the closed trades’ R (initial risk) isn’t an equity drawdown; separate deposits and withdrawals from trading profit.
  • If the total is off, trace currency conversion, fees on both sides and how partial fills were matched; never edit the CSV or drop outliers to make it match.

Comments