prices.csvOne row per trading day, one column per position:
The last row is your ledger's prices. VOO holds the 500 largest US companies: it is the market.
The prices are simulated from a fixed seed (make_prices.py): every run gives the same file. That has one big advantage today: we know the true answer, so we can check ours.
Two minutes, on your own. This is today's whole script.
Six lines. By the end of the session you can explain every one, and check every one.
slope b: 1.296 answers the guess: when the market moves 1 %, Apple moves about 1.3 %.Most of today's slides have mathematics on the left instead of code. Next slide: how to read them.
The left side holds the mathematics. It changes from slide to slide.
A gold box with a number points at one part:
The same layout as the code slides: equations on the left, explanations on the right.
Part 1
Prices are not comparable. Changes are.
Each price divided by its first-day price, times 100. So all four lines start at 100.
"Follows, but not exactly" is today's question in a picture. To measure it, we look at daily changes, not price levels.
Apple's price on day
The return on day
1 Today's price divided by yesterday's. If nothing changed, the ratio is 1, and the return is 0.
That is why we compare returns, not prices.
Apple's price on day
The return on day
In per cent, on 2026-10-30:
On 2026-10-30, Apple closed at 190.50; the day before, at 186.53.
Judge it: a 2 % day for one stock is normal. A 90 % day is not.
read_csv(..., index_col="Date"): a DataFrame, with dates as row names (session 6).pct_change() computes dropna() removes that row.* 100: per cent.250 prices give 249 returns. From now on, every number is a daily return in %.
Lines 6–7 of the script, in mathematics.
The same letters,
Part 2
Two numbers that summarise 249 days.
1 The sum of
for loop (session 3)The first five returns of VOO. You wrote this loop for the ledger total:
returns = [0.27, -1.76, 1.37, 0.65, -0.24]
total = 0
for r in returns:
total = total + r
print(round(total, 2), round(total / len(returns), 3))
0.29 0.058
Every x.mean().
1 So we square them. A square is never negative: nothing cancels, and big deviations count a lot.
2 Then average, dividing by .var()). With 249 days, the difference from
The deviations are measured from
Not for the exam. Just know that pandas' .var() and .std() divide by
The whole year:
The variance is in per cent squared. The square root returns to the unit of the data, per cent.
Finance calls the standard deviation of returns volatility.
Before any model, check by hand that the numbers make sense.
A mean of 10 % per day would tell you at once: wrong file, or wrong units.
One column is now summarised. But the question is about two columns: does Apple move with the market?
Part 3
One dot per day, and one number for the shape of the cloud.
Each dot is one day: across, VOO's return; up, Apple's return. 249 dots.
"Tends to" is not a number yet. Next: one number for it.
Draw a line at each mean. Every day lands in one of four boxes.
Most days are blue: the two columns agree much more often than they disagree.
1 The product of the two deviations: positive in blue boxes, negative in red ones. Add them all up, divide by
Apple and VOO: 1.339. Positive, but its size depends on the units, so it cannot be compared across pairs.
1 Divide by both standard deviations. The units cancel, and the result is always between −1 and 1.
| the cloud | |
|---|---|
| 1 | all dots on a rising line |
| 0.759 | a clear rising band: Apple and VOO |
| 0 | a round blob: no direction |
| −1 | all dots on a falling line |
A correlation says two columns move together. It does not say which one pushes the other, or whether a third thing pushes both.
Today's line describes how Apple moves with the market. It does not prove that the market makes Apple move.
Every formula so far is one method call on a column.
| mathematics | pandas |
|---|---|
x.mean() |
|
x.var(), x.std() |
|
x.cov(y) |
|
x.corr(y) |
Bottom left: the real output. The numbers are the ones you just computed.
A correlation of 0.759 says how tightly they move together. It does not say by how much. For that, we need a line.
Part 4
From "they move together" to "by how much".
We have 249 examples: pairs
Every model in Part 2, up to neural networks, follows these four steps.
1
2 The slope
In finance,
Machine-learning words:
Three choices of
Your eye picks the third. But "through the middle" is not a rule a computer can follow. We need step 2: a number that says how wrong a line is.
On 2026-10-30:
1 What happened minus what the line said.
On 2026-10-30, VOO rose 0.382 %. With
Gold: the vertical gap between each dot and the line, shown for every 10th day. Red: 2026-10-30.
A good line makes these gaps small, all together.
So the question becomes: how do we turn 249 gaps into one number?
The same reason as for the variance. Squares win, and the method is called least squares.
Put the line into the residual, square, average: the mean squared error (MSE).
1
The best line is the one with the smallest loss. That is step 3.
Fix
1 The coefficient of
There the curve is flat, its slope zero: the condition we use next.
1 Read "partial L, partial a": how fast
At the bottom of the bowl, a small nudge in any direction does not change
Two equations, two unknowns. The next two slides solve them.
The residuals must add up to zero. Divide by
1 Once we know
Read it the other way round:
Put in
After a few lines of algebra, two old friends appear:
1 The slope is the covariance divided by the variance of
That is line 9 of the script, x.cov(y) / x.var().
Both inputs come from Part 3.
Two lines of arithmetic: no search, no trial and error. For a line, least squares has an exact formula. Most models in Part 2 will not; Part 7 deals with that.
Multiply and divide by
1 the correlation: how tightly the cloud follows a line;
So a high beta has two possible sources: a tight link to the market, or simply a lot of movement. For Apple, both.
No other line has a smaller mean squared error than this one: 1.269.
Now use it.
Put a market move in, get Apple's expected move out.
Expected means "on average, on days like this". On a single day, Apple can be far from the line: remember the residuals.
The prices were simulated. Line 13 of make_prices.py:
returns["AAPL"] = 0.0003 + 1.25 * market + rng.normal(0, 0.011, len(days))
The true slope is 1.25. Least squares found 1.296.
rng.normal) shakes the dots, and 249 days cannot remove all of it.make_prices.py. Then you judge with what you know: a beta of 1.3 for a large tech stock is plausible. A beta of 13, or of −0.75, is not.The line is the best possible. Is it good? Line 14 answers that.
Part 5
The best line can still be a poor description.
Suppose you knew nothing about the market. Your best guess for Apple, every day, is its mean 1.
746.2: this is the amount there is to explain.
The line uses the market, so it misses less: 315.9 instead of 746.2.
The difference, 430.3, is the part of Apple's movement that the market explains.
1
The market explains 0.577, about 58 %, of Apple's daily ups and downs. The other 42 % is Apple's own news.
There is no fixed threshold. It depends on the question.
Finance names the two parts: market risk, the explained part, which no amount of diversification removes; and specific risk, the residuals, which shrinks when you hold many stocks.
Always look at the biggest residual. If it is absurd, the data probably are too.
Four small data sets (Francis Anscombe, 1973) with the same summary:
means
correlation 0.816; least-squares line
I: a line is a fair description. II: the truth is a curve.
III: one outlier tilts the line. IV: one point creates the whole slope.
Anscombe's point, taken further in 2017: 13 data sets of 142 points, all with the same means, standard deviations and correlation, to two decimals.
Next slide: what they look like.
A dinosaur, a star, a cross, a circle: one table of summary statistics.
Summary statistics compress the data. Everything that does not fit in a mean, a standard deviation and a correlation is gone: curves, clusters, outliers, a dinosaur.
Plot first, summarise second. For our Apple–VOO cloud we did: Part 3 started with the picture.
Part 6
Least squares is not just convenient. It follows from an assumption about the noise.
The line was a rule for
1
2 We assume it is normally distributed, centred at 0, with standard deviation
This is exactly line 13 of make_prices.py:
The bell curve. 1 The residual enters squared, in an exponent: small residuals are likely, large ones become unlikely very fast.
The histogram of the 249 residuals, and a normal curve with the same standard deviation.
For a candidate line
1
Maximum likelihood: choose the parameters that make the observed data most probable.
The log turns the product into a sum, and the exponent comes down. The maximum stays in the same place.
For fixed
Maximising the likelihood = minimising the sum of squares. If the noise is normal, least squares is the most probable line, not just a convenient one.
Maximise
make_prices.py.Change the assumption, change the loss: if the noise had fatter tails (a Laplace distribution), maximum likelihood would minimise the sum of absolute residuals, the second option of Part 4.
Our biggest residual is about 3.0 standard deviations. Under the normal model, a miss that large happens about once in 370 days: plausible in a year of 249.
The model also tells you what is not plausible. Keep this ruler: we will need it at the end of the session.
Part 7
The same line, found without a formula.
For a line, least squares has an exact formula. Most models do not.
The method that trains all of them is gradient descent: start anywhere, and take small steps downhill on the loss, again and again.
We try it on the line, where we know the answer:
The two rates from Part 4, now used as directions.
1 The error of each day: fitted minus actual. Same squares as before, written the other way round.
The pair of rates is called the gradient. It points uphill; we go the other way.
= in Python: a = a - rate * grad_a.
1 Minus: against the gradient, so downhill.
Repeat: compute the gradient, step; compute it again, step again. Each step lowers the loss a little.
Start from
The update rule, inside a for loop.
After about 40 steps,
The rings are contour lines of the loss, like on a hiking map: each ring joins points of the same height.
The gold path starts at
One change: learning rate 1.2 instead of 0.1.
A loss that grows is the signature of a learning rate that is too big.
| learning rate | what happens |
|---|---|
| too small | correct, but thousands of steps |
| about right | a few dozen steps |
| too big | the loss explodes |
A number that you choose, not the data, is a hyperparameter. Every model in Part 2 has some.
How do you choose? Try a few values, print the loss, and look: it must go down.
One more problem: every step used all 249 days. A neural network learns from millions of examples. Computing the full gradient at every step is too slow.
1 Sum over a batch
This is stochastic (random) gradient descent, with mini-batches. It is how every neural network is trained.
Line 13 draws 20 day numbers; x[days] picks those days' returns. Lines 15–16: the same update as before.
Good enough, at a fraction of the cost. For noisy problems, "close and cheap" beats "exact and slow".
In practice, the learning rate is often lowered over time, so the red walk settles down.
You now know how to find a line two ways. Next: more than one
Part 8
A plane instead of a line, and categories as columns.
Line 8, first round: regress Apple on Microsoft instead of the market.
To find out, put both columns in the same model.
1
With two features, the fitted model is a plane through a three-dimensional cloud.
Stack the features as columns of a table
1 Setting all partial derivatives to zero gives this normal equation. With one
You will not compute it by hand: LinearRegression().fit(X, y) does, for any number of columns.
| features | |||
|---|---|---|---|
| MSFT | 0.701 | 0.375 | |
| VOO | 1.296 | 0.577 | |
| VOO, MSFT | 1.164 | 0.119 | 0.581 |
With the market in the model, Microsoft's slope falls from 0.701 to 0.119, and
In make_prices.py, the true values are 1.25 and 0.
A classic question in finance: do stocks behave differently on some weekdays? The weekday is a category, not a number.
Coding the days as 1 to 5 would force the model to treat Tuesday as "twice Monday" and the step from Monday to Tuesday as equal to the step from Thursday to Friday. The numbers would be invented.
Instead: one column per category.
Each dummy column is 1 on its weekday and 0 otherwise. On every row, exactly one column is "hot".
1
Friday has no column: it is the baseline. With all five dummies and an intercept, the five columns would add up to the column of ones, and the least-squares problem would have no unique solution (the dummy trap).
pd.get_dummies makes one column per weekday; drop_first=True drops the first in alphabetical order, Friday.
We simulated no weekday effect. These four numbers fit noise, and
Part 9
A smaller loss on the data you have is not a better model.
Split the year in two.
The test error estimates how the model does on new data, which is the only kind that matters for prediction. This is step 4 of the recipe, done properly.
1 Add powers of
It is still least squares, with the columns np.polyfit(x, y, degree).
More parameters can only lower the loss on the training days. The question is what happens on the test days.
Dark: the line. Gold: degree 15. Both fitted on the blue dots only.
A model that learns the noise of the training days, patterns that happened by chance, is overfitting. A model too simple to follow the signal is underfitting.
make_prices.py, The training error dips below the noise line. That is the clearest sign of overfitting: the model "explains" variation that is pure chance.
Part 6's model: signal
1 Bias: the average fitted model misses the true
2 Variance:
3 Noise: make_prices.py:
Flexibility lowers bias and raises variance: the bias–variance trade-off.
Each gold line is fitted on a different random half of the year.
A model you would trust is one that gives similar answers on similar data.
"Entities should not be multiplied beyond necessity." William of Ockham, 14th century
For models: among models that explain the data equally well, prefer the simplest.
Add a column only when the test error says it helps.
Part 10
The question from the start.
The same script with y = returns["MSFT"], then y = returns["NESN"].
| position | ||
|---|---|---|
| AAPL | 1.30 | 0.58 |
| MSFT | 1.11 | 0.56 |
| NESN | 0.47 | 0.26 |
1 The portfolio's beta is the weighted average of the betas: another
MSFT is not in the sum: its row has no shares (session 6), so its value is unknown.
The portfolio is expected to fall about -2.21 %: about -74 of its 3338.20.
Compare with the guess you wrote down at the start.
A classmate runs the same script on their copy of the file, prices_typo.csv. It differs from yours in one number out of 1000.
Which output do you believe? Before the next slide: how would you find out?
Plot first. The cloud from Part 3 is squeezed into a flat line near zero, and two dots are far away: one day at -90.2 %, the next at +900.4 %.
In the file, Apple on 2026-03-16 is 15.92. The true price is 159.23: the decimal point moved one place.
Failure kind 3: it runs and lies. One look at the picture finds it. The six printed numbers hid it.
One bad day has a squared deviation of about 810679. The whole rest of the year adds up to about 746.2 (SST, the total sum of squares).
So least squares bends the line to please one day, and ignores the other 247.
What made squares attractive, punishing big misses, is also their weakness: one wrong number can take over the answer.
The ruler from Part 6: a residual of 900.4 % is about 798 standard deviations. Under the noise model that is impossible. The model is not wrong here; the data are.
None of these checks needs mathematics. They need you to look. An AI (artificial intelligence) assistant will happily fit a line to a file with a typo, and report beta −0.75 with full confidence. Judging is your job.
The script from the start. Every line now has a meaning:
SSE: sum of squared errors; SST: total sum of squares
On paper, then with your neighbour:
Next session: cross-validation and regularisation.
GENERATED from slides.src.md by tools/codewalk/build.py. Edit the source, not this file.