An agent reports +0.4R a trade over 25 trades. A backtest shows a Sharpe of 2.0 after three months. Is that skill or luck, and how many trades would you need before you could tell?
This post builds src/stats_lab.py, a small statistics library with eight
golden tests, and applies it to real backtest trade logs. The short answer for
one of them: +0.096R a trade over 168 trades, 95% interval −0.126R to +0.317R.
No evidence yet.
Terms used below:
- Base rate: the share of cases where the event happens across all the data, before you look at any signal. The rarer the event, the more a fairly accurate signal raises false alarms rather than real ones.
- R: a trade’s profit or loss divided by the distance from entry to the initial SL. Hitting the SL is −1R; a win of twice the SL distance is +2R.
- Sample standard deviation (ddof=1): how spread out per-trade R is,
dividing by n − 1.
numpy.stddivides by n by default (ddof=0); pandas divides by n − 1. Mixing them shifts your numbers. - Standard error (SE): the noise in the mean R itself: standard deviation ÷ √n. Halving it takes four times as many trades.
- 95% confidence interval: mean R ± t(0.975; n − 1) × SE, where the multiplier comes from the t distribution with n − 1 degrees of freedom (2.064 for n = 25, close to 1.96 for large n). An interval containing 0 means no evidence yet that the true mean R differs from 0.
- t statistic: mean R ÷ SE: how many times its own noise the mean sits away from 0.
- Per-session Sharpe: mean return per session ÷ standard deviation of session returns (risk-free rate 0). Annualise by × √(real sessions a year).
- Multiple testing: trying many variants and keeping the best. If the variants are independent, the chance at least one passes by luck is 1 − (1 − p)^m; similar variants push it lower, but it still grows with m.
- Pre-registered threshold: the pass criterion, trades needed and maximum number of variants, written to a file and committed before you run anything. Setting the bar after seeing the result is fooling yourself.
Start from the base rate
Before asking whether a result is good, ask how often the thing happens anyway.
A real example: XAUUSD H1, 1 January 2025 to 30 October 2026, UTC. Of 476 Monday–Friday sessions, 18 had a range (high minus low) of at least 5% of the open: 3.8%. The 5% threshold was picked to make the event rare. At 3% the base rate is 15.3% (73/476). Base rates change with the definition, so always write the definition next to the denominator.
Say an agent has a “volatile session ahead” signal, sold as “80% accurate”: it fires on 80% of event sessions and stays quiet on 80% of normal ones, so it false-alarms on 20%. Those accuracy numbers are assumptions. Count it over 1,000 sessions at a 3.8% base rate:
- 38 volatile sessions; the signal catches about 30.
- 962 normal sessions; the signal false-alarms about 192 times.
- Of about 222 alarms, only about 30 are real: 13.6%.
“80% accurate” does not mean each alarm is right 80% of the time. That’s Bayes’ theorem: what an alarm tells you depends on both accuracy and the base rate. The rarer the event, the more false alarms dominate.
| Base rate | Event sessions | Hits | False alarms | Share of alarms that are real |
|---|---|---|---|---|
| 3.8% (range ≥ 5%) | 38 | 30 | 192 | 13.6% |
| 15.3% (range ≥ 3%) | 153 | 123 | 169 | 42.0% |
| 50% (assumed) | 500 | 400 | 100 | 80.0% |
Share of alarms that are real = (base rate × sensitivity) ÷ (base rate × sensitivity + (1 − base rate) × false-alarm rate), where sensitivity is the share of event sessions the signal catches (80% here).
The same counting applies to trading ideas. Assume 1,000 ideas, 5% with a real edge; a backtest pass threshold of p = 0.05, so an idea with no edge still passes 5% of the time; and an idea with a real edge passes only half the time, because samples are short. Expected: 25 ideas pass on their edge, 47.5 pass by luck. Of the ideas that pass, 66% are luck. If only 1% of ideas have an edge, luck’s share rises to 91%.
| Share with an edge | With an edge | Pass on the edge | Pass by luck | Share of passes due to luck |
|---|---|---|---|---|
| 1% | 10 | 5 | 49.5 | 91% |
| 5% | 50 | 25 | 47.5 | 66% |
| 20% | 200 | 100 | 40 | 29% |
“It passed a backtest” is the first filter, not evidence.
Twenty people, one method with no edge
To see luck look like skill, simulate 20 people running the same method with no edge. Each trade hits TP for +2R with probability 1/3 or SL for −1R with probability 2/3. The expectation is exactly 0R before costs, and the true standard deviation of one trade is √2, about 1.414R. Each person takes 500 trades; the seed is fixed at 20261123, so a rerun gives the same numbers.
| Trades | Lowest mean R | Highest mean R | People at ≥ +0.20R | 95% interval wholly above 0 | Theoretical SE |
|---|---|---|---|---|---|
| 20 | −0.550R | +0.950R | 7/20 | 1/20 | 0.316R |
| 100 | −0.310R | +0.230R | 2/20 | 0/20 | 0.141R |
| 500 | −0.058R | +0.110R | 0/20 | 0/20 | 0.063R |
After 20 trades, seven people are at +0.20R or better, enough to believe they’re good, and one even has a 95% interval wholly above 0. After 500 trades nobody is. That’s the law of large numbers: the average closes in on the true expectation, and its noise shrinks with √n.
The luckiest person ends 500 trades at +55R, and their cumulative R line looks fairly straight: R² against trade number is 0.84, correlation r = 0.91. (This R² measures how much of the line’s movement a straight line explains; 1 is a perfect line. It has nothing to do with trade R. MT5’s Strategy Tester reports the same idea as LR Correlation, the correlation of the balance curve with a straight line; with one variable, R² is the correlation squared.)
A smooth, straight equity curve is not evidence. Each person has about a 34% chance of reaching +0.20R after 20 trades, so among 20 people the chance that at least one does is 99.97%. Showing off the best of many people, accounts or variants says very little about skill.
src/luck_sim.py (needs src/stats_lab.py from the next sections):
# src/luck_sim.py: 20 people run the SAME method with NO edge; look at results after 20, 100 and 500 trades.
# Made-up numbers, not real data: each trade is +2R (TP) with probability 1/3 and -1R (SL) with probability 2/3,
# so the expectation is exactly 0R before costs. Fixed seed: a rerun gives the same numbers.
# Run: .venv\Scripts\python src\luck_sim.py
import math
import sys
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src import stats_lab as sl
SEED, PEOPLE, CHECKPOINTS = 20261123, 20, (20, 100, 500)
rng = np.random.default_rng(SEED)
trades = rng.choice([2.0, -1.0], size=(PEOPLE, max(CHECKPOINTS)), p=[1 / 3, 2 / 3])
true_sd = math.sqrt(2.0) # sqrt(4*1/3 + 1*2/3 - 0^2): true standard deviation of one trade
print("Trades | lowest mean R | highest mean R | people >= +0.20R | 95% interval above 0 | theoretical SE")
for n in CHECKPOINTS:
mean = trades[:, :n].mean(axis=1)
above_0 = sum(1 for i in range(PEOPLE) if sl.confidence_interval(trades[i, :n])["low"] > 0)
print(f"{n:6d} | {mean.min():+13.3f} | {mean.max():+14.3f} | {(mean >= 0.2).sum():16d} | "
f"{above_0:20d} | {true_sd / math.sqrt(n):.3f}")
totals = trades.sum(axis=1) # each person's total R after 500 trades
best = int(totals.argmax())
cum = np.cumsum(trades[best]) # the luckiest person's cumulative R line
idx = np.arange(1, max(CHECKPOINTS) + 1)
print(f"Luckiest after {max(CHECKPOINTS)} trades: total {totals[best]:+.0f}R; cumulative R line vs trade number has "
f"R^2 = {sl.r_squared(idx, cum):.2f}, correlation r = {sl.correlation(idx, cum):.2f}")cd C:\trading-agent-lab
notepad src\luck_sim.py
.venv\Scripts\python src\luck_sim.pyExpected output:
Trades | lowest mean R | highest mean R | people >= +0.20R | 95% interval above 0 | theoretical SE
20 | -0.550 | +0.950 | 7 | 1 | 0.316
100 | -0.310 | +0.230 | 2 | 0 | 0.141
500 | -0.058 | +0.110 | 0 | 0 | 0.063
Luckiest after 500 trades: total +55R; cumulative R line vs trade number has R^2 = 0.84, correlation r = 0.91Different numbers? Check the seed and the p=[1 / 3, 2 / 3] line. NumPy
doesn’t guarantee the same stream for a seed across versions, so pin numpy
(below). Another version can give other numbers but the same picture: wide
spread after 20 trades, everyone near 0 after 500.
Standard error, the 95% interval and t
Every mean R needs three companions: the sample standard deviation s, the standard error SE and t.
s = sample std dev of per-trade R (divide by n − 1, ddof=1)
SE = s ÷ √n
t = mean R ÷ SE
95% interval = mean R ± t(0.975; n − 1) × SE
Minimum trades ≈ (1.96 × s ÷ μ)² (clears 0 only about half the time)
Trades for 8 in 10 ≈ ((1.96 + 0.84) × s ÷ μ)² (μ = true mean R, unknown)Reading the interval:
| 95% interval | Means | Next step |
|---|---|---|
| Wholly above 0 | Evidence of a positive mean R, for this one test | Adjust for the number of tries (below), then test on unused data |
| Contains 0 | No evidence yet | More trades on unused data, or a shadow run where the agent only logs decisions; don’t raise risk |
| Wholly below 0 | Evidence of a loss on this data and these costs | Stop, or rewrite the spec as a new version and test from scratch |
“No evidence yet” doesn’t mean there’s certainly no edge. The data just isn’t enough to say.
The opening example: +0.4R over 25 trades with s = 1.4R. SE = 1.4 ÷ 5 = 0.28R; t = 1.43; 95% interval = 0.4 ± 2.064 × 0.28 = −0.178R to +0.978R. It contains 0: no evidence yet, and no reason to raise risk.
How many trades do you need? Two levels, and the second is roughly double the first.
- Minimum: about (1.96 × s ÷ μ)² trades. Below that, the interval contains 0 even if the measured mean equals the true μ exactly. At exactly this number it isn’t enough: the measured mean wobbles around μ, so a system with a real edge clears 0 only about half the time. That’s where the “passes half the time” assumption above comes from.
- More reliable: to clear 0 eight times in ten, about ((1.96 + 0.84) × s ÷ μ)² trades.
With s = 1.4R (close to a 2R-TP, 1R-SL system), computed with the t distribution:
| True mean R μ (assumed) | Minimum | Chance at the minimum | For 8 in 10 |
|---|---|---|---|
| +0.30R | 87 | 50.7% | 173 |
| +0.20R | 191 | 50.2% | 387 |
| +0.10R | 756 | 50.1% | 1,541 |
| +0.05R | 3,015 | 50.0% | 6,156 |
The smaller the edge, the faster the trade count grows: with the square. Costs pull μ down, so after costs you need even more.
Two assumptions to remember. The t interval treats trades as independent; trades that cluster in streaks make the true interval wider. And when R is heavily skewed by a few huge trades, a small-sample t interval can be off; check by dropping the one or two biggest winners and seeing whether the verdict changes (the script below does it for you).
A stats library with golden tests
Don’t let the agent do statistics in its head. Language models mix up ddof, forget the √n, or read the wrong row of a t table, and a wrong number can still be written with total confidence. Every number in a report comes from a small tested library; the agent may run the script and copy the result, never recompute. Code computes, the agent writes, you decide.
A golden test takes its expected answer from an independent source, never from the function it tests. The eight tests check:
- ddof: the series 2, 4, 4, 4, 5, 5, 7, 9 has population standard deviation exactly 2 and sample standard deviation √(32/7). numpy defaults to dividing by n, pandas by n − 1.
- t = Sharpe × √n, and it matches SciPy’s
ttest_1samp. - With one variable, R² equals the squared correlation.
- The interval matches a published worked example: n = 195, mean 9.261460, standard deviation 0.022789 gives 9.258242 to 9.264679; and for n = 25 the multiplier is 2.064, as in a standard t table with 24 degrees of freedom. This catches looking up t at n instead of n − 1.
- A series with mean R exactly 0 gives an interval containing 0.
- 1 − 0.95^20 = 0.6415.
- Bayes, and the expected maximum of 2 standard normals is 1/√π.
min_tradesreturns the exact boundary, andtrades_neededandchance_above_0match textbook sample-size examples (a 0.8 standard deviation shift needs 15 for 8 in 10 and 19 for 9 in 10).
Pin versions. Tested with numpy 2.5.5, scipy 1.18.1, pandas 3.1, pytest 9 on
Python 3.13–3.14 (Windows 11). Write them in requirements.txt so another
machine installs the same; if a package is already listed, edit that line
rather than adding a second one. When a test goes red, fix the code, never the
test.
cd C:\trading-agent-lab
if (-not (Test-Path src\__init__.py)) { New-Item -ItemType File src\__init__.py }
notepad requirements.txt
.venv\Scripts\python -m pip install -r requirements.txt
notepad src\stats_lab.py
notepad tests\test_stats_lab.py
.venv\Scripts\python -m pytest -q tests\test_stats_lab.pyrequirements.txt (add these four lines; keep your other lines):
numpy==2.5.5
scipy==1.18.1
pandas==3.1.2
pytest==9.2.0src/stats_lab.py:
# src/stats_lab.py: the minimum statistics for reading agent and backtest results.
# Needs only numpy and scipy; reads no files, makes no network calls. Every number in a report comes from here.
import math
import numpy as np
from scipy import integrate, stats
def _series(x):
a = np.asarray(x, dtype=float)
if a.ndim != 1 or len(a) < 2:
raise ValueError("need a series of at least 2 numbers")
if np.isnan(a).any():
raise ValueError("series has empty cells (NaN): clean it first")
return a
def std_dev(x, ddof=1):
"""ddof=1: divide by n - 1 (sample standard deviation, the pandas default). numpy.std defaults to ddof=0."""
return float(np.std(_series(x), ddof=ddof))
def std_error(x):
"""Standard error of the mean = sample standard deviation / sqrt(n)."""
a = _series(x)
return std_dev(a) / math.sqrt(len(a))
def t_stat(x, ref=0.0):
"""t = (mean - reference) / standard error."""
a = _series(x)
return (float(a.mean()) - ref) / std_error(a)
def ci_from_summary(mean, sd, n, level=0.95):
"""Confidence interval of the mean: mean +/- t(1 - alpha/2, n - 1) * sd / sqrt(n)."""
t_crit = float(stats.t.ppf(1 - (1 - level) / 2, n - 1))
half = t_crit * sd / math.sqrt(n)
return mean - half, mean + half, t_crit
def confidence_interval(x, level=0.95):
"""Summary of per-trade R; contains_0 = True means the interval contains 0: no evidence yet."""
a = _series(x)
n, mean, sd = len(a), float(a.mean()), std_dev(a)
low, high, t_crit = ci_from_summary(mean, sd, n, level)
return {"n": n, "mean": mean, "median": float(np.median(a)), "sd": sd,
"se": sd / math.sqrt(n), "t": mean / (sd / math.sqrt(n)), "t_crit": t_crit,
"low": low, "high": high, "contains_0": low <= 0 <= high}
def min_trades(mean, sd, level=0.95):
"""Below this many trades the interval contains 0 even if the measured mean R equals `mean` exactly.
Only a floor: if the true mean R is `mean`, at this n the interval clears 0 only about half the time."""
if mean == 0:
raise ValueError("mean R is 0: no number of trades is enough")
z = stats.norm.ppf(1 - (1 - level) / 2)
n = max(2, int((z * sd / abs(mean)) ** 2))
def enough(k):
return stats.t.ppf(1 - (1 - level) / 2, k - 1) * sd / math.sqrt(k) < abs(mean)
while not enough(n):
n += 1
while n > 2 and enough(n - 1):
n -= 1
return n
def chance_above_0(mean, sd, n, level=0.95):
"""IF the true mean R = mean with standard deviation sd: the chance the interval of n trades lies wholly
above 0 (noncentral t; assumes normal R and independent trades). Textbooks call this power."""
t_crit = stats.t.ppf(1 - (1 - level) / 2, n - 1)
return float(stats.nct.sf(t_crit, n - 1, mean * math.sqrt(n) / sd))
def trades_needed(mean, sd, chance=0.8, level=0.95):
"""Smallest n with chance_above_0 >= chance (default 8 times in 10), IF the true mean R = mean > 0.
Starting point: ((z(1 - alpha/2) + z(chance)) * sd / mean)^2, the standard sample-size formula."""
if mean <= 0:
raise ValueError("true mean R must be positive")
z = stats.norm.ppf(1 - (1 - level) / 2) + stats.norm.ppf(chance)
n = max(2, int((z * sd / mean) ** 2))
while chance_above_0(mean, sd, n, level) < chance:
n += 1
while n > 2 and chance_above_0(mean, sd, n - 1, level) >= chance:
n -= 1
return n
def sharpe(x, ddof=1):
"""Per-period Sharpe (session, day, month), risk-free rate = 0: mean / standard deviation."""
a = _series(x)
return float(a.mean()) / std_dev(a, ddof)
def t_from_sharpe(sr_period, n):
"""t of the mean per-period return = per-period Sharpe * sqrt(n) (exact when Sharpe uses ddof=1)."""
return sr_period * math.sqrt(n)
def annual_sharpe(sr_period, periods_per_year):
"""Annualise: * sqrt(real periods per year). Only valid if period returns are independent and identically distributed."""
return sr_period * math.sqrt(periods_per_year)
def years_needed(sr_annual, t_target=2.0):
"""Years of data for an annual Sharpe sr_annual to reach t >= t_target: (t_target / sr_annual)^2."""
return (t_target / sr_annual) ** 2
def prob_at_least_one(p, m):
"""m independent tries, each passing by luck with probability p: chance of at least one pass = 1 - (1 - p)^m."""
return 1 - (1 - p) ** m
def bonferroni(alpha, m):
"""Per-try threshold so that all m tries together give a false alarm no more than alpha."""
return alpha / m
def t_for_p(p):
"""One-sided t threshold for p, normal approximation (large samples)."""
return float(stats.norm.isf(p))
def posterior_after_signal(base_rate, sensitivity, false_alarm):
"""Bayes: of the times the signal fires, what share is a real event."""
hit = base_rate * sensitivity
miss = (1 - base_rate) * false_alarm
return hit / (hit + miss)
def ideas_passing(n_ideas, share_real, power, alpha):
"""Expected count: how many ideas pass on a real edge, how many by luck."""
real = n_ideas * share_real
pass_real, pass_luck = real * power, (n_ideas - real) * alpha
return {"with_edge": real, "pass_on_edge": pass_real, "pass_by_luck": pass_luck,
"luck_share": pass_luck / (pass_real + pass_luck)}
def correlation(x, y):
"""Pearson correlation r."""
a, b = _series(x), _series(y)
da, db = a - a.mean(), b - b.mean()
return float((da * db).sum() / math.sqrt((da ** 2).sum() * (db ** 2).sum()))
def r_squared(x, y):
"""R^2 of the regression y = a + b*x (with intercept) = 1 - residual sum of squares / total sum of squares."""
a, b = _series(x), _series(y)
resid = b - np.polyval(np.polyfit(a, b, 1), a)
return float(1 - (resid ** 2).sum() / ((b - b.mean()) ** 2).sum())
def expected_max_normal(m):
"""Expected value of the largest of m independent standard normals (numerical integral). m = 2 gives 1/sqrt(pi)."""
if m == 1:
return 0.0
def density(z): # z * density of the max of m draws
return z * m * stats.norm.pdf(z) * stats.norm.cdf(z) ** (m - 1)
return float(integrate.quad(density, -12, 12, limit=200)[0])tests/test_stats_lab.py:
# tests/test_stats_lab.py: golden tests for src/stats_lab.py. Expected values come from independent places (a published
# worked example, closed-form results, scipy, numpy, pandas), never from the function under test.
# Run: .venv\Scripts\python -m pytest -q tests\test_stats_lab.py
import math
import numpy as np
import pandas as pd
import pytest
from scipy import stats
from src import stats_lab as sl
SERIES_8 = [2, 4, 4, 4, 5, 5, 7, 9] # mean 5, sum of squared deviations 32
def test_ddof_sample_and_population():
assert sl.std_dev(SERIES_8, ddof=0) == pytest.approx(2.0) # divide by n = 8
assert sl.std_dev(SERIES_8) == pytest.approx(math.sqrt(32 / 7)) # divide by n - 1 = 7
assert np.std(SERIES_8) == pytest.approx(2.0) # numpy default ddof=0
assert pd.Series(SERIES_8).std() == pytest.approx(math.sqrt(32 / 7)) # pandas default ddof=1
def test_t_equals_sharpe_times_root_n():
r = np.random.default_rng(7).normal(0.05, 1.0, 250)
assert sl.t_stat(r) == pytest.approx(sl.t_from_sharpe(sl.sharpe(r), len(r)), rel=1e-12)
assert sl.t_stat(r) == pytest.approx(stats.ttest_1samp(r, 0.0).statistic, rel=1e-12)
def test_r2_equals_squared_correlation_with_one_variable():
rng = np.random.default_rng(11)
x = rng.normal(size=300)
y = 0.4 * x + rng.normal(size=300)
assert sl.r_squared(x, y) == pytest.approx(sl.correlation(x, y) ** 2, rel=1e-10)
assert sl.correlation(x, y) == pytest.approx(np.corrcoef(x, y)[0, 1], rel=1e-12)
def test_interval_matches_published_example():
low, high, t_crit = sl.ci_from_summary(9.261460, 0.022789, 195, 0.95)
assert t_crit == pytest.approx(1.9723, abs=1e-4)
assert low == pytest.approx(9.258242, abs=1e-6)
assert high == pytest.approx(9.264679, abs=1e-6)
assert sl.ci_from_summary(0.4, 1.4, 25)[2] == pytest.approx(2.064, abs=5e-4) # t table, 24 degrees of freedom
def test_interval_containing_0_is_no_evidence():
res = sl.confidence_interval([2, -1, -1] * 10) # +2R once, -1R twice: mean R exactly 0
assert res["n"] == 30 and res["mean"] == pytest.approx(0.0, abs=1e-12)
assert res["contains_0"] is True
def test_multiple_tries_and_bonferroni():
assert sl.prob_at_least_one(0.05, 1) == pytest.approx(0.05)
assert sl.prob_at_least_one(0.05, 20) == pytest.approx(1 - 0.95 ** 20)
assert sl.prob_at_least_one(0.05, 20) == pytest.approx(0.6415, abs=1e-4)
assert sl.bonferroni(0.05, 20) == pytest.approx(0.0025)
assert sl.t_for_p(0.025) == pytest.approx(1.959964, abs=1e-6)
def test_bayes_and_expected_max():
assert sl.posterior_after_signal(0.5, 0.8, 0.2) == pytest.approx(0.8)
assert sl.posterior_after_signal(0.01, 0.8, 0.2) == pytest.approx(0.008 / (0.008 + 0.198))
assert sl.expected_max_normal(2) == pytest.approx(1 / math.sqrt(math.pi), rel=1e-9)
def test_min_trades_and_trades_needed():
n = sl.min_trades(0.1, 1.4)
def half_width(k):
return stats.t.ppf(0.975, k - 1) * 1.4 / math.sqrt(k)
assert half_width(n) < 0.1 <= half_width(n - 1) # exactly on the boundary
assert sl.trades_needed(40, 50) == 15 # 0.8 sd shift, 80%: n 14.30 -> 15
assert sl.trades_needed(40, 50, chance=0.9) == 19 # 90%: n 18.45 -> 19
assert sl.chance_above_0(40, 50, 15) == pytest.approx(0.8213, abs=1e-4) # power 0.8213 at n = 15
assert sl.trades_needed(1.0, 1.0, chance=0.9, level=0.90) == 11 # (1.860 + 1.397)^2 = 10.6 -> 11
assert sl.years_needed(1.0) == pytest.approx(4.0)Expected: the last line reads 8 passed.
| You see | Cause | Fix |
|---|---|---|
No module named 'scipy' or 'pandas' |
Packages not installed in .venv |
.venv\Scripts\python -m pip install -r requirements.txt |
No module named 'src' |
Wrong folder, or bare pytest instead of python -m pytest |
cd C:\trading-agent-lab, then run the last line above exactly |
No matching distribution found for numpy==2.5.5 |
.venv Python older than 3.12, or an old pip |
.venv\Scripts\python --version; recreate .venv on a newer Python; python -m pip install -U pip |
2 failed in the ddof and Sharpe tests |
std_dev changed to plain np.std (ddof=0) |
Compare with the file above; don’t change the test |
1 failed in the published-example test |
1.96 used instead of the t multiplier, t looked up at n instead of n − 1, or divided by √(n − 1) instead of √n | Keep stats.t.ppf(1 - (1 - level) / 2, n - 1) and sd / math.sqrt(n) |
UnicodeEncodeError: 'charmap' codec when an agent runs a script |
On Windows, piped output uses the legacy code page | Keep printed text ASCII, or add -X utf8 after .venv\Scripts\python |
Applying it to backtest trade logs
The trade logs here come from a backtest of 13 methods on XAUUSD from 1 January 2018 to 11 November 2026, on M5 candles built from historical bid and ask quotes. Net R per trade includes spread, slippage and commission. It does not include swap, margin or compounding. These are simulated trades, not real fills.
src/confidence_interval.py works on any CSV with one closed trade per row
and a net R column (pass a different column name after the path). If the file
has an entry_time column, it also turns trades needed into years.
# src/confidence_interval.py: read a CSV trade log (one closed trade per row, a net R column) and print
# the mean R, its 95% confidence interval and t.
# Run: .venv\Scripts\python src\confidence_interval.py data\trades.csv [R column name, default R]
import csv
import sys
from datetime import datetime
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 import stats_lab as sl
path = sys.argv[1]
col = sys.argv[2] if len(sys.argv) > 2 else "R"
with open(path, encoding="utf-8-sig") as f:
rows = list(csv.DictReader(f))
r = [float(row[col]) for row in rows]
res = sl.confidence_interval(r)
print(f"Trade log: {Path(path).name} | column {col}")
print(f"Trades n : {res['n']}")
print(f"Mean R : {res['mean']:+.3f}R (median {res['median']:+.3f}R)")
print(f"Std dev (n-1) : {res['sd']:.3f}R | standard error {res['se']:.3f}R")
print(f"t : {res['t']:.2f} (two-sided 95% threshold: {res['t_crit']:.3f})")
print(f"95% interval : {res['low']:+.3f}R to {res['high']:+.3f}R")
if res["contains_0"]:
print("Verdict : NO EVIDENCE YET (interval contains 0)")
else:
print("Verdict : interval wholly", "above" if res["low"] > 0 else "below",
"0 (one test, not adjusted for the number of tries)")
for k in (1, 2): # drop the k biggest winners: if the verdict changes, it rests on a few trades
if len(r) - k < 2:
print(f"Drop {k} biggest : not enough trades")
continue
rest = sl.confidence_interval(sorted(r)[:-k])
print(f"Drop {k} biggest : n {rest['n']} | mean R {rest['mean']:+.3f}R | "
f"95% {rest['low']:+.3f}R to {rest['high']:+.3f}R")
if res["mean"] > 0: # IF the true mean R equals the measured one: how many trades
floor = sl.min_trades(res["mean"], res["sd"])
need = sl.trades_needed(res["mean"], res["sd"])
print(f"If the true mean R is exactly {res['mean']:+.3f}R with std dev {res['sd']:.3f}R:")
print(f"Minimum trades : {floor} (at this n the interval clears 0 only "
f"{sl.chance_above_0(res['mean'], res['sd'], floor):.0%} of the time)")
print(f"Trades for 8 in 10 : {need}")
if "entry_time" in rows[0]: # with entry times, turn trades needed into years
times = sorted(datetime.fromisoformat(row["entry_time"].replace("Z", "+00:00")) for row in rows)
years = (times[-1] - times[0]).days / 365.25
pace = res["n"] / years
print(f"Trade pace : {res['n']} trades in {years:.1f} years = {pace:.1f} a year "
f"-> {floor} trades ~ {floor / pace:.0f} years | {need} trades ~ {need / pace:.0f} years")
print("Simulation on historical data, not investment advice.")cd C:\trading-agent-lab
notepad src\confidence_interval.py
.venv\Scripts\python src\confidence_interval.py data\your-trades.csvMACD cross filtered by EMA200, fixed SL/TP: 168 trades, mean R +0.096R, median −1.006R. Standard deviation 1.451R, SE 0.112R, t = 0.85. 95% interval −0.126R to +0.317R: contains 0, no evidence yet.
Trades n : 168
Mean R : +0.096R (median -1.006R)
Std dev (n-1) : 1.451R | standard error 0.112R
t : 0.85 (two-sided 95% threshold: 1.974)
95% interval : -0.126R to +0.317R
Verdict : NO EVIDENCE YET (interval contains 0)
Drop 1 biggest : n 167 | mean R +0.084R | 95% -0.137R to +0.305R
Drop 2 biggest : n 166 | mean R +0.073R | 95% -0.149R to +0.294R
If the true mean R is exactly +0.096R with std dev 1.451R:
Minimum trades : 889 (at this n the interval clears 0 only 50% of the time)
Trades for 8 in 10 : 1813
Trade pace : 168 trades in 8.4 years = 20.0 a year -> 889 trades ~ 45 years | 1813 trades ~ 91 years
Simulation on historical data, not investment advice.If the true mean really were +0.096R, the minimum is 889 trades, about 45 years at this method’s pace of 20 trades a year, and even then the interval clears 0 only half the time. Eight in ten takes about 1,813 trades, roughly 91 years. Two kinder cost scenarios still contain 0: historical spread with no commission and no slippage gives −0.100R to +0.343R; a flat 0.04 USD spread with no commission or slippage gives −0.048R to +0.398R (for comparison, the data’s median 2025 spread was 0.58 USD).
Donchian 55/20 breakout: 34 trades, mean R +1.197R but median −0.496R. The mean is high because of a few huge trades, the largest +21.6R. Drop the biggest and it falls to +0.577R; drop two and it’s +0.294R. The verdict rests on one or two trades. With R this skewed, the trades-needed numbers (56 and 111) are rough t-based estimates. Trades are held about 43 days at the median, so swap, not included here, could matter.
To reproduce it, save these 34 values (in entry order) as data/donchian.csv:
R
3.27903
-0.50809
-1.00984
1.61332
-1.0091
9.65172
-1.00555
-1.01134
-1.00182
-0.72894
2.05375
-1.0031
0.2916
0.08618
-1.00373
-1.00463
-1.00572
1.07367
-0.15376
-0.08993
-1.00413
2.06641
-0.48306
-1.00426
-1.00634
0.66902
5.23264
-1.00296
1.4483
8.34749
21.62988
0.27848
-1.00102
-1.00142Trade log: donchian.csv | column R
Trades n : 34
Mean R : +1.197R (median -0.496R)
Std dev (n-1) : 4.443R | standard error 0.762R
t : 1.57 (two-sided 95% threshold: 2.035)
95% interval : -0.354R to +2.747R
Verdict : NO EVIDENCE YET (interval contains 0)
Drop 1 biggest : n 33 | mean R +0.577R | 95% -0.355R to +1.509R
Drop 2 biggest : n 32 | mean R +0.294R | 95% -0.462R to +1.050R
If the true mean R is exactly +1.197R with std dev 4.443R:
Minimum trades : 56 (at this n the interval clears 0 only 51% of the time)
Trades for 8 in 10 : 111
Simulation on historical data, not investment advice.Across all 13 methods (default variants, the same costs), none has an interval wholly above 0. Eight are wholly below 0; five contain 0.
| Method | Trades | Mean R | 95% interval | Interval |
|---|---|---|---|---|
| 01 | 869 | −0.060R | −0.154R to +0.034R | contains 0 |
| 02 (MACD + EMA200) | 168 | +0.096R | −0.126R to +0.317R | contains 0 |
| 03 | 898 | −0.132R | −0.349R to +0.085R | contains 0 |
| 04 | 24 | −0.631R | −0.964R to −0.298R | below 0 |
| 05 | 901 | −0.016R | −0.109R to +0.076R | contains 0 |
| 06 | 30,802 | −0.851R | −0.860R to −0.842R | below 0 |
| 07 | 107,042 | −2.328R | −2.333R to −2.323R | below 0 |
| 08 | 1,177 | −0.220R | −0.293R to −0.146R | below 0 |
| 09 | 1,123 | −0.207R | −0.284R to −0.131R | below 0 |
| 10 | 2,668 | −0.141R | −0.187R to −0.095R | below 0 |
| 11 | 2,110 | −0.138R | −0.189R to −0.086R | below 0 |
| 12 (Donchian 55/20) | 34 | +1.197R | −0.354R to +2.747R | contains 0 |
| 13 | 441 | −0.259R | −0.376R to −0.143R | below 0 |
Method 07 loses more than 1R a trade because its SL sat only 0.20 USD from entry, tighter than the data’s median spread in every year 2018–2026 (0.23 to 0.66 USD): 105,202 of 107,042 trades hit the SL the moment they filled, so spread, slippage and commission in R exceeded the SL distance itself.
The Donchian method has the highest mean R. But picking the top one of 13 is 13 tries. With the adjustment in the multiple-testing section, the t threshold for 13 tries is 2.89; its t is 1.57.
These intervals treat trades as independent and aren’t corrected for serial dependence. The whole 2018–2026 period has been seen; there’s no sealed hold-out yet. Simulation on historical data, not investment advice.
So don’t feed these mean R values into a position-sizing formula. Kelly sizing takes estimates like mean R and the outcome distribution as inputs, and it’s very sensitive to their errors: lower one input slightly and the Kelly fraction drops sharply. While the interval for mean R still contains 0, its lower bound is a loss, so there’s no basis for raising risk per trade. Keep a small fixed risk on demo, with the lot computed by code from the broker’s contract specs and rounded down to 0.01.
Sharpe, t = Sharpe × √n, and gold’s real session count
Per-session Sharpe = mean return per session ÷ standard deviation of session returns, with the risk-free rate at 0, as MT5’s Strategy Tester does. Put it next to the formula above and t = per-session Sharpe × √n, where n is the number of sessions you have. That’s exact, not an approximation, when Sharpe uses the sample standard deviation; golden test 2 checks it.
So a nice Sharpe on a short history is weak evidence. An agent reports “annual Sharpe 2.0” after 3 months of demo. At 260 sessions a year, 3 months is 65 sessions and the per-session Sharpe is 0.124, so t = 1.00, far from the 1.96 of a 95% interval.
Annualised it’s simpler: t = annual Sharpe × √(years), independent of sessions per year.
| Annual Sharpe | Years of data for t ≥ 2 | Years for t ≥ 3 |
|---|---|---|
| 0.5 | 16 | 36 |
| 1.0 | 4 | 9 |
| 1.5 | 1.78 | 4 |
| 2.0 | 1 | 2.25 |
| 3.0 | 0.44 | 1 |
Converting a per-session Sharpe to annual needs the real session count. On XAUUSD H1 in UTC, 2025 had 312 days with candles, including 52 Sundays with a median of 2 candles at the reopen. Fold those into Monday and you get 260 Monday–Friday sessions, √260 = 16.12. The same per-session Sharpe of 0.10 annualises to:
| Per-session Sharpe 0.10, annualised with | Annual Sharpe |
|---|---|
| 260 Monday–Friday sessions counted from the data | 1.61 |
| 252, the familiar equities number | 1.59 |
| 312 days with candles, Sundays included | 1.77 |
| 365 calendar days | 1.91 |
Counting the Sunday candles inflates annual Sharpe by about 9.5%; 365 days by about 18.5%. Another period or symbol may give 259 or 261 (EURUSD 2025 was 261); one or two sessions change annual Sharpe by under 0.4%. Your MT5 file is in server time, usually a few hours ahead of UTC, so the Sunday reopen may land on Monday. Count on your own file.
Two caveats. A monthly Sharpe can’t be annualised by multiplying by √12 except in special cases: serial correlation (this month’s return depending on last month’s) can inflate the annual figure a lot, by up to 65% for some hedge funds. Multiplying by √(sessions) is only right when session returns are independent and identically distributed. And a per-trade Sharpe (mean R ÷ std dev of R) doesn’t annualise by sessions, because trades don’t arrive evenly. For it use t = per-trade Sharpe × √(trades) directly. The MACD method above has a per-trade Sharpe of 0.066 and t = 0.85.
src/count_sessions.py counts sessions per year and the base rate of
wide-range sessions:
# src/count_sessions.py: count sessions with candles per year (to annualise Sharpe) and the share of
# wide-range sessions (a base rate).
# Run: .venv\Scripts\python src\count_sessions.py data\xauusd_h1_mt5.csv [range threshold, default 0.03 = 3%]
# CSV columns time,open,high,low,close,...; time is the candle open, e.g. 2025-01-02 00:00:00 (2025-01-02T00:00:00Z works too).
import csv
import math
import statistics
import sys
from collections import defaultdict
from datetime import datetime, timedelta
path = sys.argv[1]
threshold = float(sys.argv[2]) if len(sys.argv) > 2 else 0.03
by_day = defaultdict(list) # date -> [(open, high, low)], in time order
with open(path, encoding="utf-8-sig") as f:
for row in csv.DictReader(f):
t = datetime.fromisoformat(row["time"][:19]) # [:19] drops a zone suffix such as Z
by_day[t.date()].append((float(row["open"]), float(row["high"]), float(row["low"])))
# A session is a Monday-Friday date with candles; Saturday/Sunday candles (usually 1-2 at the reopen) go to the next Monday.
sessions = defaultdict(list)
for day, candles in sorted(by_day.items()):
wd = day.weekday() # 0 = Monday ... 6 = Sunday
target = day + timedelta(days=7 - wd) if wd >= 5 else day
sessions[target].extend(candles)
print(f"File: {path} | {sum(len(v) for v in by_day.values())} candles | {min(by_day)} -> {max(by_day)}")
print("Year | days with candles | of which Sat/Sun (candles/day) | Mon-Fri sessions | sqrt(sessions)")
for year in sorted({d.year for d in by_day}):
days = [d for d in by_day if d.year == year]
weekend = [d for d in days if d.weekday() >= 5]
wk_candles = statistics.median(len(by_day[d]) for d in weekend) if weekend else 0
n_sessions = sum(1 for d in sessions if d.year == year)
print(f"{year} | {len(days):17d} | {len(weekend):3d} days (median {wk_candles:g} candles) | "
f"{n_sessions:16d} | {math.sqrt(n_sessions):6.2f}")
# Full weeks (drop the file's first and last week): sessions and days with candles per week; works on short files too.
week_sessions, week_days = defaultdict(set), defaultdict(set)
for d in sessions:
week_sessions[d.isocalendar()[:2]].add(d)
for d in by_day:
week_days[d.isocalendar()[:2]].add(d)
keys = sorted(week_sessions)[1:-1]
if keys:
per_week = statistics.median(len(week_sessions[k]) for k in keys)
days_per_week = statistics.median(len(week_days[k]) for k in keys)
print(f"Full weeks: {len(keys)} | median {per_week:g} sessions/week, {days_per_week:g} days with candles/week")
print(f"One-year estimate (x 52): {per_week * 52:g} Mon-Fri sessions (--sessions) | "
f"{days_per_week * 52:g} days with candles (--days)")
# Base rate: share of sessions whose range (high - low) >= threshold x the session's first open.
ranges = [(max(h for _, h, _ in c) - min(l for _, _, l in c)) / c[0][0] for c in sessions.values()]
wide = sum(1 for x in ranges if x >= threshold)
print(f"Sessions with range >= {threshold:.1%}: {wide}/{len(ranges)} = {wide / len(ranges):.1%} (base rate)")cd C:\trading-agent-lab
notepad src\count_sessions.py
.venv\Scripts\python src\count_sessions.py data\xauusd_h1_mt5.csv 0.05On the 2025–2026 XAUUSD H1 data above it prints:
File: data\xauusd_h1_mt5.csv | 10831 candles | 2025-01-01 -> 2026-10-30
Year | days with candles | of which Sat/Sun (candles/day) | Mon-Fri sessions | sqrt(sessions)
2025 | 312 | 52 days (median 2 candles) | 260 | 16.12
2026 | 259 | 43 days (median 2 candles) | 216 | 14.70
Full weeks: 94 | median 5 sessions/week, 6 days with candles/week
One-year estimate (x 52): 260 Mon-Fri sessions (--sessions) | 312 days with candles (--days)
Sessions with range >= 5.0%: 18/476 = 3.8% (base rate)If your file covers less than a year (a 2,000-candle H1 export is about 4 months), the year rows are partial: don’t use them. Take the one-year estimate line, built from full weeks × 52. Base rates need long samples too: 0 of 23 sessions in one month with a 5% range doesn’t mean it never happens. With a short file, keep the 18/476 and 73/476 above.
Multiple testing: a trial log and thresholds written first
Every parameter change, every added filter, every “let the agent try a few more” is a try. If a variant with no edge passes by luck with probability p, then over m independent variants the chance that at least one passes is 1 − (1 − p)^m. At p = 0.05: 64.2% for 20 variants, 99.4% for 100. With this post’s criterion (95% interval wholly above 0, so p = 0.025 a variant): 39.7% for 20, 71.8% for 50.
Variants are usually similar, so the real figure is lower, sometimes much lower: 20 variants whose results correlate at 0.8 give about 11%. The direction holds: the more you try, the less the best one tells you. Because variants are similar, the adjustment below is conservative.
The simplest adjustment is Bonferroni: divide the threshold by the number of tries. To keep the chance of any false alarm across m tries at 2.5%, each variant must reach p ≤ 0.025 ÷ m. As t for large samples:
| m variants | p = 0.05 each | p = 0.025 each | t threshold |
|---|---|---|---|
| 1 | 5.0% | 2.5% | 1.96 |
| 5 | 22.6% | 11.9% | 2.58 |
| 10 | 40.1% | 22.4% | 2.81 |
| 20 | 64.2% | 39.7% | 3.02 |
| 50 | 92.3% | 71.8% | 3.29 |
| 100 | 99.4% | 92.0% | 3.48 |
After hundreds of equity factors have been tried, a new factor should clear about t = 3.0 rather than the familiar 2.0. The same logic applies to your variants.
Sharpe inflates with tries too. If m variants all have a true Sharpe of 0, the best annual Sharpe among them has an expected value of about E[max] ÷ √(years), where E[max] is the expected largest of m standard normals. Try 45 variants on 1 year of data and the best has an expected annual Sharpe of 2.21; on 5 years it’s still 0.99. With 5 years of data, about 45 configurations are enough to fool you.
| m | Best expected after 1 year | After 5 years | Years until ≤ 1.0 |
|---|---|---|---|
| 10 | 1.54 | 0.69 | 2.4 |
| 45 | 2.21 | 0.99 | 4.9 |
| 100 | 2.51 | 1.12 | 6.3 |
| 1,000 | 3.24 | 1.45 | 10.5 |
So two files must exist before you run anything.
reports/threshold-before-run.md: trades needed (from trades_needed at 8
in 10, for the smallest after-cost edge you want to detect, not
min_trades); the pass criterion (lower bound of the 95% interval of
after-cost mean R above 0); the maximum number of variants and the adjusted t
threshold; the selection period and the sealed hold-out period.
reports/trial-log.csv: one row per try, including bad ones, broken ones
and ones the agent ran on its own. When you conclude, m is the number of data
rows (not counting the header), not the number of variants you’d like to
mention.
Commit both with git for a timestamp.
# Threshold written first · [DATE] · not edited after running
System: [NAME + VERSION] · Symbol: XAUUSD · Timeframe: [H1]
Selection data: [2023-01 to 2025-12] · Sealed data: [2026-01 to 2026-10], opened once
Costs included: spread, commission, slippage [NUMBER] · Not included: swap
Max variants m: [10] · Adjusted t threshold: [2.81] (Bonferroni 0.025 ÷ m, large sample)
1. At least [200] closed trades on the selection data.
2. Lower bound of the 95% interval of mean R above 0, and t not below the threshold above.
3. Dropping the 2 biggest winners, mean R stays positive.
4. Sealed data run exactly once on the locked version; record mean R and the 95% interval even if bad.
No criterion based on win rate.reports/trial-log.csv, created with just this header:
date,version,change,data,trades,mean_r,interval_95,t,run_by,noteA row added after each try (never delete old rows):
[2026-11-24],v2,[EMA 20 to 30],[2023-01..2025-12],[N],[MEAN],[LOW..HIGH],[T],agent,[agent tried this itself]notepad reports\threshold-before-run.md
notepad reports\trial-log.csv
git add reports\threshold-before-run.md reports\trial-log.csv
git commit -m "Lock threshold before run and open trial log"Git prints a short commit hash and 2 files changed. nothing to commit
means a file wasn’t saved: go back to Notepad and press Ctrl + S.
The gates a best-of-many result has to pass before you believe it:
| Gate | Check | If it fails |
|---|---|---|
| 1 | Threshold and trial log committed before the run | Not locked: write the threshold, commit, then run |
| 2 | m is every data row of the trial log | Wrong m: count bad, broken and agent-run variants too |
| 3 | Lower bound of the 95% interval above 0 | No evidence yet |
| 4 | t at or above the Bonferroni threshold (m = 20: 3.02) | Could be luck |
| 5 | Mean R stays positive after dropping the 2 biggest winners | Rests on one or two trades |
| 6 | Sealed data run exactly once on the locked version | Record the result even if bad; don’t rerun |
src/luck_tables.py prints every table in this post from the library:
# src/luck_tables.py: the "luck or skill" tables. Probabilities in sections 1-4 are ASSUMPTIONS for illustration;
# the two base rates (--base, --base2) and the session counts (--sessions, --days) come from src/count_sessions.py.
# Run: .venv\Scripts\python src\luck_tables.py --base 18/476 --base2 73/476 --sessions 260 --days 312
import argparse
import math
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from src import stats_lab as sl
def fraction(s):
a, _, b = s.partition("/")
return float(a) / float(b) if b else float(a)
ap = argparse.ArgumentParser()
ap.add_argument("--base", type=fraction, default=0.05, help="base rate, e.g. 18/476 or 0.038")
ap.add_argument("--base2", type=fraction, default=0.15, help="a second base rate to compare, e.g. 73/476")
ap.add_argument("--sessions", type=int, default=260, help="Monday-Friday sessions per year")
ap.add_argument("--days", type=int, default=312, help="days with candles per year, weekends included")
a = ap.parse_args()
print("1) An '80% accurate' signal (assumed: fires on 80% of event sessions, false alarm on 20% of others), 1,000 sessions")
print(" Base rate | event sessions | hits | false alarms | share of alarms that are real")
for p in (a.base, a.base2, 0.5):
ev = 1000 * p
print(f" {p:9.1%} | {ev:14.0f} | {0.8 * ev:4.0f} | {0.2 * (1000 - ev):12.0f} | "
f"{sl.posterior_after_signal(p, 0.8, 0.2):.1%}")
print("2) 1,000 ideas, backtest threshold p = 0.05, an idea with a real edge passes half the time (assumed)")
print(" Share with edge | with edge | pass on edge | pass by luck | share of passes due to luck")
for share in (0.01, 0.05, 0.20):
k = sl.ideas_passing(1000, share, 0.5, 0.05)
print(f" {share:15.0%} | {k['with_edge']:9.0f} | {k['pass_on_edge']:12.1f} | {k['pass_by_luck']:12.1f} | "
f"{k['luck_share']:.0%}")
print("3) m variants with NO edge: chance at least one 'passes' by luck, and the t threshold that holds it at 2.5%")
print(" m | p = 0.05 each | 95% interval above 0 (p = 0.025) | t threshold (Bonferroni, large sample)")
for m in (1, 5, 10, 20, 50, 100):
print(f" {m:3d} | {sl.prob_at_least_one(0.05, m):13.1%} | {sl.prob_at_least_one(0.025, m):32.1%} | "
f"{sl.t_for_p(sl.bonferroni(0.025, m)):.2f}")
print("4) Expected best annual Sharpe of m variants whose true Sharpe = 0 (annual Sharpe error ~ 1 / sqrt(years))")
print(" m | after 1 year | after 5 years | years until expectation <= 1.0")
for m in (10, 45, 100, 1000):
e = sl.expected_max_normal(m)
print(f" {m:4d} | {e:12.2f} | {e / math.sqrt(5):13.2f} | {e ** 2:.1f}")
print("5) Sharpe and sessions: annual Sharpe = session Sharpe x sqrt(sessions/year); "
"t = session Sharpe x sqrt(sessions so far)")
for label, n in ((f"{a.sessions} Mon-Fri sessions counted from the CSV", a.sessions), ("252 from equities", 252),
(f"{a.days} days with candles, Sunday candles included", a.days), ("365 calendar days", 365)):
print(f" Session Sharpe 0.10 -> annual Sharpe {sl.annual_sharpe(0.10, n):.2f} using {label}")
quarter = round(a.sessions / 4)
sr = 2.0 / math.sqrt(a.sessions)
print(f" Annual Sharpe 2.0 over 3 months ({quarter} sessions): session Sharpe {sr:.3f}, "
f"t = {sl.t_from_sharpe(sr, quarter):.2f}")
print(" Annual Sharpe | years for t >= 2 | years for t >= 3")
for s in (0.5, 1.0, 1.5, 2.0, 3.0):
print(f" {s:13.1f} | {sl.years_needed(s, 2.0):16.2f} | {sl.years_needed(s, 3.0):.2f}").venv\Scripts\python src\luck_tables.py --base 18/476 --base2 73/476 --sessions 260 --days 312On your own file, take --sessions and --days from a full year’s row, or
from the one-year estimate line if the file is shorter. The other numbers
(80% sensitivity, 20% false alarms, the 50% base-rate row, p and the share of
ideas with an edge) are assumptions for illustration.
Try it: the agent writes the stats report from script output
Save as prompts/stats-report-v1.md:
<role>
You write the statistics report for a backtest or shadow result. You compute no number yourself: every
number comes from the output of the commands below. You don't recommend buying or selling and don't
suggest increasing size.
</role>
<data>
Trade log: [data/FILE.csv], one closed trade per row, column R is net R.
Costs included: [spread, commission, slippage]. Not included: [swap].
Period: [FROM DATE to TO DATE]. Trial log: reports/trial-log.csv. Pre-written threshold: reports/threshold-before-run.md.
</data>
<tasks>
1. Run .venv\Scripts\python src\confidence_interval.py [data/FILE.csv] and paste the output verbatim.
2. Run .venv\Scripts\python -c "import csv; from src import stats_lab as sl; m = len(list(csv.DictReader(open('reports/trial-log.csv', encoding='utf-8-sig')))); print(m, sl.prob_at_least_one(0.025, m), sl.t_for_p(sl.bonferroni(0.025, m)))" and paste the output: the first number is m, the number of tries, counted by code; don't count it yourself.
3. Compare each threshold in reports/threshold-before-run.md: met or not, with the number.
</tasks>
<constraints>
Always state the trade count next to mean R. If the 95% interval contains 0, write exactly: "No evidence yet
that mean R differs from 0." Don't use win rate to conclude anything. Don't round differently from the
script output. If a file is missing or a command errors, stop, paste the error, don't guess numbers.
</constraints>
<output>
At most 12 lines: trade count, mean R, median, 95% interval, t, results after dropping the 1 and 2
biggest winners, m and the adjusted t threshold, each threshold met or not, costs not included, and the
sentence "This is an analysis of historical data, not investment advice." The decision is the reader's.
</output>The order to work in:
- Before running: write the threshold (trades needed from
trades_needed, the 95% interval criterion, maximum variants, adjusted t) and commit it. - Log every try, including bad ones, broken ones and the agent’s own.
- Compute net R per trade after costs; the denominator is every closed trade.
- Run
src/confidence_interval.py: mean R, median, 95% interval, t and the drop-the-biggest check. An interval containing 0 is no evidence yet. - Adjust for the number of tries: after many tries, require t of about 3 or more.
- Annualise Sharpe only with sessions counted from your candle file, and remember t = per-session Sharpe × √(sessions).
- The agent writes the report from numbers the code printed; you decide, and you don’t raise risk on a result without evidence.
Key takeaways
- A 95% interval of mean R that contains 0 is no evidence yet. Always state the trade count and which costs are included and which aren’t (swap) next to mean R.
- t = per-session Sharpe × √n: an annual Sharpe of 2.0 after 3 months gives t = 1.00. Annualise with sessions counted from your candle file (gold in 2025: 260).
- Trying m variants gives 1 − (1 − p)^m: 20 variants at p = 0.05 is 64.2%. Log every try and write the t threshold before you run.
- Statistics come from a tested library, never from the agent’s head.
Comments