Session 9 · Fitting a line

Session 9: Fitting a line

How much does Apple move when the market moves? Today you measure it, judge the answer, and find it a second way.

Data Science and Advanced Programming · UNIL · 2026

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

What the ledger cannot tell you

Session 6's report, one more time:

ticker shares price value
AAPL 10 190.50 1905.00
NESN 4 102.30 409.20
VOO 2 512.00 1024.00

Total: 3338.20. The report says what you own. It says nothing about what could happen to it.

The question: if the market falls 2 % tomorrow, how much does this portfolio lose? Write down a guess now. We answer it at the end, with a number.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Today: one question, one script

  1. From prices to returns
  2. One column: centre and spread
  3. Two columns: do they move together?
  4. A line through the cloud: least squares
  5. How good is the line?
  6. Why squares? A model for the noise
  7. Walking downhill: the same line, found by search
  8. More than one
  9. Fit the past, judge the future
  10. Back to the ledger

Part 1 of the course asked "what is the total?". From today, Part 2 asks "what does the data tell us?"

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv(one year, four columns"prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
not run yet

The data: prices.csv

One row per trading day, one column per position:

Date,AAPL,NESN,VOO,MSFT 2025-11-17,134.20,…,390.88,… … (248 more days) 2026-10-30,190.50,102.3,512.00,410.0

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
not run yet

Read it cold

Two minutes, on your own. This is today's whole script.

  • Line 9 divides a covariance by a variance. What could that ratio measure?
  • Line 14 compares two sums of squares. What do you expect its value to be: closer to 0 or to 1?
  • Predict: if the market moves +1 %, how much does Apple move?
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
days: 249
mean, VOO, AAPL: 0.114 0.156
sd, VOO, AAPL: 1.016 1.735
correlation: 0.759
slope b: 1.296 intercept a: 0.009today's number
R squared: 0.577

What it prints

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 %.
  • But why this formula? Is 1.296 right? And what is "R squared"?

Most of today's slides have mathematics on the left instead of code. Next slide: how to read them.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
How to read these slides

The left side holds the mathematics. It changes from slide to slide.

A gold box with a number points at one part:

Math on the left, words on the right

The same layout as the code slides: equations on the left, explanations on the right.

  • A gold box marks the part we are talking about. Its number, like 1, comes back on the right.
  • A pale row is context: you saw it on an earlier slide.
  • A gold bar on the left edge marks a row that is new on this slide.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 1

From prices to returns

Prices are not comparable. Changes are.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
prices.csv, one year

One year, four positions

Each price divided by its first-day price, times 100. So all four lines start at 100.

  • Apple ends about 42.0 % up, VOO 31.0 %.
  • Apple's line is more jagged, and its ups and downs follow VOO's, but not exactly.

"Follows, but not exactly" is today's question in a picture. To measure it, we look at daily changes, not price levels.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Return

Apple's price on day , and on the day before:

The return on day :

A return: how much did the price change?

1 Today's price divided by yesterday's. If nothing changed, the ratio is 1, and the return is 0.

  • A return has no unit: a 2 % day means the same for a 190 share and a 512 share.

That is why we compare returns, not prices.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Return

Apple's price on day , and on the day before:

The return on day :

In per cent, on 2026-10-30:

One day, by hand

On 2026-10-30, Apple closed at 190.50; the day before, at 186.53.

  • The ratio is 1.0213: the price grew by about 2 %.
  • Times 100 to read it in per cent.

Judge it: a 2 % day for one stock is normal. A 90 % day is not.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.r_t, every day, every columnpct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
not run yet

Lines 3–4: prices in, returns out (session 6)

  • read_csv(..., index_col="Date"): a DataFrame, with dates as row names (session 6).
  • pct_change() computes for every day and every column at once.
  • The first day has no "day before", so its return is NaN, missing (session 6). dropna() removes that row.
  • * 100: per cent.

250 prices give 249 returns. From now on, every number is a daily return in %.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Names

Two columns, two letters

Lines 6–7 of the script, in mathematics.

  • is the column we use to explain: the market.
  • is the column we want to explain: Apple.

The same letters, for what we know and for what we want, are used in every textbook and every library. You will see them all through Part 2.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 2

One column: centre and spread

Two numbers that summarise 249 days.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Mean

The mean

("x bar"): the average daily return of VOO.

1 The sum of over all days, to . Every formula today is written with ; the index under it says what changes from term to term, the limits say where it starts and stops.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Mean, five days

is a 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 on these slides is a loop like this one. pandas runs it for you: x.mean().

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Variance

Variance: how far from the mean, on average

is a deviation: how much better or worse than average day was. Added up, deviations always give 0: the mean sits in the middle.

1 So we square them. A square is never negative: nothing cancels, and big deviations count a lot.

2 Then average, dividing by . That is what pandas does (.var()). With 249 days, the difference from is tiny.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Why n − 1

Why ?

The deviations are measured from , which was computed from the same data. The data sit a little closer to their own mean than to the true centre, so the plain average of squares comes out slightly too small. Dividing by corrects this.

  • 5 days: divide by 4 instead of 5, a 25 % difference.
  • 249 days: divide by 248 instead of 249, 0.4 %.

Not for the exam. Just know that pandas' .var() and .std() divide by .

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Standard deviation

The whole year:

Standard deviation: spread in per cent

The variance is in per cent squared. The square root returns to the unit of the data, per cent.

  • On a typical day, VOO is about 1.016 % away from its mean; Apple about 1.735 %.
  • Apple moves more than the market: a first hint of today's answer.

Finance calls the standard deviation of returns volatility.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Judge it: are these numbers believable?

Before any model, check by hand that the numbers make sense.

  • VOO's mean: 0.114 % per day. Times 249 days, about 28 %. The chart said +31.0 % for the year. Close; the gap is compounding (gains on gains).
  • The market moves about 1 % on a typical day: normal for stock markets.
  • One stock more volatile than the market: normal. A company has its own news.

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?

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 3

Two columns: do they move together?

One dot per day, and one number for the shape of the cloud.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
One dot = one day

The cloud

Each dot is one day: across, VOO's return; up, Apple's return. 249 dots.

  • The dots go from bottom left to top right: when the market is up, Apple tends to be up.
  • But they spread around: Apple has its own news.

"Tends to" is not a number yet. Next: one number for it.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Covariance

Cut the cloud at the means

Draw a line at each mean. Every day lands in one of four boxes.

  • Blue boxes: both above their mean, or both below. The product of the two deviations is positive. 95 + 95 days.
  • Red boxes: one up, one down. The product is negative. 28 + 31 days.

Most days are blue: the two columns agree much more often than they disagree.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Covariance

Covariance: the boxes, in one number

1 The product of the two deviations: positive in blue boxes, negative in red ones. Add them all up, divide by .

  • Positive: the columns move together. Negative: in opposite directions. Near 0: no pattern.
  • Put in both places, and you get back: the variance is the covariance of a column with itself.

Apple and VOO: 1.339. Positive, but its size depends on the units, so it cannot be compared across pairs.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Correlation

Correlation: covariance without units

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
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Correlation is not causation

A correlation says two columns move together. It does not say which one pushes the other, or whether a third thing pushes both.

  • Here we have a reason: Apple is part of VOO, and both react to the same news.
  • Ice-cream sales and sunburns are correlated. Ice cream does not cause sunburn: summer causes both.

Today's line describes how Apple moves with the market. It does not prove that the market makes Apple move.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
days: 249
mean, VOO, AAPL: 0.114 0.156
sd, VOO, AAPL: 1.016 1.735
correlation: 0.759
slope b: 1.296 intercept a: 0.009
R squared: 0.577

The same, in pandas

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 4

A line through the cloud

From "they move together" to "by how much".

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Supervised learning: learn from examples

We have 249 examples: pairs , what we knew and what happened. We want a rule that gives from , also on days we have not seen. Learning a rule from examples with answers is called supervised learning.

1 · modelthe shape of the rule:
today, a line
→
2 · lossone number: how
wrong is the rule?
→
3 · minimisefind the rule with
the smallest loss
→
4 · testis it right? does it
work on new data?
  • Regression: is a number (Apple's return). Today.
  • Classification: is a category (will Apple close up or down?). Later in Part 2.

Every model in Part 2, up to neural networks, follows these four steps.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 1 · the model

The model: a line

1 , "y hat": the line's prediction for Apple on day . The hat means "fitted", not "observed".

2 The slope : if the market moves 1 %, the line says Apple moves %.

  • is the intercept: Apple's return on a day when the market does not move.
  • and are the model's parameters: the two numbers we must choose.

In finance, has a name: beta. A stock with amplifies the market.

Machine-learning words: is the feature, the target.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Which line?

Which line is best?

Three choices of , through the same cloud.

  • : Apple ignores the market. Clearly wrong.
  • : better, but too flat at both ends.
  • : through the middle of the cloud.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 2 · the loss

On 2026-10-30:

The residual: how wrong on one day

1 What happened minus what the line said.

On 2026-10-30, VOO rose 0.382 %. With , the line says Apple should rise 0.504 %. Apple rose 2.128 %: the line missed by 1.624 points.

  • : the dot is above the line.
  • : the dot is below the line.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 2 · the loss

Every day has a residual

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?

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 2 · the loss

Three ways to add up the misses

  • Plain sum: misses above and below cancel. A terrible line can score 0.
  • Absolute values: no cancelling. A fair choice, but harder to work with.
  • 1 Squares: no cancelling, big misses count a lot, and the mathematics stays simple.

The same reason as for the variance. Squares win, and the method is called least squares.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 2 · the loss

The loss: one number for a whole line

Put the line into the residual, square, average: the mean squared error (MSE).

1 depends on and . The data are fixed; we choose the line. Every choice of gets a score.

The best line is the one with the smallest loss. That is step 3.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 3 · minimise

The loss is a bowl

Fix at its best value; is then a function of alone. Expand each square: every term is quadratic in , and averaging over the days (the bars) only produces the three numbers in front of , and . So is a parabola.

1 The coefficient of is the average of : never negative. The parabola opens upwards, so it has exactly one lowest point:

There the curve is flat, its slope zero: the condition we use next.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 3 · minimise

Two conditions for the lowest point

1 Read "partial L, partial a": how fast changes when you nudge a little, keeping fixed.

At the bottom of the bowl, a small nudge in any direction does not change . So both rates are zero.

Two equations, two unknowns. The next two slides solve them.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 3 · minimise

The intercept

The residuals must add up to zero. Divide by , and averages appear.

1 Once we know , the intercept follows.

Read it the other way round: . The best line passes through the point of means , the centre of the cloud.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 3 · minimise

Put in , and collect terms:

The slope

After a few lines of algebra, two old friends appear:

  • on the left, the sum behind the covariance;
  • on the right, the sum behind the variance.

1 The slope is the covariance divided by the variance of . How much and move together, per unit of how much moves on its own.

That is line 9 of the script, x.cov(y) / x.var().

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 3 · minimise

The numbers

Both inputs come from Part 3.

  • Slope . When the market moves 1 %, Apple moves about 1.3 %, on average.
  • Intercept % per day: practically zero. On a flat market day, Apple is flat too, on average.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Slope and correlation

The slope is a rescaled correlation

Multiply and divide by , and the formula splits in two:

1 the correlation: how tightly the cloud follows a line;

: how much more Apple moves than the market, 1.735 against 1.016.

So a high beta has two possible sources: a tight link to the market, or simply a lot of movement. For Apple, both.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The fitted line

The least-squares line

No other line has a smaller mean squared error than this one: 1.269.

  • It passes through the centre of the cloud, .
  • About half the dots are above it, half below.

Now use it.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Using the line

What the line says

Put a market move in, get Apple's expected move out.

  • Market +1 %: Apple about 1.304 %.
  • Market −2 %: Apple about -2.583 %.

Expected means "on average, on days like this". On a single day, Apple can be far from the line: remember the residuals.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Step 4 · test: we know the truth

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.

  • Close, not exact: the noise (rng.normal) shakes the dots, and 249 days cannot remove all of it.
  • With real data there is no 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.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
days: 249
mean, VOO, AAPL: 0.114 0.156
sd, VOO, AAPL: 1.016 1.735
correlation: 0.759
slope b: 1.296 intercept a: 0.009as by hand
R squared: 0.577

The formula is two lines of code

  • Line 9: the slope, word for word: covariance over variance.
  • Line 10: the intercept: the line goes through the means.
  • Lines 12–13: the fitted values and the residuals , for all days at once.

The line is the best possible. Is it good? Line 14 answers that.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 5

How good is the line?

The best line can still be a poor description.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
How much is explained

Start without the market

Suppose you knew nothing about the market. Your best guess for Apple, every day, is its mean 1.

, the total sum of squares, measures how wrong that guess is: how much Apple moves around its mean.

746.2: this is the amount there is to explain.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
How much is explained

What the line leaves over

, the sum of squared errors: the same sum, but around the line instead of the mean.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
How much is explained

: the share explained

1 (sum of squared errors) over (total sum of squares): the share the line does not explain. One minus that is the share it does.

The market explains 0.577, about 58 %, of Apple's daily ups and downs. The other 42 % is Apple's own news.

  • : the line is no better than the mean. : every dot on the line.
  • With one , is simply the correlation squared. That is line 14 of the script.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Is 0.58 good?

There is no fixed threshold. It depends on the question.

  • For one stock against the market, 0.58 is high. Many stocks are below 0.3.
  • A low does not make the beta wrong. It says that most of the movement comes from somewhere else.
  • For predicting tomorrow's return of Apple alone, 0.58 is not enough: 42 % is unexplained, and you do not know tomorrow's market move anyway.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The residuals

Look at what is left over

  • The residuals average exactly zero: that is the condition . Least squares always does this.
  • Their standard deviation: 1.129 %. On a typical day, the line misses by about 1 %.
  • The biggest miss: 3.43 %. Large, but possible for one stock on one day.

Always look at the biggest residual. If it is absurd, the data probably are too.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Anscombe's quartet (1973)

Same numbers, four different stories

Four small data sets (Francis Anscombe, 1973) with the same summary:

  • means , ; standard deviations 3.32 and 2.03;

  • 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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
plot_first.py
1import pandas as pd
2
3anscombe = pd.read_csv("anscombe.csv")
4dozen = pd.read_csv("datasaurus.csv")
5
6def describe(name, x, y):
7 b = x.cov(y) / x.var()
8 a = y.mean() - b * x.mean()
9 print(name.ljust(8), round(x.mean(), 2), round(y.mean(), 2),
10 round(x.std(), 2), round(y.std(), 2),
11 round(x.corr(y), 3), round(a, 2), round(b, 3))
12
13print("set, mean x, mean y, sd x, sd y, corr, a, b")
14for name in ["I", "II", "III", "IV"]:
15 rows = anscombe[anscombe["set"] == name]
16 describe(name, rows["x"], rows["y"])
17for name in ["dino", "star", "x_shape", "circle"]:
18 rows = dozen[dozen["dataset"] == name]
19 describe(name, rows["x"], rows["y"])
$ python plot_first.py
set, mean x, mean y, sd x, sd y, corr, a, b
I 9.0 7.5 3.32 2.03 0.816 3.0 0.5
II 9.0 7.5 3.32 2.03 0.816 3.0 0.5
III 9.0 7.5 3.32 2.03 0.816 3.0 0.5
IV 9.0 7.5 3.32 2.03 0.817 3.0 0.5
dino 54.26 47.83 16.77 26.94 -0.064 53.45 -0.104
star 54.27 47.84 16.77 26.93 -0.063 53.33 -0.101
x_shape 54.26 47.84 16.77 26.93 -0.066 53.55 -0.105
circle 54.27 47.84 16.76 26.93 -0.068 53.8 -0.11

The Datasaurus

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.

  • Lines 2–5 of the output: Anscombe's four sets. Identical to the third decimal.
  • Lines 6–9: four of the dozen. Means 54.3 and 47.8, correlation -0.06, every time.

Next slide: what they look like.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Datasaurus Dozen (Matejka & Fitzmaurice, 2017)

Same statistics, different pictures

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 6

Why squares? A model for the noise

Least squares is not just convenient. It follows from an assumption about the noise.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
A model with noise

The line, plus noise

The line was a rule for . Now we describe how the data were generated:

1 ("epsilon"): the part of Apple's return the market does not explain, different every day.

2 We assume it is normally distributed, centred at 0, with standard deviation , independently from day to day.

This is exactly line 13 of make_prices.py: , , %. For real data, it is an assumption to check.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The normal density

How likely is a residual of size ?

The bell curve. 1 The residual enters squared, in an exponent: small residuals are likely, large ones become unlikely very fast.

  • About 68 % of draws fall within , about 95 % within .
  • Our residuals: 71 % within one standard deviation, 95 % within two.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Residuals of the fitted line

Do the residuals look normal?

The histogram of the 249 residuals, and a normal curve with the same standard deviation.

  • Centred at zero, symmetric, no long tails: the assumption looks reasonable here.
  • Real stock returns have fatter tails than this: more extreme days than a normal curve allows. Simulated data are tidier than markets.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Likelihood

The likelihood of the whole year

For a candidate line and noise level , each day's residual has a density .

1 : the product over all days, as is the sum. Days are independent, so their probabilities multiply.

is the likelihood: how probable the observed year is, if the model with these parameters were true.

Maximum likelihood: choose the parameters that make the observed data most probable.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Likelihood

Take the logarithm

The log turns the product into a sum, and the exponent comes down. The maximum stays in the same place.

For fixed , the first term does not depend on and . What is left: minus a constant times 1, the sum of squared residuals.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The noise level

Maximum likelihood also estimates

Maximise over as well (: the sum of squared errors): the answer is the mean squared residual, the minimum of our loss.

  • %, against the true 1.1 % in make_prices.py.
  • A third check against the truth, after (1.296 vs 1.25).

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
What the noise model rules out

How extreme is the biggest miss?

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 7

Walking downhill

The same line, found without a formula.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Why find it a second time?

For a line, least squares has an exact formula. Most models do not.

  • A neural network, later in Part 2, has thousands or millions of parameters. No formula gives them.
  • But it still has a loss, and we still want it small.

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: . If the method works, it must find the same number.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The gradient

Which way is downhill?

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.

  • : increasing makes the loss bigger, so decrease .
  • : increase .

The pair of rates is called the gradient. It points uphill; we go the other way.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
One step

The update rule

means "becomes", like = in Python: a = a - rate * grad_a.

1 Minus: against the gradient, so downhill. ("eta") is the learning rate: the size of the step.

Repeat: compute the gradient, step; compute it again, step again. Each step lowers the loss a little.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Step 1, by hand

The first step

Start from , : a prediction of 0 % every day.

  • Both rates are negative: increasing or lowers the loss.
  • With learning rate : moves to 0.031, to 0.270.

moves much more than , because the loss is much steeper in the direction.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
descent.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5x = returns["VOO"]
6y = returns["AAPL"]
7
8a = 0.0 # start anywhere: a flat line at zero
9b = 0.0
10rate = 0.1 # the learning rate: step size
11print("step, loss, a, b")
12for step in range(1, 61):
13 errors = (a + b * x) - yŷ − y, every day at once
14 loss = (errors ** 2).mean() # mean squared error
15 grad_a = 2 * errors.mean() # rate of change in a
16 grad_b = 2 * (errors * x).mean() # rate of change in b
17 a = a - rate * grad_a # step downhill
18 b = b - rate * grad_b
19 if step in [1, 2, 3, 5, 10, 20, 40, 60]:
20 print(step, round(loss, 3), round(a, 3), round(b, 3))
$ python descent.py
step, loss, a, b
1 3.021 0.031 0.27
2 2.36 0.05 0.483
3 1.951 0.06 0.652
5 1.538 0.065 0.89
10 1.297 0.046 1.166
20 1.269 0.016 1.282
40 1.269 0.009 1.296
60 1.269 0.009 1.296the formula's answer

Gradient descent, in code

The update rule, inside a for loop.

  • Lines 13–16: errors, loss, the two rates.
  • Lines 17–18: one step downhill.
  • Output: step, loss, , . Step 1 matches the hand calculation: .

After about 40 steps, stops changing at 1.296: the formula's answer. Two methods, one line.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The path

The walk, seen from above

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 and walks to the bottom of the valley.

  • Big steps at first: the ground is steep.
  • Small steps at the end: near the bottom the ground is flat, so the gradient is small.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
descent.py changed on this slide
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5x = returns["VOO"]
6y = returns["AAPL"]
7
8a = 0.0 # start anywhere: a flat line at zero
9b = 0.0
10rate = 1.2 # the learning rate: step size
11print("step, loss, a, b")
12for step in range(1, 61):
13 errors = (a + b * x) - y
14 loss = (errors ** 2).mean() # mean squared error
15 grad_a = 2 * errors.mean() # rate of change in a
16 grad_b = 2 * (errors * x).mean() # rate of change in b
17 a = a - rate * grad_a # step downhill
18 b = b - rate * grad_b
19 if step in [1, 2, 3, 5, 10, 20, 40, 60]:
20 print(step, round(loss, 3), round(a, 3), round(b, 3))
$ python descent.py
step, loss, a, b
1 3.021 0.374 3.243
2 5.512 -1.034 -1.724
3 12.574 2.291 6.112
5 93.8 8.46 14.3
10 21383.629 -148.459 -183.34
20 1196178787.58 -35846.653 -43078.819
40 3.7472840474573696e+18 -2007220501.015 -2410505848.601
60 1.173916556823452e+28 -112345445739842.27 -134917548280469.34

Too big a step

One change: learning rate 1.2 instead of 0.1.

  • Each step jumps over the valley and lands higher on the other side.
  • The loss grows: 3, 5, 12, 94, … then .
  • No error message. The numbers just explode: it runs and lies.

A loss that grows is the signature of a learning rate that is too big.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Why 1.2 explodes

Why: each step multiplies the distance

is the answer. Each step multiplies the distance to by a fixed number, which depends on the learning rate and on how steep the bowl is (2.08 here).

  • : times 0.79. The distance shrinks at every step.
  • : times -1.50. You land on the other side, and further away: the distance grows by half at every step.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

The learning rate is your choice

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Mini-batch

: 20 days drawn at random, new ones at every step

Use a sample of days

1 Sum over a batch of 20 random days instead of all 249. is the size of the batch.

  • The batch gradient is an estimate: right on average, but noisy.
  • Each step is about 12 times cheaper.

This is stochastic (random) gradient descent, with mini-batches. It is how every neural network is trained.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
sgd.py
1import numpy as np
2import pandas as pd
3
4prices = pd.read_csv("prices.csv", index_col="Date")
5returns = prices.pct_change().dropna() * 100 # in %
6x = returns["VOO"].to_numpy()
7y = returns["AAPL"].to_numpy()
8
9rng = np.random.default_rng(9)
10a, b, rate = 0.0, 0.0, 0.1
11print("step, loss on all days, a, b")
12for step in range(1, 201):
13 days = rng.choice(len(x), size=20) # 20 random days
14 errors = (a + b * x[days]) - y[days]
15 a = a - rate * 2 * errors.mean()
16 b = b - rate * 2 * (errors * x[days]).mean()
17 if step in [1, 5, 20, 50, 100, 150, 200]:
18 loss = (((a + b * x) - y) ** 2).mean()
19 print(step, round(loss, 3), round(a, 3), round(b, 3))
$ python sgd.py
step, loss on all days, a, b
1 1.877 0.227 0.538
5 1.36 0.014 1.0
20 1.27 0.033 1.278
50 1.272 -0.013 1.353
100 1.283 0.121 1.328
150 1.276 0.016 1.378
200 1.271 0.027 1.248

Mini-batch descent, in code

Line 13 draws 20 day numbers; x[days] picks those days' returns. Lines 15–16: the same update as before.

  • gets near 1.296 in about 20 steps.
  • Then it wanders: 1.35, 1.33, 1.38, 1.25. Each batch pulls a little differently.
  • The loss on all days stays close to the best, 1.269.

Good enough, at a fraction of the cost. For noisy problems, "close and cheap" beats "exact and slow".

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Two walks

Two walks to the same valley

  • Gold: all 249 days at every step. A smooth path, straight to the bottom.
  • Red: 20 random days at every step. A shaky path that reaches the valley quickly, then keeps moving around the bottom.

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 .

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 8

More than one

A plane instead of a line, and categories as columns.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
multi.py
1import pandas as pd
2from sklearn.linear_model import LinearRegression
3
4prices = pd.read_csv("prices.csv", index_col="Date")
5returns = prices.pct_change().dropna() * 100 # in %
6y = returns["AAPL"]
7
8for columns in [["MSFT"], ["VOO"], ["VOO", "MSFT"]]:
9 X = returns[columns] # one column, or two
10 model = LinearRegression().fit(X, y)
11 print(columns, "b:", model.coef_.round(3),
12 "a:", round(model.intercept_, 3),
13 "R2:", round(model.score(X, y), 3))
$ python multi.py
['MSFT'] b: [0.701] a: 0.068 R2: 0.375
['VOO'] b: [1.296] a: 0.009 R2: 0.577
['VOO', 'MSFT'] b: [1.164 0.119] a: 0.009 R2: 0.581

Does Microsoft explain Apple?

Line 8, first round: regress Apple on Microsoft instead of the market.

  • Slope 0.701, : when Microsoft moves 1 %, Apple moves 0.7 %. A third of Apple's movement "explained".
  • Is that a real link between the two companies? Both are large tech stocks. Both are in VOO.

To find out, put both columns in the same model.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Two features

Multiple regression

: VOO, : MSFT. Same model idea, same loss, one more parameter.

1 now means: how much Apple moves when VOO moves 1 %, with Microsoft held fixed. Each slope measures what its column adds on top of the others.

With two features, the fitted model is a plane through a three-dimensional cloud.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Matrix form

One formula for any number of columns

Stack the features as columns of a table , with a column of ones for the intercept. One row per day.

1 Setting all partial derivatives to zero gives this normal equation. With one , it reduces to .

You will not compute it by hand: LinearRegression().fit(X, y) does, for any number of columns.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
multi.py
1import pandas as pd
2from sklearn.linear_model import LinearRegression
3
4prices = pd.read_csv("prices.csv", index_col="Date")
5returns = prices.pct_change().dropna() * 100 # in %
6y = returns["AAPL"]
7
8for columns in [["MSFT"], ["VOO"], ["VOO", "MSFT"]]:
9 X = returns[columns] # one column, or two
10 model = LinearRegression().fit(X, y)
11 print(columns, "b:", model.coef_.round(3),
12 "a:", round(model.intercept_, 3),
13 "R2:", round(model.score(X, y), 3))
$ python multi.py
['MSFT'] b: [0.701] a: 0.068 R2: 0.375
['VOO'] b: [1.296] a: 0.009 R2: 0.577
['VOO', 'MSFT'] b: [1.164 almost nothing left0.119] a: 0.009 R2: 0.581

Hold the market fixed

features VOO MSFT
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 barely moves. Microsoft "explained" Apple only because both follow the market: a third variable, as on the causation slide.

In make_prices.py, the true values are 1.25 and 0.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Categories

Is Monday different?

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
One-hot encoding

One-hot encoding

Each dummy column is 1 on its weekday and 0 otherwise. On every row, exactly one column is "hot".

1 : how much more (or less) Apple returns on a Monday than on the baseline day, for the same market move.

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).

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
onehot.py
1import pandas as pd
2from sklearn.linear_model import LinearRegression
3
4prices = pd.read_csv("prices.csv", index_col="Date")
5returns = prices.pct_change().dropna() * 100 # in %
6
7day = pd.to_datetime(returns.index).day_name() # "Monday"
8dummies = pd.get_dummies(day, drop_first=True, dtype=int)
9dummies.index = returns.index
10
11X = pd.concat([returns[["VOO"]], dummies], axis=1)
12print(X.head(3))
13model = LinearRegression().fit(X, returns["AAPL"])
14print("b:", model.coef_.round(3))
15print("R2:", round(model.score(X, returns["AAPL"]), 3))
$ python onehot.py
VOO Monday Thursday Tuesday Wednesday
Date
2025-11-18 0.268625 0 0 1 0
2025-11-19 -1.763070 0 0 0 1
2025-11-20 1.366163 0 1 0 0
b: [ 1.287 -0.115 -0.173 -0.342 -0.266]
R2: 0.581

One-hot encoding, in code

pd.get_dummies makes one column per weekday; drop_first=True drops the first in alphabetical order, Friday.

  • The table: VOO's return, then four 0/1 columns. 18 November 2025 was a Tuesday.
  • Slopes: VOO 1.287; weekdays between -0.342 and -0.115 % relative to Friday.
  • : 0.581, up from 0.577.

We simulated no weekday effect. These four numbers fit noise, and rose anyway. Adding columns never lowers on the data you fit. Next part: why that is a problem.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 9

Fit the past, judge the future

A smaller loss on the data you have is not a better model.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Train and test

Hold some days back

Split the year in two.

  • Training set: the first 200 days. The model is fitted on these only.
  • 1 Test set: the last 49 days, 2026-08-25 to 2026-10-30. The model never sees them while fitting.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
More flexible models

Curves instead of a line

1 Add powers of as extra columns: the curve can bend. Degree has parameters. Degree 0 is a flat line at the mean.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
A line and a degree-15 curve

Two models, the same training data

Dark: the line. Gold: degree 15. Both fitted on the blue dots only.

  • The curve bends to pass closer to the blue dots: lower training error.
  • At the edges, it swings to chase a few extreme days.
  • The red test days do not follow the swings.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
overfit.py
1import numpy as np
2import pandas as pd
3
4prices = pd.read_csv("prices.csv", index_col="Date")
5returns = prices.pct_change().dropna() * 100 # in %
6x = returns["VOO"].to_numpy()
7y = returns["AAPL"].to_numpy()
8
9x_train, y_train = x[:200], y[:200] # the first 200 days
10x_test, y_test = x[200:], y[200:] # the last 49 days
11print("degree, train error, test error")
12for degree in [0, 1, 3, 8, 15]:
13 c = np.polyfit(x_train, y_train, degree) # 1 = a line
14 train = ((np.polyval(c, x_train) - y_train) ** 2).mean()
15 test = ((np.polyval(c, x_test) - y_test) ** 2).mean()
16 print(degree, round(train, 3), round(test, 3))
$ python overfit.py
degree, train error, test error
0 3.075 2.687
1 1.228 1.447best on new data
3 1.218 1.453
8 1.196 1.467
15 1.169 1.535

Train error falls, test error does not

  • Degree 0, a flat line: bad on both sets (3.075, 2.687). Too simple.
  • Degree 1: the lowest test error, 1.447.
  • Degree 3 to 15: training error keeps falling, to 1.169. Test error rises, to 1.535.

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Error by degree

The picture behind every model choice

  • Training error (blue) falls with every degree. It is always too optimistic.
  • Test error (red) is lowest at degree 1 and rises after.
  • The dotted line: the noise in make_prices.py, . No model can do better on average: the noise is not predictable.

The training error dips below the noise line. That is the clearest sign of overfitting: the model "explains" variation that is pure chance.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Bias–variance, at one market return x

: the average over many training sets and over the noise of the new day

Three sources of test error

Part 6's model: signal plus noise . is fitted on one training set; other days give another. The average error splits in three:

1 Bias: the average fitted model misses the true . Too simple.

2 Variance: changes from one training set to another. Too flexible.

3 Noise: , the standard deviation of , is 1.1 % in make_prices.py: . No model can predict it.

Flexibility lowers bias and raises variance: the bias–variance trade-off.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
20 fits, each on a random half of the year

Bias and variance, seen

Each gold line is fitted on a different random half of the year.

  • Degree 0: all 20 fits agree, and all miss the slope. High bias, low variance.
  • Degree 12: the fits disagree wildly, above all at the edges. Low bias, high variance.
  • Degree 1: the fits agree and follow the cloud.

A model you would trust is one that gives similar answers on similar data.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Occam's razor

"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.

  • Degree 1 over degree 15: equal or better on the test days, with 2 parameters instead of 16.
  • VOO alone over VOO and MSFT: 0.577 against 0.581. Microsoft adds nothing real.
  • No weekday dummies: they fitted noise.

Add a column only when the test error says it helps.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Part 10

Back to the ledger

The question from the start.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Three positions, three betas

Every position has a beta

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
  • Apple and Microsoft amplify the market. Nestlé moves less than half as much: people buy coffee in a recession too.
  • VOO against itself gives exactly 1.00: a good check that the code is right.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Portfolio beta

The beta of the whole portfolio

is each position's weight: its share of the total value, from the ledger.

1 The portfolio's beta is the weighted average of the betas: another , another loop over the ledger.

MSFT is not in the sum: its row has no shares (session 6), so its value is unknown.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The answer

If the market falls 2 % tomorrow

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.

  • More than 2 %: Apple is more than half the ledger, and Apple amplifies the market.
  • Expected, not certain: said that a large part of each stock's movement is its own.
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py changed on this slide
1import pandas as pd
2
3prices = pd.read_csv("prices_typo.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
days: 249
mean, VOO, AAPL: 0.114 3.417
sd, VOO, AAPL: 1.016 57.384
correlation: -0.013
slope b: -0.751 intercept a: 3.502below zero?
R squared: 0.0

Spot the lie

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.

  • Beta −0.751: Apple goes down when the market goes up?
  • : the market explains nothing?
  • No crash, no warning.

Which output do you believe? Before the next slide: how would you find out?

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
The classmate's cloud

The lie, explained

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Why one day wins

Squares punish big misses

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

Before you trust a fitted line

  • Plot the cloud. Any dots far from the rest?
  • Check the extremes. A −90 % day for Apple did not happen.
  • Check the sign and the size of the slope. Beta of a large stock: usually between 0.5 and 2.
  • Check . Between 0 and 1, and plausible for the question?
  • Check one number by hand (session 6).

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.

Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
beta.py
1import pandas as pd
2
3prices = pd.read_csv("prices.csv", index_col="Date")
4returns = prices.pct_change().dropna() * 100 # in %
5
6x = returns["VOO"] # the market
7y = returns["AAPL"] # one stock from the ledger
8
9b = x.cov(y) / x.var() # the slope: beta
10a = y.mean() - b * x.mean() # the intercept
11
12fitted = a + b * x
13residuals = y - fitted
14r2 = 1 - (residuals ** 2).sum() / ((y - y.mean()) ** 2).sum()
15
16print("days:", len(returns))
17print("mean, VOO, AAPL:", round(x.mean(), 3), round(y.mean(), 3))
18print("sd, VOO, AAPL:", round(x.std(), 3), round(y.std(), 3))
19print("correlation:", round(x.corr(y), 3))
20print("slope b:", round(b, 3), " intercept a:", round(a, 3))
21print("R squared:", round(r2, 3))
$ python beta.py
days: 249
mean, VOO, AAPL: 0.114 0.156
sd, VOO, AAPL: 1.016 1.735
correlation: 0.759
slope b: 1.296 intercept a: 0.009
R squared: 0.577

Read it again

The script from the start. Every line now has a meaning:

  • 3–4: prices → returns, in % (Part 1)
  • 6–7: is the market, is Apple
  • 9–10: least squares: , (Part 4)
  • 12–14: fitted values, residuals, (Part 5)
  • 16–21: the numbers you checked by hand (Parts 2–3)
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line
Today, in five lines

SSE: sum of squared errors; SST: total sum of squares

Check yourself

On paper, then with your neighbour:

  1. A stock is exactly as volatile as the market, with correlation 0.3. What are its beta and its ?
  2. Least squares squares the residuals. What does that buy, and what does it cost?
  3. Correlation 0.9, beta 0.5: is that possible?
  4. A portfolio is half VOO, half Nestlé. What is its beta?
  5. Your script prints beta −0.75 for Microsoft. Name two things you check first.
  6. Weekday dummies raise from 0.577 to 0.581. Is the model better?
Data Science and Advanced Programming · UNIL · 2026
Session 9 · Fitting a line

What you can now do

  • Turn prices into returns; summarise a column with its mean and standard deviation.
  • Translate between notation and a loop.
  • Measure how two columns move together, and know what correlation does not prove.
  • Fit a line by least squares, explain , read beta and ; plot first.
  • Derive least squares from a normal noise model, by maximum likelihood.
  • Find the same line by gradient descent, full-batch and mini-batch.
  • Fit several features, and encode categories with one-hot columns.
  • Judge a model on data it has not seen, and explain bias, variance and Occam's razor.

Next session: cross-validation and regularisation.

Data Science and Advanced Programming · UNIL · 2026

GENERATED from slides.src.md by tools/codewalk/build.py. Edit the source, not this file.