Contents Lesson 11 of 19

11 min read · professional

Find the leaking bar

By the end of this lesson you will have three leak tests — future mutation, truncation and fill range — each seen red against a leak you planted, a shuffle check on the page that detects no leaks at all, and your agent's attack on the strategy, checked line by line.

Unit 2 told you not to peek. Now find out whether you did, because look-ahead does not announce itself — it announces a great strategy.

The symptom is success

A leaked backtest looks like the best thing you have ever built. Smooth curve, shallow drawdowns, a hit rate in the seventies. That is the tell. If a first attempt at a simple rule produces a result that would make you rich, the prior should be a bug rather than an edge, and the next hour goes into looking for it.

Real edges are small, noisy, and mostly gone after costs. A result that does not look like that is a claim about your code, not about the market.

Four tests, and you check all of them

This is the course's craft discipline at full strength. Bias detection is code review, and code review that runs automatically is a test.

1. The future-mutation test. Compute all signals. Change every bar after index k to nonsense. Recompute. Every signal at or before k must be bit-identical. This is the general form of the test from unit 2 and it catches leaks no eyeball review will.

2. The truncation test. Run the backtest on bars 0..k, then on all bars, and compare the signal and position series through k — not the trade lists, because the truncated run force-closes an open position at k and the full run does not, which is a difference by construction rather than a bug. If running with more data changes what happened in the past, something is reading ahead.

3. The fill-range assertion. From the previous lesson: every fill inside its bar's low-to-high.

Those three are leak detectors. The fourth is a different instrument and it is worth keeping them separate in your head.

4. The shuffle test — a null test, not a leak test. Replace the returns with a random permutation of themselves, keeping the same dates, and run. A rule that depends on chronological structure should lose most of its edge. If it performs just as well on shuffled data, the "edge" comes from exposure, the return distribution or your accounting rather than from anything about the order of the series.

It does not detect look-ahead: a rule that reads tomorrow's return will happily read tomorrow's shuffled return and score just as well. Use it to answer "is there any time structure here at all", and use the first three to answer "am I cheating".

Where the leaks actually come from

In order of how often each one appears in generated code:

  • A window that extends past the current bar. A window ending at bar i is honest for a signal you act on at i + 1; anything reaching i + 1 or beyond is reading the future. One index.
  • Normalising over the whole series — dividing by the full-sample mean, or scaling to the maximum. Every point then knows the future.
  • A parameter chosen by looking at the whole sample, which is the human version of the same leak. This is unit 4's subject.
  • fillna or interpolation running backwards, quietly filling today's hole with tomorrow's value.
  • Sorting or reindexing that reverses the series without anyone noticing.

Ask your assistant to attack it

Hand it your strategy function and the four tests and ask: "find a way this could be using information from the future." Then read the answers sceptically — some will be wrong, and one or two will be things you would not have found.

This is the most valuable single prompt in the course. Assistants are good at this specific task because it is pattern-matching over a well-known bug family.

Try it now

Have your agent write all four tests, read each one until you can say what it asserts, and run them. Then plant each of the five leaks above on purpose, one at a time, and confirm which test catches it. You will find at least one leak that none of them catch — ask your agent for a fifth test for that one and read it like any other test, and you have learned more about testing than any tutorial teaches.

The prompt

Mock mode on, plan mode on. The first prompt builds the tests:

Plan first. Write tests/honesty.test.ts on synthetic bars, with no
request. Future mutation: change every bar after k to nonsense, and
every signal and position at or before k is identical. Truncation:
run on bars 0 to k and on all bars, and the signal and position series
through k match; not the trades, since the short run closes its open
position at k by construction. The fill-range test in
tests/fills.test.ts is the third. Then add shuffleCheck(bars, params,
seed) in src/lib/backtest/shuffle.ts: the strategy on twenty seeded
permutations of the daily returns, dates kept, shown on the page as a
median beside the real result, with no pass mark. Run npm test, then
show me the diff.

The second is the attack, and it must change nothing:

Read src/lib/backtest/ and tests/. Find every way this code could be
using information from the future. For each, name the file and line
and say which of my tests would catch it. Do not change any file.

A good answer to the first adds tests/honesty.test.ts and src/lib/backtest/shuffle.ts and changes the page. A good answer to the second is a list you have to check, and an unchanged git status.

Check it yourself

  1. The three leak tests are green on your code.
  2. The page shows the real result beside the median of twenty shuffles. A rule that depends on the order of returns loses most of its edge on shuffled ones; if yours does not, the edge comes from exposure or accounting.
  3. After the attack, git status is unchanged. Open the line behind each claim and mark it right or wrong: usually at least one is wrong, and one is something you would not have found. If every claim holds up, that is a result too; ask the agent which one it is least sure of and check that one.
  4. Every confirmed leak that no test catches becomes a test of its own.

Break it on purpose

The five leaks above, one at a time, in mock mode: a window reaching bar i + 1, a divide by the whole series' maximum, a backward fill of a missing bar, a reversed series, and a parameter picked by looking at the whole sample. For each one, paste this to your agent, naming the leak:

On a scratch branch, plant this leak in src/lib/backtest: <the leak>.
Run npm test, tell me which test went red, and then discard the branch.

Write down what went red after each. The reversed series turns everything red at once, because the oldest-first assertion throws before any comparison runs. The last one turns nothing red at all, because it is a habit rather than a line of code, and the walk-forward lesson is its test.

Compare with ours

Our two leak tests
// tests/honesty.test.ts
const k = 150;
const base = runStrategy(bars, DEFAULTS);
const through = (xs: unknown[]) => xs.slice(0, k + 1);

it("the past does not move when the future does", () => {
  const mutated = runStrategy(bars.map((b, i) => (i > k ? nonsense(b) : b)), DEFAULTS);
  expect(through(mutated.signals)).toEqual(through(base.signals));
  expect(through(mutated.positions)).toEqual(through(base.positions));
});

it("more data does not change what already happened", () => {
  const short = runStrategy(bars.slice(0, k + 1), DEFAULTS);
  expect(short.signals).toEqual(through(base.signals));
  expect(short.positions).toEqual(through(base.positions));
});

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 "Three leak tests and a shuffle check, each leak test seen red on a planted leak"

Add any fifth test you wrote in a commit of its own. Then answer this lesson's questions.