State a rule that cannot see the future
By the end of this lesson you will have a leak test you wrote before the rule existed, signals() in src/lib/backtest/signal.ts passing it, and the same test going red the moment you centred the window on purpose.
Everything in a backtest hangs on one discipline: at every bar, the rule may only use information that existed at that bar. Break it anywhere and every number downstream is fiction, and the fiction is always flattering.
Write the rule in English first
Before code, one sentence with no ambiguity left in it:
If the 20-day moving average of the adjusted close is above the 50-day, hold one unit of the instrument; otherwise hold nothing.
That sentence forces three answers a vague version hides. Which prices — adjusted, as lesson 3 settled. Measured when — at the close of each bar. Acted on when — the next lesson's subject, and the usual place the leak lives.
If your assistant can generate ten plausible implementations of your sentence, the sentence is not finished.
Where the leak gets in
A moving average at bar i must be computed from bars i-19 through i. Write it as a window ending at i and it is honest. Write it as a window centred on i, or fetch it from a library that pads at the end, and half the window is tomorrow.
The classic slip, and it is one character:
const window = bars.slice(i - 19, i + 20); // centred: half of this is the future
const window = bars.slice(i - 19, i + 1); // ending at i: honest
Both run. Both produce a curve. One of them is a time machine, and it will look like a brilliant strategy.
Two habits that make the leak visible
Compute signals in one pass, forwards. A single loop from oldest to newest, where each iteration may only read what earlier iterations already saw. Any code that indexes ahead of the cursor stands out immediately, which is the point — the shape of the loop is the check.
Never sort or reverse the series in place. Build Your First Tool taught that Array.prototype.sort mutates. Here that bug does not just reorder a table, it silently reverses time. If your bars arrive newest-first from anywhere, normalise once at the boundary and assert the direction.
if (bars[0].date > bars[bars.length - 1].date) throw new Error("bars must be oldest-first");
One line, at the boundary, and it converts a whole class of catastrophic silent bug into a loud crash.
The test you write now, not later
This is the course's craft discipline arriving: bias detection is code review, and the best code review is a test.
Write one now, on a fixture you control. The fixture has to be long enough for the rule: a 50-day average needs fifty bars before it exists at all, so take 120 synthetic bars, compute the signal at bar 80, then change the prices of bars 81 through 120 and recompute. If the signal at bar 80 moved, your rule reads the future.
Check the window before you trust the result, because this is where the test lies to you. bars.slice(i - 19, i + 1) looks right and is right at bar 80. At bar 10 it is bars.slice(-9, 11), and JavaScript counts a negative start from the END of the array — on a twenty-bar fixture that resolves to slice(11, 11), an empty window. The signal is then garbage, garbage does not move when you change the future, and the test passes. Print the window length once and assert it: if (window.length !== 20) throw new Error("short window at bar " + i).
That test is a few lines, it never needs updating, and it catches the single most expensive bug in this domain.
Run it on every strategy you write for the rest of the course.
Try it now
Write the leak test before the strategy. Then ask your assistant for the moving-average signal and run the test against what it hands you. If it passes first time, deliberately break it — switch the slice to a centred window — and confirm the test actually fails. A test you have never seen fail is not evidence.
The prompt
Create tests/leak.test.ts yourself, from the template below: 120 synthetic bars, the signal at bar 80, bars 81 to 120 changed, and an assertion that the signal at bar 80 is not null before you compare it. The test is the part that has to be yours, so type it in or paste it, then read each line until you can say what it asserts. The bar generator is plain arithmetic, and the template passes npm run typecheck:
// tests/leak.test.ts
import { expect, test } from "vitest";
import type { Bar } from "@/lib/backtest/candles";
import { sma, signals } from "@/lib/backtest/signal";
function makeBars(count: number): Bar[] {
const bars: Bar[] = [];
for (let i = 0; i < count; i++) {
const price = 100 + i * 0.3 + Math.sin(i / 5) * 8;
bars.push({
date: new Date(Date.UTC(2025, 0, 1 + i)).toISOString().slice(0, 10),
open: price, high: price + 1, low: price - 1, close: price,
adjusted_close: price, volume: 1_000_000,
});
}
return bars;
}
test("the signal at bar 80 does not move when bars 81 to 120 change", () => {
const bars = makeBars(120);
const at80 = (b: Bar[]) => [sma(b, 80, 20), sma(b, 80, 50), signals(b, 20, 50)[80]];
const before = at80(bars);
expect(before[2]).not.toBeNull(); // a null cannot move, so it proves nothing
const changed = bars.map((b, i) => (i > 80 ? { ...b, adjusted_close: 1 } : b));
expect(at80(changed)).toEqual(before);
});
Run npm test and watch it fail — there is no signal.ts yet. Stage it with git add tests/leak.test.ts, so git holds the version you wrote. Mock mode on, plan mode on:
Plan first. Make tests/leak.test.ts pass without editing it. Add
src/lib/backtest/signal.ts with sma(bars, i, n), over a window that
ends at bar i and throws "short window at bar i" unless it holds
exactly n bars, and signals(bars, fast, slow): one forward pass over
adjusted closes, null until the slow average exists, then whether the
fast average is above the slow. Assert oldest-first at the boundary
with assertOldestFirst from candles.ts (add it there and export it if it
is not exported yet). No request. Run npm test and
show me the output, then the diff.
A good answer adds one file, src/lib/backtest/signal.ts, leaves your test alone, and ends green.
Check it yourself
- Your own first
npm testfailed becausesrc/lib/backtest/signal.tsdid not exist: proof the test runs. - Green now, and
git diff -- tests/leak.test.tsprints nothing. The agent did not touch your test. signals()gives null for the first 49 bars of a 20/50 rule and a boolean from bar 49 on. The warm-up is visible, not filled in with false.- The window in
smaisslice(i - n + 1, i + 1)and its length is asserted, so a negative start throws instead of quietly reading from the end of the array.
Break it on purpose
Change the window to the lesson's centred one, slice(i - n + 1, i + n), and run npm test: red. Read which assertion fired. On a centred window the length check throws before the comparison is reached — two nets on one bug, which is fine. Now delete the length check as well and run it again: the leak test alone must still go red. If it stays green, it compares only the boolean, and a true can stay true by luck while the window reads the future; compare the two averages at bar 80 too. Restore both lines: green.
Compare with ours
Our signal and our leak test
// src/lib/backtest/signal.ts
export function sma(bars: Bar[], i: number, n: number): number {
const window = bars.slice(i - n + 1, i + 1); // ends at bar i: honest
if (window.length !== n) throw new Error("short window at bar " + i);
return window.reduce((sum, b) => sum + b.adjusted_close, 0) / n;
}
export function signals(bars: Bar[], fast: number, slow: number): (boolean | null)[] {
assertOldestFirst(bars);
return bars.map((_, i) => (i < slow - 1 ? null : sma(bars, i, fast) > sma(bars, i, slow)));
}
// tests/leak.test.ts, the assertion
const at80 = (b: Bar[]) => [sma(b, 80, 20), sma(b, 80, 50), signals(b, 20, 50)[80]];
const before = at80(bars);
expect(before[2]).not.toBeNull(); // a null cannot move, so it proves nothing
const changed = bars.map((b, i) => (i > 80 ? { ...b, adjusted_close: 1 } : b));
expect(at80(changed)).toEqual(before);
The full state at the end of this unit is on the starter's branch ref/backtest-strategies/u2.
Checkpoint
npm test && npm run typecheck
git status # only the files this step touched, no .env*
git add -A
git commit -m "Leak test first: the signal at bar 80 must not move when later bars do"
Then answer this lesson's questions.