How do you tune parameters so that the final test period is still data you never used to choose?
This post writes the test plan first: a few combinations decided in advance, the same costs and exits for all, and data split by time into train, validation and test. Then a script logs every run, locks the choice and opens the test period once. The easy mistake: looking at the test and adjusting again. After that, the period isn’t out-of-sample any more; you need new data or a forward run.
Terms used below:
- Parameter search: trying parameter values inside a space you chose. It can overfit even when no code changes.
- Train, validation, test: three periods in time order. Train is for building, validation for choosing, test for judging one locked version.
- Out-of-sample: data that played no part in any choice.
- Hash: a short fingerprint of a file; change one character and it changes. Here it proves the plan and the data didn’t change after locking.
- m: the number of runs you made, bad ones included.
Decide the search before you see a result
Write down first: a small range of parameters and why, how many runs you allow, the costs, and what counts as a failure. Split the data by time and never use the test period to choose. Keep the bad reports too. Once you’ve picked one version, lock it with a hash, open the test period once, and record that you’ve looked. MT5’s forward period in the Strategy Tester helps with the split, but it doesn’t solve every leak of labels or features into the past.
| Gate | Question | If not |
|---|---|---|
| Input | The parameter set just chosen on validation | |
| 1 | Was every run written down in advance, with all results reported? | Log them all, bad ones included; don’t hide runs |
| 2 | Same costs, exits and timeline for every run? | Run again under the same assumptions |
| 3 | Locked before the test period was opened? | Lock the hash and the log first |
| 4 | The test period never used to choose or adjust? | Record that the test was used; you need a new sample or a new forward run |
| Passed | Open the test period once; a bad result is still recorded as bad |
A period only stays out-of-sample while it hasn’t been used to choose or change a decision.
Three versions against forty hidden ones
You test Length 10, 20 and 30, written down beforehand.
- Keep the same costs, exits and timeline.
- Pick the metric in advance and report all three results.
- Lock the chosen version, then check it on the later data you haven’t used.
- If the test version is bad, record it as bad. Don’t go back, pick another version, and still call the test sealed.
Three versions reported in full say more than one good version picked out of forty you never mention.
Worked example: four combinations, locked before the test
Only EMA fast 8 or 12 and slow 21 or 26: four combinations. Exits, costs, data and risk limits are fixed. Don’t try ten more indicators at the same time to rescue a bad result. Save every run, including errors and losses.
| Period | Dates | Job |
|---|---|---|
| Train | 2025-01 to 2025-08 | Build, inside the parameter space written in advance |
| Validation | 2025-09 to 2025-12 | Choose within that space; compare the peak with its neighbours |
| Test | 2026-01 to 2026-10, opened once | Judge the locked version; if you adjust after looking, record the test as used |
| Before a demo | After the test | Runs outside the development period; sensitivity to costs and slippage |
The plan, plan.json, written and committed before the first run:
{
"version": "ema-long-v1",
"why": "two common fast and two common slow EMA lengths; nothing else changes",
"fast": [8, 12],
"slow": [21, 26],
"cost_pct_per_side": 0.01,
"metric": "net_return_pct",
"min_trades": 20,
"fail_if": "best validation return not above 0, or fewer than min_trades on validation",
"data": "data/xauusd_h1_utc.csv",
"train": ["2025-01-01", "2025-08-31"],
"validation": ["2025-09-01", "2025-12-31"],
"test": ["2026-01-01", "2026-10-31"]
}The script, src/tuning.py. lock runs every combination on train and
validation, appends each run to reports/trial-log.csv, picks the best
validation result by the metric in the plan, and writes the choice and both
hashes to reports/manifest.json. open-test refuses if the plan or data
changed after locking, runs the locked choice on the test period, records the
result, and refuses every later attempt:
# src/tuning.py: try a small parameter grid written in plan.json, choose on validation, lock, then open the test period once.
# Reads candles from a CSV (time in UTC, open, high, low, close); no network, no orders.
# .venv\Scripts\python src\tuning.py lock runs every combination on train and validation, logs each run, locks the choice
# .venv\Scripts\python src\tuning.py open-test runs the locked choice on the test period, once
import csv, hashlib, json, sys
from datetime import datetime, timezone
from pathlib import Path
LOG_HEADER = ["date", "version", "change", "data", "trades", "net_return_pct", "max_dd_pct", "run_by", "note"]
def sha(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:12]
def load_candles(path):
with open(path, newline="") as f:
return [dict(time=r["time"], open=float(r["open"]), close=float(r["close"])) for r in csv.DictReader(f)]
def ema(values, n):
k, out, e = 2 / (n + 1), [], None
for v in values:
e = v if e is None else e + k * (v - e)
out.append(e)
return out
def backtest(candles, fast, slow, cost_pct, start, end):
"""Long while EMA fast > EMA slow. Signal on a closed candle, fill at the next candle's open.
EMAs use all earlier candles; trades only inside [start, end]. cost_pct is charged on each side."""
closes = [c["close"] for c in candles]
ef, es = ema(closes, fast), ema(closes, slow)
idx = [i for i, c in enumerate(candles) if start <= c["time"][:10] <= end]
c = cost_pct / 100
equity, peak, dd, trades, entry = 1.0, 1.0, 0.0, 0, None
for i in idx[:-1]:
nxt = candles[i + 1]["open"]
if i < slow: # warm-up
continue
if entry is None and ef[i] > es[i]:
entry = nxt * (1 + c)
elif entry is not None and ef[i] <= es[i]:
equity *= nxt * (1 - c) / entry
entry, trades = None, trades + 1
peak, dd = max(peak, equity), min(dd, equity / peak - 1)
if entry is not None: # close what's open at the period's last close
equity *= candles[idx[-1]]["close"] * (1 - c) / entry
trades += 1
peak, dd = max(peak, equity), min(dd, equity / peak - 1)
return dict(trades=trades, net_return_pct=round((equity - 1) * 100, 2), max_dd_pct=round(dd * 100, 2))
def log_run(base, plan, change, period, res, note=""):
path = base / "reports" / "trial-log.csv"
path.parent.mkdir(exist_ok=True)
new = not path.exists()
with open(path, "a", newline="") as f:
w = csv.writer(f)
if new:
w.writerow(LOG_HEADER)
w.writerow([datetime.now(timezone.utc).strftime("%Y-%m-%d"), plan["version"], change,
f"{period} {plan[period][0]}..{plan[period][1]}", res["trades"], res["net_return_pct"],
res["max_dd_pct"], "script", note])
def trial_count(base):
with open(base / "reports" / "trial-log.csv", newline="") as f:
return sum(1 for _ in csv.DictReader(f))
def lock(base=Path(".")):
if (base / "reports" / "test-opened.json").exists():
sys.exit("The test period is already opened. A new choice needs new data or a forward run, not a re-lock.")
plan = json.loads((base / "plan.json").read_text())
candles = load_candles(base / plan["data"])
rows = []
for f in plan["fast"]:
for s in plan["slow"]:
r = {p: backtest(candles, f, s, plan["cost_pct_per_side"], *plan[p]) for p in ("train", "validation")}
for p in r:
log_run(base, plan, f"fast={f} slow={s}", p, r[p])
rows.append((f, s, r))
print(f"{'fast':>4} {'slow':>4} | {'train trades':>12} {'return %':>8} | {'valid trades':>12} {'return %':>8}")
for f, s, r in rows:
print(f"{f:>4} {s:>4} | {r['train']['trades']:>12} {r['train']['net_return_pct']:>8.2f} |"
f" {r['validation']['trades']:>12} {r['validation']['net_return_pct']:>8.2f}")
ok = [x for x in rows if x[2]["validation"]["trades"] >= plan["min_trades"]]
if not ok:
sys.exit("No combination has enough trades on validation: the plan fails as written.")
f, s, r = max(ok, key=lambda x: x[2]["validation"][plan["metric"]])
best = r["validation"][plan["metric"]]
print(f"chosen on validation by {plan['metric']}: fast={f} slow={s} ({best:+.2f}%)")
for nf, ns, nr in rows:
if (nf == f) != (ns == s): # differs by exactly one step
print(f" neighbour fast={nf} slow={ns}: {nr['validation'][plan['metric']]:+.2f}%")
if best <= 0:
sys.exit("The best validation result isn't positive: the plan's fail criterion is met. Nothing to test.")
manifest = dict(version=plan["version"], chosen=dict(fast=f, slow=s), plan_sha=sha(base / "plan.json"),
data_sha=sha(base / plan["data"]), trials_m=trial_count(base),
locked_at=datetime.now(timezone.utc).isoformat(timespec="seconds"))
(base / "reports" / "manifest.json").write_text(json.dumps(manifest, indent=2))
print(f"locked: plan {manifest['plan_sha']} data {manifest['data_sha']} | m = {manifest['trials_m']} runs logged")
print("Commit plan.json and reports/ now, then run open-test once.")
def open_test(base=Path(".")):
rep = base / "reports"
if not (rep / "manifest.json").exists():
sys.exit("No locked choice. Run lock first.")
opened = rep / "test-opened.json"
if opened.exists():
sys.exit("The test period was already opened: " + json.dumps(json.loads(opened.read_text()))
+ " Running it again isn't out-of-sample any more; you need new data or a forward run.")
m = json.loads((rep / "manifest.json").read_text())
plan = json.loads((base / "plan.json").read_text())
if sha(base / "plan.json") != m["plan_sha"] or sha(base / plan["data"]) != m["data_sha"]:
sys.exit("plan.json or the data changed after locking. Lock again; the new runs count in the trial log.")
candles = load_candles(base / plan["data"])
f, s = m["chosen"]["fast"], m["chosen"]["slow"]
res = backtest(candles, f, s, plan["cost_pct_per_side"], *plan["test"])
t = [c for c in candles if plan["test"][0] <= c["time"][:10] <= plan["test"][1]]
hold = round((t[-1]["close"] / t[0]["open"] - 1) * 100, 2)
log_run(base, plan, f"fast={f} slow={s}", "test", res, "test, opened once")
record = dict(chosen=m["chosen"], **res, buy_and_hold_pct=hold,
opened_at=datetime.now(timezone.utc).isoformat(timespec="seconds"))
opened.write_text(json.dumps(record, indent=2))
print(f"test {plan['test'][0]}..{plan['test'][1]}: fast={f} slow={s} | {res['trades']} trades |"
f" {res['net_return_pct']:+.2f}% | max drawdown {res['max_dd_pct']:.2f}% | buy and hold {hold:+.2f}%")
print("Recorded in reports/test-opened.json. A bad result stays recorded as bad.")
if __name__ == "__main__":
{"lock": lock, "open-test": open_test}[sys.argv[1]]()The CSV needs a time column in UTC plus open, high, low and close. For MT5
candles, convert server time to UTC first, as in the backtest post. The
output below is on a made-up random-walk series (10,994 H1 candles), so no
rule has a real edge on it. The first lines:
time,open,high,low,close
2025-01-01T00:00Z,2650.0,2662.17,2649.48,2660.4
2025-01-01T01:00Z,2660.4,2661.8,2658.26,2659.17In Windows PowerShell, from C:\trade-system-lab:
git add plan.json
git commit -m "Tuning plan before any run"
.venv\Scripts\python src\tuning.py lock
git add plan.json reports
git commit -m "Lock ema-long-v1 before opening the test"
.venv\Scripts\python src\tuning.py open-test
git add reports
git commit -m "Test period opened once"lock prints:
fast slow | train trades return % | valid trades return %
8 21 | 101 -2.92 | 47 13.77
8 26 | 90 -3.69 | 49 10.37
12 21 | 82 -3.60 | 39 11.52
12 26 | 73 -1.64 | 35 12.41
chosen on validation by net_return_pct: fast=8 slow=21 (+13.77%)
neighbour fast=8 slow=26: +10.37%
neighbour fast=12 slow=21: +11.52%
locked: plan 7b307556ff22 data 1098236c9a88 | m = 8 runs logged
Commit plan.json and reports/ now, then run open-test once.All four combinations lose on train and all four make 10–14% on validation. On a random walk, that swing is luck, and the choice of 8/21 rests on a lead of 1.4 percentage points over the next-best combination. That’s what comparing with neighbours is for: a peak far above its neighbours is fragile; a flat area says the exact values barely matter.
open-test prints:
test 2026-01-01..2026-10-31: fast=8 slow=21 | 117 trades | +8.57% | max drawdown -4.81% | buy and hold +12.80%
Recorded in reports/test-opened.json. A bad result stays recorded as bad.+8.57% on the test looks fine until you read the next number: holding the
series did +12.80%. A long-only rule on a rising series makes money without
any edge. Running open-test a second time:
The test period was already opened: {"chosen": {"fast": 8, "slow": 21}, "trades": 117, "net_return_pct": 8.57, "max_dd_pct": -4.81, "buy_and_hold_pct": 12.8, "opened_at": "2026-12-04T02:14:57+00:00"} Running it again isn't out-of-sample any more; you need new data or a forward run.The tests, tests/test_tuning.py:
# tests/test_tuning.py: costs, and the test period opening only once.
import json, shutil
from pathlib import Path
import pytest
from src.tuning import backtest, lock, open_test
def candles(prices, start_day=1):
out = []
for i, p in enumerate(prices):
out.append(dict(time=f"2025-01-{start_day + i // 24:02d}T{i % 24:02d}:00Z", open=p, close=p))
return out
def test_flat_prices_lose_only_the_costs():
# up, so EMA fast > slow and a trade opens, then flat, then down so it closes
prices = [100 + i for i in range(30)] + [129] * 5 + [129 - 2 * i for i in range(1, 20)]
res = backtest(candles(prices), 3, 8, 0.01, "2025-01-01", "2025-01-31")
assert res["trades"] == 1
flat = backtest(candles([100.0] * 60), 3, 8, 0.01, "2025-01-01", "2025-01-31")
assert flat["trades"] == 0 and flat["net_return_pct"] == 0
@pytest.fixture
def project(tmp_path):
here = Path(__file__).resolve().parent.parent
shutil.copy(here / "plan.json", tmp_path / "plan.json")
(tmp_path / "data").mkdir()
shutil.copy(here / "data" / "xauusd_h1_utc.csv", tmp_path / "data" / "xauusd_h1_utc.csv")
return tmp_path
def test_test_period_opens_once(project):
lock(project)
open_test(project)
with pytest.raises(SystemExit, match="already opened"):
open_test(project)
with pytest.raises(SystemExit, match="already opened"):
lock(project)
def test_editing_the_plan_after_locking_is_refused(project):
lock(project)
plan = json.loads((project / "plan.json").read_text())
plan["cost_pct_per_side"] = 0.005
(project / "plan.json").write_text(json.dumps(plan))
with pytest.raises(SystemExit, match="changed after locking"):
open_test(project)Run .venv\Scripts\python -m pytest -q tests; you should see 3 passed.
Optional: the brightest cell on a heatmap
Outside this post’s main path. Keep the trial log as in the luck-or-skill
post: one row in reports/trial-log.csv for every combination you ran, bad
ones included. m is the number of data rows (not counting the header) and the
denominator when you read the best cell: the more you try, the easier it is to
find a good cell by luck.
A parameter heatmap colours the result of every combination, which makes the
brightest cell very tempting. With backtesting.py (open-source, AGPL-3.0; run
it only on your own machine),
optimize(n1=[5, 10, 20, 30, 40], n2=[50, 75, 100, 150, 200], maximize='Return [%]', return_heatmap=True)
also returns a Series with the results of all 25 cells, and
backtesting.lib.plot_heatmaps draws them to an HTML file in reports/.
Facts checked on 2026-11-23 with backtesting 0.6.6:
- Offline plotting library: set
BOKEH_RESOURCES=inlinebefore running (in Python:os.environ['BOKEH_RESOURCES'] = 'inline'before plotting), and the file carries its own plotting library (about 1.4 MB) and opens without a network. - The hidden page: from 0.6.2 to 0.6.6, backtesting.py injects JavaScript
into every HTML file from
plot_heatmapsandbt.plot(). Each time the file opens online, it creates a hidden 1×1 frame loading kernc.github.io/backtesting.py/plx.gif.html, a page that runs Google Analytics and Google Tag Manager. The changelog doesn’t mention it. - The fix: after the imports and before plotting, add
import backtesting._plotting as bpandbp._add_popcon = lambda: None. It’s an internal function, so pinbacktesting==0.6.6and check again on every upgrade. - The check:
.venv\Scripts\python -c "import sys; print(open(sys.argv[1], encoding='utf-8').read().count('plx.gif'))" reports\<file name>.htmlmust print 0. Don’t countkernc.github.io: the faint credit text on the chart contains that address but loads nothing. If you can’t fix it, only open the file with the network off.
On historical XAUUSD H1 candles (EMA n1 crossing EMA n2, spread 0.02% of price; train and validation combined as the selection period):
| Selection period (2025) | First 10 months of 2026 | |
|---|---|---|
| All 25 cells | All profitable, +9.5% to +47.6% | Rank correlation with 2025: −0.05 (Spearman) |
| Brightest cell, n1=10, n2=75 | +47.6%, 102 trades | −7.9%, 123 trades, 19th of 25 |
| Its neighbours | Same n1: +23.4% and +22.6%; same n2: +38.2% and +38.1% | |
| Buy and hold gold | +63.7%, above every cell | −10.6% |
One step in n2 halves the profit: a sharp peak, a sensitive parameter. A rank correlation of −0.05 means the ranking on the selection period says almost nothing about the next one. The test was opened for all 25 cells here only to show the trap; in a real process you lock one choice and the log first, then open the test once. A simulation on historical data, not investment advice.
Try it: an optimisation plan you approve before anything runs
Design an optimisation plan for the parameters [LIST] on the data [SOURCE + DATE RANGE]. First propose how to split it by time into development, validation and test, and explain how the test stays sealed. Build a table that logs every run: parameters, costs, number of trades, drawdown, result per period. Suggest a neighbourhood sensitivity check and a suitable walk-forward; don't run any optimisation before I approve the plan. Don't pick a single peak as "optimal", and don't change the strategy after seeing the test while still calling that run out-of-sample.Fill the [brackets] with your own details. Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- Define the train/validation/test split before optimising.
- Tune only the parameters you need, log every run, and choose a stable area rather than a single peak.
- Lock the version after choosing; run forward or out-of-sample once, as planned.
Key takeaways
- EMA fast 8 or 12, slow 21 or 26: exactly four combinations; don’t add new indicators to rescue a bad result.
- Train builds, validation chooses, test opens exactly once for the locked version; a bad test result is still recorded as bad.
- A single parameter peak is fragile: compare it with its neighbours, and make the AI return the table of every run, losses included.
Comments