Turn prices into returns, before any strategy exists
By the end of this lesson you will have dailyReturns and compound in src/lib/backtest/returns.ts, a test that pins them on the five real AAPL bars across the 2020 split — +3.4% on adjusted, −74.2% on raw — and the ten largest moves of your own history on both columns, side by side.
No rules yet. This lesson is arithmetic, and getting it wrong invalidates everything built on top — which is why it comes before anything interesting.
A return is a ratio, not a difference
const r = bars[i].adjusted_close / bars[i - 1].adjusted_close - 1;
A price series is not comparable across time or across instruments; a return series is. Two rules follow immediately, and both are about which column you divide.
The column that decides whether your numbers mean anything
Here are five consecutive AAPL bars captured live, spanning 2020-08-31:
[{"date":"2020-08-27","close":500.04,"adjusted_close":121.1519},
{"date":"2020-08-28","close":499.23,"adjusted_close":120.9557},
{"date":"2020-08-31","close":129.04,"adjusted_close":125.0575},
{"date":"2020-09-01","close":134.18,"adjusted_close":130.0389},
{"date":"2020-09-02","close":131.40,"adjusted_close":127.3447}]
Compute the 2020-08-31 return both ways:
- On
close: 129.04 / 499.23 − 1 = −74.2% - On
adjusted_close: 125.0575 / 120.9557 − 1 = +3.4%
Nothing bad happened to Apple that day. It was a four-for-one stock split, confirmed by the splits endpoint:
{"date":"2020-08-31","split":"4.000000/1.000000"}
Note the shape: the ratio arrives as a string, not a number. Parsing it is your problem.
A backtest on the raw close column sees a −74% day. If your rule buys crashes, it just bought a phantom. If it stops out on losses, it just stopped out of nothing. Use adjusted_close for returns. Every time.
Why raw close still exists
Because it is what actually printed, and some questions need it: what you would have paid per share, whether a limit at 130 filled, what the position was worth in dollars on the day.
The rule is nearly clean: returns and signals on adjusted, execution arithmetic on raw — with one caveat worth saying out loud in a unit about information that existed at the bar. Today's adjusted series already contains every dividend paid since, so a level-based rule near an ex-date on a high-yield name is slightly contaminated by a payment that had not happened yet, and none of the leak tests below can see it, because the data arrives that way. Label the two columns in your code so nobody — including you next month — has to guess which is which.
Compounding, and the mistake beneath it
To turn a return series into an equity curve you multiply, never add:
let equity = 1;
for (const r of returns) equity *= 1 + r;
Adding returns overstates gains and understates losses, and the error grows with the number of periods. The intuition: −50% then +50% is not flat, it is −25%. Any code path that sums percentages is wrong, and it will look approximately right on short samples, which is what makes it dangerous.
The finance behind it
Two lessons stand behind the adjusted column — what it is for, and why it keeps changing: Why do old prices look "wrong" on charts? and Why does your price history rewrite itself every quarter?
Try it now
Compute the daily return series for one symbol twice, once on each close column, and print the ten largest moves from each. The raw-close list will be full of splits pretending to be crashes. That list is your evidence, and it takes about four lines.
The prompt
Mock mode on, plan mode on. Paste this, and under it the five bars and the split row from this lesson:
Plan first. Add src/lib/backtest/returns.ts: dailyReturns(bars, column),
where column is "adjusted_close" or "close" and the first bar has no
return; compound(returns), an equity curve from 1 that multiplies;
largestMoves(returns, n); and parseSplit for the splits endpoint's
string ratio. Tests first in tests/returns.test.ts, on the five bars
and the split row below, as literals: for 2020-08-31, +3.4% on adjusted
and -74.2% on close, as I read them off the lesson, and one case where
adding returns instead of multiplying them would give the wrong curve.
Compare with a tolerance. Every expected value is a literal I give you,
never one computed with the code's own arithmetic. No request and no
other file. Run npm test,
then show me the diff.
A good answer adds two files, src/lib/backtest/returns.ts and tests/returns.test.ts, shows the tests red before the code and green after, and spends nothing.
Check it yourself
- The test asserts +3.4% and −74.2% as numbers read off this lesson, not values computed the way
dailyReturnscomputes them. A test that repeats the code's arithmetic cannot disagree with it. - On the five bars,
dailyReturnsgives four returns, the first dated 2020-08-28: the first bar has none. compoundturns −50% then +50% into a curve that ends below where it started, and the test says by how much.- Now your own history. Mock off for one call (the shared
demokey serves AAPL but not SPY, both with the .US suffix, so withdemouse AAPL): have the agent fetch one symbol's daily history through your proxy and printlargestMoveson both columns side by side, without adding anything to the repository. On a long history the raw list is full of splits pretending to be crashes. On a year it may hold none, and the two lists then nearly match, differing on ex-dividend days by a fraction of a per cent — your test is the split evidence, and it reached back to 2020 without a call.
Break it on purpose
Change compound to add returns instead of multiplying them and run npm test. Your compounding case goes red: a sum calls −50% then +50% flat. Put it back: green.
Compare with ours
Our returns
// src/lib/backtest/returns.ts
export function dailyReturns(bars: Bar[], column: CloseColumn) {
const out: { date: string; r: number }[] = [];
for (let i = 1; i < bars.length; i++) { // bar 0 has nothing before it
out.push({ date: bars[i].date, r: bars[i][column] / bars[i - 1][column] - 1 });
}
return out;
}
export function compound(returns: number[]): number[] {
const curve = [1];
for (const r of returns) curve.push(curve[curve.length - 1] * (1 + r)); // never add
return curve;
}
parseSplit reads the string ratio and gives 4 for Apple's 2020 split, or null for anything not shaped like a ratio. The full state at the end of this unit is on the starter's branch ref/backtest-strategies/u1.
Checkpoint
npm test && npm run typecheck
git status # only the files this step touched, no .env*
git add -A
git commit -m "Returns as ratios on adjusted close, compounded by multiplying"
Then answer this lesson's questions.