| ticker | shares | price | value |
|---|---|---|---|
| AAPL | 10 | 190.50 | 1905.00 |
| NESN | 4 | 102.30 | 409.20 |
| VOO | 2 | 512.00 | 1024.00 |
Apple is more than half of the ledger. A risk manager does not need tomorrow's exact return. They need to know: is today a bad day for Apple, a fall of more than 2 %?
On the ledger's 1905.00 in Apple, a bad day costs more than 38. Predicting a category from data is classification, the second kind of supervised learning.
Four methods, each with its own idea: look at similar days, fit a probability curve, ask yes-or-no questions, let many models vote. All four are judged the same way, on the same test year.
history.csv: daily prices of the four ledger positions, 2022-01-17 to 2026-10-30.
prices.csv, unchanged.make_history.py).Why more days? Bad days are rare: about one in ten. To learn what precedes them and to judge a classifier honestly, one year is too little. We train on the four years and test on the year you already know.
Two minutes, on your own.
Is 14 of 24 good? What did it cost? And is this the best method? By the end of the session you can answer all three, with numbers.
Part 1
What exactly do we predict, from what, and against which baseline?
Line 9 of the script. 1 Each day gets a class label: 1 for a bad day, the positive class, and 0 for a normal day.
The share of ones is the base rate: about one day in ten. Bad days are the rare class, and that will shape everything we measure.
The labels come from Apple's return, but the model is not allowed to see that return: it is what we want to predict.
Lines 11–12: the first four years train, the last year tests. The comparison works on the date strings, because dates written year-month-day (the ISO standard format) sort in the right order.
.fit (line 14) sees only training days.predict_proba (line 15) is asked only about test days.Session 9 showed why: a model judged on the days it learned from looks better than it is. Everything we report today is from the test year, a year none of the models saw.
Session 9's cloud, now for the four training years. Red triangles: the 91 bad days, below the dashed line.
The market tells us something about the risk, not everything. A classifier has to turn "something" into a decision.
| session 9: regression | today: classification | |
|---|---|---|
| target |
a number: Apple's return | a class: bad day or not |
| the model gives | a predicted number |
a probability |
| loss | squared error | the log loss (Part 3) |
| judged by | mean squared error on test days | confusion matrix, recall, precision (Part 4) |
| overfitting | yes, the same danger | yes, the same danger |
The features are the same kind of thing as before: numbers we know on day
Our bad-day question is one case of a very common task: put each case into a class, from numbers you know about it.
The next four slides look at each one. The same methods of today apply to all of them.
Each dot is one past borrower (simulated, 800 of them). Red crosses: those who did not repay.
Defaults sit at the bottom right: high debt, short history. But the classes overlap, as our bad days did.
Missing a default costs the loan; refusing a good borrower costs the interest. Two mistakes, two prices: Part 4.
4020 payments (simulated): when they happened, and how much. Red stars: the 20 frauds.
Fraud detection is the extreme case of a rare positive class. Keep it in mind when Part 4 asks what "accuracy" is worth.
1797 real handwritten digits, scanned at 8 × 8 pixels; they ship with scikit-learn (load_digits).
Mail sorting, cheque reading and, with bigger images and neural networks (later in Part 2), face and object recognition all start here.
569 real tumour samples, measured under a microscope (load_breast_cancer in scikit-learn). Red: the 212 malignant ones.
The two classes separate well, but not perfectly. And here a missed malignant tumour costs far more than a second test: the threshold must reflect that.
| task | features |
label |
share positive | worst mistake |
|---|---|---|---|---|
| bad day | VOO, MSFT returns | bad / normal | 9.1 % | missed bad day |
| credit | debt ratio, history | default / repaid | 5.5 % | loan to a defaulter |
| fraud | hour, amount | fraud / normal | 0.5 % | fraud let through |
| tumour | 30 cell measurements | malignant / benign | 37 % | missed malignancy |
| digits | 64 pixels | 0, 1, …, 9 | ten classes | depends on use |
Same ingredients every time: known numbers
Each dot is one training day: across, VOO; up, Microsoft. Red triangles: bad days for Apple.
A classifier divides this plane into a region where it says "bad" and a region where it says "normal". The line between them is the decision boundary. Each method today draws a different kind of boundary.
1 Read "the probability that
2 A threshold
Two separate choices: the model, which gives
A "classifier" that always says "normal" is right 90.4 % of the time on the test year, and catches no bad day at all.
Every model today has to beat this, and "right 90.4 % of the time" already shows that the share of correct answers is a poor way to judge it. Part 4 fixes that.
Part 2
A market scenario arrives. How likely is a bad day for Apple?
A risk manager runs scenarios, as in session 9 ("if the market falls 2 %"). Today's scenario:
VOO falls -1.49 % and Microsoft -1.68 %. How likely is a bad day for Apple?
The simplest idea: look at the past days that looked like this scenario, and count how often they were bad.
The scenario is the star: VOO -1.49 %, Microsoft -1.68 %. Which training days looked most like it?
No equation, no parameters to fit. The training days are the model.
1
Two things are still open: what "closest" means, and how to choose
Two days
The last test day (2026-10-30) and its nearest training day (2024-03-01): Euclidean distance 0.034, Manhattan 0.046, in standardised units. Standardised?
A distance adds up differences across features. Microsoft moves about 1.450 % on a typical day, VOO 0.952 %: unscaled, Microsoft's differences would weigh more, for no good reason.
1 Standardise: subtract the mean, divide by the standard deviation (session 9's
Min–max rescales to
The whole method is the function on lines 11–15: a dozen symbols.
np.argsort gives the positions in order of distance; [:k] keeps the first Lines 17–20 ask this for every test day. Same result as scikit-learn's KNeighborsClassifier: 14 caught, 19 false alarms (Part 7).
Lines 12–13: the scaler learns the mean and standard deviation from the training years only, then transforms all days. The test year must not shape the model, not even through the scaling.
Each round (lines 16–25): fit, predict with the majority vote, count. Output columns:
Colour: the predicted probability of a bad day. White below 0.2, orange above, darker above 0.5.
The same picture as the polynomial degree in session 9, with
| test error | caught | false alarms | |
|---|---|---|---|
| 1 | 12.4 % | 7 | 14 |
| 5 | 8.0 % | 8 | 4 |
| 15 | 8.4 % | 6 | 3 |
| 151 | 9.6 % | 0 | 0 |
| strengths | weaknesses |
|---|---|
| no training: the data are the model | every prediction searches all training days |
| any shape of boundary | needs scaled features |
| easy to explain: "days like this one" | with many features, "near" stops meaning much |
| works for numbers too: average the neighbours' |
The last weakness has a name, the curse of dimensionality: in many dimensions, every day is far from every other day. With two or three features, k-nearest neighbours (kNN) is a strong, simple baseline.
Two things it cannot give: a smooth probability (with
Part 3
k-nearest neighbours gives jumpy probabilities and no number to interpret. Can a formula do better?
Fit a straight line to the 0/1 labels, by least squares, on VOO alone.
A line has no floor and no ceiling. A probability has both. We keep the line, and pass it through a function that maps any number into
It squeezes the whole number line into
Session 9's line gives a score
1 The odds: the chance of a bad day against the chance of a normal one. A probability of 20 % is odds of 20 to 80, or 1 to 4.
Undo the sigmoid, and the log of the odds is exactly session 9's line. Logistic regression is a linear model, on the log-odds scale.
The fitted model, with VOO's return as the only feature.
Each 1 % changes
Each dot is a training day, at 1 (bad) or 0 (normal), spread a little vertically so the dots do not hide each other.
Unlike the line, the curve stays between 0 and 1 everywhere.
On the log-odds scale the model adds; on the odds scale it multiplies.
1 Every additional 1 % fall of the market multiplies the odds of a bad day by
This is how logistic models are reported in finance, economics and medicine, as odds ratios: "each extra percentage point of market fall multiplies the odds of a bad day for Apple by about nine."
With one feature, the boundary is a single market return: where the curve crosses
A lower threshold raises more alarms: it catches more bad days, and cries wolf more often. Which threshold is right is a question about costs, not about the model.
In session 9, least squares came from the likelihood of normal noise. Here the same move gives the loss.
1 The probability the model gives to what actually happened:
Days are independent, so these multiply; the log turns the product into a sum. Minus the average is the log loss, also called cross-entropy. Maximum likelihood = minimum log loss.
Confident and wrong is punished hardest. A model that says "impossible" about something that happens pays without limit.
On the training years: a log loss of 0.196, against 0.305 for a model that predicts the base rate every day.
There is no formula for the best
LogisticRegression(C=np.inf) (line 22).C=np.inf switches off a small built-in penalty. The default, C = 1, shrinks the slope slightly:
Line 14 of the script: the same model with both features.
Add a third class: a good day, Apple up more than 2 %. In the training years: 91 bad, 799 normal, 109 good.
One score
A calm market: 95 % normal. VOO −2 %: 68 % bad. VOO +2 %: 78 % good. LogisticRegression does this by itself when
Part 4
We have probabilities and alarms. How good are they, and which mistakes do they make?
The accuracy is the share of days classified correctly; the error rate, used for k-nearest neighbours, is the rest.
With a rare positive class, both are dominated by the easy majority. A model that never raises an alarm scores 90.4 %. A model that catches every bad day but also raises a few false alarms can score lower.
We need to count the two kinds of mistake separately.
This table is the confusion matrix. confusion_matrix in scikit-learn prints it with the true class in rows, in the order 0 then 1: the first row is the normal days, the second the bad days.
Each dot is one test day, placed at the probability the model gave it. Top: the 24 bad days. Bottom: the 226 normal days.
At
The two-feature model of the script, with
Accuracy adds the diagonal, TP and TN. The bad-day row is where the model fails.
TP: true positives (bad days caught). TN: true negatives (quiet normal days). FN: false negatives (missed bad days). FP: false positives (false alarms).
At
TP: true positives (bad days caught). FN: false negatives (missed bad days). FP: false positives (false alarms).
The data cannot tell you the price of a mistake. The situation can.
If a miss costs several times a false alarm, a rule that catches more bad days, at the price of more alarms, is better, even if its accuracy is lower.
The threshold is a business decision. 0.5 is a habit, not a rule.
The script, line 16. Its confusion matrix (line 19), in scikit-learn's layout:
TN: true negatives (quiet normal days). FP: false positives (false alarms). FN: false negatives (missed bad days). TP: true positives (bad days caught).
For a risk manager this rule is much more useful, and the accuracy says the opposite.
Choosing the threshold means choosing a point on these curves, with the costs of the two mistakes in mind.
To compare models, not thresholds, we need a summary over all thresholds at once.
For every threshold, plot the share of bad days caught (TPR, true positive rate: the recall) against the share of normal days with an alarm (FPR, false positive rate).
The closer to the top left, the better the model separates the classes.
TP: true positives (bad days caught). FN: false negatives (missed bad days). FP: false positives (false alarms). TN: true negatives (quiet normal days).
The area under the ROC curve (AUC; ROC: receiver operating characteristic) has a direct meaning: pick one bad day and one normal day at random. AUC is the probability that the model gave the bad day the higher probability.
AUC judges the ranking of days; the threshold is chosen afterwards. That makes it the fair number for comparing methods, and we use it from now on.
Nothing in Part 4 needs a library.
24 × 226 pairs, two for loops (session 3). Same answer as roc_auc_score: 0.861. The library is only faster.
Precision, recall and classification_report prints them, with three averages:
With a rare class that matters, read its own row. If you need one number, use the macro average.
| question | measure |
|---|---|
| how often is it right? | accuracy (misleading if a class is rare) |
| of the real events, how many were caught? | recall, TPR: true positive rate |
| of the alarms, how many were real? | precision |
| one number from precision and recall | |
| how often is a normal day flagged? | FPR: false positive rate |
| does it rank events above non-events? | AUC: area under the curve of caught vs false alarms |
| one number over classes | macro average |
Always report the base rate too: 43.8 % precision is poor if half the days are bad, useful if one in ten is.
Part 5
Can we learn rules a person can read and check?
The risk committee asks for something neither model gives: a rule they can read and check.
What the committee wants looks like this: "Raise the alarm when VOO falls more than ⋯ %, unless ⋯".
Can we learn such rules from the data, and choose the cut-offs automatically?
DecisionTreeClassifier with at most two questions in a row (line 12). Its rules, as text:
The weights are [normal, bad] days in the training years. A tree is a set of rules you can read aloud, and check.
Each box is a group of training days. The top box holds all 999; each question sends a day left (yes) or right (no).
How did the tree choose these questions, and these cut-offs? It measures how much each question reduces the mixing.
Claude Shannon's measure of uncertainty (1948), named after Boltzmann's entropy in physics.
1 Logarithm to base 2, so the unit is the bit: the information in one fair yes/no answer.
Ask "is VOO below −0.36 %?". It splits the 999 training days in two groups:
The entropy after the question is the average of the two, weighted by group size. This is the conditional entropy.
1 The drop is the information gain: 0.119 bits. The tree asks the question with the largest gain.
The function entropy (lines 4–8) is the formula of two slides back. Lines 18–25 try four cut-offs for VOO and compute the gain of each.
The real tree tries every cut-off between two observed values, for every feature, and keeps the best.
Numerical features are split by a cut-off, as above. Categories, like the weekday, are split by one-hot columns (session 9): "is it a Monday?" is a yes-or-no question like any other.
Trees need no scaling: a cut-off works the same in % or in basis points.
best_split (lines 9–20) is step 2 of the recipe: try every cut-off, keep the one with the largest information gain.
Then grow: ask the best question of all training days (line 28), and again inside each of the two groups (lines 31–32). The three cut-offs, −0.359, −2.067 and −0.079, are exactly those of scikit-learn's depth-2 tree.
Deeper trees repeat the same step inside every new group, until a stopping rule.
Every question cuts the plane along one axis, so a tree's regions are boxes.
What does that do on the test year?
Six trees, judged by AUC (area under the curve of bad days caught against false alarms) on the training years and on the test year.
The unlimited tree memorised the four training years, noise included. Session 9's overfitting, a third time today: the degree of a polynomial,
| strengths | weaknesses |
|---|---|
| rules you can read and check | a small change in the data can change the whole tree |
| no scaling needed | overfit easily: depth must be limited |
| numbers and categories alike | boxes only, so diagonal boundaries need many cuts |
The best single tree here (depth 5, area under the curve, AUC, 0.815) is clearly behind logistic regression (0.861). The first weakness, instability, is also the key to fixing the second.
Part 6
Deep trees memorise the past. Can we keep their flexibility without their instability?
The trees of Part 5 face the trade-off of session 9 head-on:
Limiting the depth trades one problem for the other. Is there a way to keep the flexibility of deep trees and remove their instability?
AUC: area under the curve of bad days caught against false alarms.
Ask
1 If those errors are independent, their average has variance
Left: a random forest's test AUC (area under the curve) as trees are added: 0.80 with one tree, 0.86 with 300.
The catch: models trained on the same data make the same mistakes. To profit, the members must be different: the next slide shows how.
Bagging ("bootstrap aggregating"): build each tree on a bootstrap sample: 999 days drawn from the training years with replacement. Some days appear twice, some not at all.
Left: three depth-6 trees, each on its own bootstrap sample. Same method, slightly different pasts, visibly different boxes.
Random forest: bagging, plus a random subset of features at every split, for even more different trees. Then all trees vote, or average their probabilities.
One loop (lines 16–24), one tree per round:
random, now numpy's).Line 25: divide by 100, the average vote. One tree on its own: AUC (area under the curve) 0.567. A hundred, averaged: 0.823.
A random forest adds one line inside the tree: at each split, only a random subset of features may be used.
Three models in a dictionary (lines 14–22, session 5), each fitted and judged on the test year in the same loop.
The same kind of overfitted tree, averaged a few hundred times, becomes one of the best models of the day.
The forest has lost the readable rules of a single tree. That is the price: accuracy against explanation.
Bagging trains its trees side by side and averages them. Boosting trains them one after another:
AdaBoost was the first such method; gradient boosting (XGBoost, LightGBM) is the most used today, and wins many prediction competitions on tables of data. Same idea as gradient descent: each new tree takes a small step that reduces the remaining error.
Part 7
Four methods. Which one goes to the risk manager?
Four methods, each with its own idea, each with numbers that look good. Which one should the risk manager use?
A fair comparison needs the same of everything:
| model | AUC | caught | false |
|---|---|---|---|
| logistic | 0.861 | 14 | 18 |
| kNN, |
0.865 | 14 | 19 |
| tree, depth 5 | 0.815 | 14 | 16 |
| forest | 0.864 | 16 | 23 |
Caught and false alarms at
Three tie: the boundary is nearly straight. Occam's razor (session 9): take logistic regression.
kNN: k-nearest neighbours. AUC: area under the curve of bad days caught against false alarms.
A classmate wants to predict tomorrow's bad day from today's market, to hedge in advance. Same method, trained on four years, judged on the test year: AUC (area under the curve of bad days caught against false alarms) 0.858.
Is this a money machine? What is wrong?
Their line 9 read returns["VOO"].shift(-1): shifted the wrong way.
Their model saw the market of the very day it predicted. With today's return, the AUC (area under the curve of bad days caught against false alarms) is 0.623: close to a coin. In make_history.py the days are independent, so today says nothing about tomorrow.
This is leakage: information that would not exist at the moment of prediction. A test year cannot catch it.
The script from the start of the session:
TP, FN, FP: true positives, false negatives, false positives
Next session: learning without labels: clustering and principal components.
GENERATED from slides.src.md by tools/codewalk/build.py. Edit the source, not this file.