Build it twice, and make the two agree
By the end of this lesson you will have a second backtest engine written without reading the first, a test that holds the two together on every bar of four runs, a split put into the history that moves neither curve, and three planted bugs that only the second engine sees.
The leak tests ask what the code was allowed to read. They do not ask whether it added up. A backtester can look only at the past and still credit you with a night you were not invested, charge an exit fee twice, or take a holding day's return from the raw close. Each of those moves the result by a fraction of a per cent, looks entirely plausible, and passes every test this unit has written so far.
A second implementation is a test of the number
The fill-range test and the leak tests check a property of the result. None of them checks the result itself, because nobody can work out a year of compounded equity by hand to compare against.
What you can do is compute it again by a different route and demand the same answer. Payment systems, compilers and flight software check arithmetic nobody can eyeball this way, and in a backtester it costs about forty lines. When two independent versions agree on every bar, a mistake would have to be made the same way twice. When they disagree, you have found a bug before it found your money, and the bar where they part tells you where to look.
Independence is the whole value
A second version written by the session that just wrote the first, with the first open beside it, repeats its mistakes. So three rules:
- A fresh session that has not read the engine. It gets the rule's paragraph from this lesson and is told not to open
strategy.ts. - A different shape. Your engine is a state machine: flat, buy, hold, sell. If the second one is also a state machine, you have the same design typed twice.
- Shared inputs only where they are already tested. Both may use
signals(), which the leak tests pin. Nothing else from the engine.
The same curve, by a different route
Cut every bar into two pieces: the night, from the previous close to this open, and the day, from this open to this close. Price both on the adjusted column: the open times that bar's adjusted_close / close. Then ask one question of each piece: was a unit held through it?
- With fills at the next open, the night belongs to the position held at the previous close, and the day to the position held at this close. A night held earns its move; a piece not held earns nothing.
- With fills at the signal's close, the change happened the evening before, so the whole day belongs to the position held at this close.
- Every change of position pays the fee once. A unit still held at the last bar pays it once more, as if sold at that close.
No buy, no sell, no trade list: the curve falls out of which pieces were held.
How close counts as the same
Not bit for bit. The same products in a different order differ in the last bits of a float, so the test compares with a tolerance, and the tolerance is set from two measurements rather than chosen until the test goes green. On the mock year our two engines agree to about two parts in a thousand trillion. The quietest of the bugs below parts them by 0.27%. A relative tolerance of a billionth sits between the two with room on both sides.
When they disagree
Find the first bar where they part, and read what happened on it: an entry, an exit, an ex-dividend day. Then decide which one is wrong — sometimes it is the new one — fix that one, and keep the test that found it.
The one move that is never allowed is loosening the tolerance until they agree. That turns the check into decoration.
A split changes nothing
A four-for-one split rewrites every raw price before it to four times its size and leaves the adjusted column as it was. A backtest whose returns come only from the adjusted column must give exactly the same curves on the history with the split as without it. Put one into the fixture on a day the rule is holding, and any return that touches a raw price reads that day as −75%.
The trade list does change: fill prices are printed prices, and before the split they were four times higher.
Try it now
Write the second engine in a session that has not seen the first, then hold the two together, then put a split in.
The prompt
Mock mode on, plan mode on. Start a new session for the first prompt:
Plan first. Do not open src/lib/backtest/strategy.ts or tests/ for
this. Add twin(bars, params) in src/lib/backtest/twin.ts, returning
dates, gross and net from the first bar where the slow average exists.
The unit held at a bar's close is 1 when the signal at the close
before was true, and 0 on that first bar. Each bar is a night,
previous close to this open, and a day, this open to this close, both
on adjusted prices: the open times that bar's adjusted_close / close.
With fill "next-open" the night earns its move if a unit was held at
the previous close, and the day if one is held at this close. With
"signal-close" the whole bar earns its move if a unit is held at this
close. Each change of position pays (costBps + slippageBps) / 10000
once, and a unit still held at the last bar pays it once more. Use
signals() from signal.ts and nothing else from src/lib/backtest. No
test yet. Show me the diff.
The second, back in your usual session:
Plan first. Add tests/twin.test.ts on the SPY fixture: backtest()
and twin() give the same dates and, on every bar, gross and net
within a relative 1e-9, on four runs: the defaults, costs and
slippage off, fill "signal-close", and fast 5 with slow 10. Assert
that each run trades at least twice and that one still holds at the
last bar. Then a split: on a copy of the fixture with every raw open,
high, low and close before a bar the default run holds through
multiplied by 4, adjusted_close untouched, both engines give the
original curves. Change nothing in strategy.ts. Run npm test, then
show me the diff.
A good answer to the first adds src/lib/backtest/twin.ts and nothing else. A good answer to the second adds tests/twin.test.ts, is green, and leaves strategy.ts alone. If either engine was edited to make the test pass, reject the diff: a disagreement is a finding to read, not a red test to silence.
Check it yourself
twin.tsimportssignalsand no other backtest module, and has no buy, hold or sell branches. If it walks a state machine, ask for the night-and-day version.- The tolerance in the test is
1e-9, relative. Ask the agent to print the largest difference it saw: on the fixture it is around1e-15. - Every run trades, and one still holds at the end. A comparison of two flat lines proves nothing, and the closing fee at the last bar is a branch of its own.
- The split test leaves both curves where they were and multiplies the fill prices before the split by four.
Break it on purpose
Three bugs in strategy.ts, one at a time: an entry at the open that earns the night before it (close / prev where the code has close / adjOpen(i)), a holding day priced on the raw close (bars[i].close / bars[i - 1].close), and an exit that pays the fee twice. For each one, paste this to your agent, naming the bug:
On a scratch branch, plant this bug in src/lib/backtest/strategy.ts:
<the bug>. Run npm test, tell me which tests went red and what the
default run's net return became, and then discard the branch.
On ours, the first moves the default run from +4.67% to +4.39% on the mock year, and only twin.test.ts goes red: the leak tests stay green because nothing read the future, and the fill-range test stays green because every fill is inside its bar. The second turns the split test red too. The third is red on every run that charges costs and green on the one that does not, which is why that run is never the only one.
Compare with ours
Our second engine
// src/lib/backtest/twin.ts, the loop
const held = (i: number) => (i > start && signal[i - 1] === true ? 1 : 0);
const adjustedOpen = (b: Bar) => b.open * (b.adjusted_close / b.close);
for (let i = start + 1; i < bars.length; i++) {
const before = held(i - 1);
const after = held(i);
const night = adjustedOpen(bars[i]) / bars[i - 1].adjusted_close;
const day = bars[i].adjusted_close / adjustedOpen(bars[i]);
const step = params.fill === "next-open"
? (before ? night : 1) * (after ? day : 1)
: after ? night * day : 1;
if (before !== after) changes++;
gross.push(gross[gross.length - 1] * step);
net.push(gross[gross.length - 1] * fee ** changes);
}
if (held(bars.length - 1)) net[net.length - 1] *= fee;
The full state at the end of this unit is on the starter's branch ref/backtest-strategies/u3.
Checkpoint
npm test && npm run typecheck
git status # only the files this step touched, no .env*
git add -A
git commit -m "A second engine, held to the first on every bar, and a split that changes nothing"
Then answer this lesson's questions.