| ticker | shares | price | value |
|---|---|---|---|
| AAPL | 10 | 190.50 | 1905.00 |
| NESN | 4 | 102.30 | 409.20 |
| VOO | 2 | 512.00 | 1024.00 |
Apple is 57 % of the ledger. The risk manager asks: is this portfolio diversified? Which stocks move together, and which do not?
No file says "these stocks belong together". There is nothing to predict, only 1249 days of returns. Finding structure without answers is unsupervised learning.
Parts 3 to 7 find groups of stocks. Part 8 finds the few hidden factors that move all of them.
DBSCAN: density-based spatial clustering of applications with noise.
universe.csvDaily returns, in %, of 34 large stocks and VOO, 2022-01-18 to 2026-10-30:
make_universe.py, fixed seed). AAPL, MSFT and NESN keep their betas of session 9.Simulated data have one advantage today: we know the true sectors, and can check whether a method finds them, without telling it.
Two minutes, on your own.
Five groups of stocks, found without being told any sector.
Is that a mistake? What exactly did the method group by, and how would we know whether a grouping is any good? This session answers both.
Part 1
No one gives us the answers. What can we still learn from the data?
Left: each point has its class, as the bad days did. Right: no classes; the eye still sees three groups. Can an algorithm?
| supervised | unsupervised | |
|---|---|---|
| data | features |
features |
| goal | predict |
find structure in |
| judged by | error on a test set | harder: no answers to compare with |
Groups: clustering. Split the cases into groups: alike inside a group, different across groups (left).
Few hidden factors: dimension reduction. Many columns often move because of a few common causes. Find them, and describe each case with fewer numbers (right: two columns, one direction).
Parts 3 to 7 cluster; Part 8 reduces dimensions.
The next three slides look at the first three. The fourth, outliers, comes back in Part 7.
300 customers (simulated), each described by how often they come and how much they spend per month.
This is the typical use of clustering: describe a population by a few types.
150 real iris flowers, measured in 1936 (load_iris in scikit-learn): four lengths in cm per flower.
The small flowers at the bottom left are one species, cleanly found. The other two species overlap, and no method separates them perfectly from these measurements alone. Groups found without labels are only as clear as the data allow.
The 1797 handwritten digits of session 10, each 64 pixel values, squeezed to two numbers by principal components (Part 8). The colours and labels are added afterwards, for us.
Dimension reduction lets you look at data with many columns, and gives later models fewer, more informative inputs.
In sessions 9 and 10, every model was judged against the truth on a test year. Without labels there is no truth to compare with. Three replacements, used today:
And because our stocks are simulated, we also have what real life never gives: the true sectors, to check against at the end.
Part 2
Before grouping stocks, we must say when two stocks are alike.
Every clustering method groups "similar" cases. But a stock is 1249 returns: in which sense are two stocks similar?
These are different questions, and they give different groups. Parts 3 to 5 use the risk profile; Part 6 uses the movements.
Choosing the features is choosing what "similar" means. No algorithm makes that choice for you.
Lines 9–13 of the script.
Apple: beta 1.28, volatility 1.63 %. Nestlé: 0.56 and 0.88 %.
Even without colours, the eye sees groups: low and calm at the bottom left, a band of high-beta stocks on the right, a volatile group at the top.
Line 15 of the script. Beta and volatility are on different scales. A distance in the raw plane would weigh them by their units, not by how much they vary.
After standardising, each feature has mean 0 and standard deviation 1. Apple is 1.56 standard deviations above the average beta, 0.87 above the average volatility.
From here on, "distance between two stocks" means the Euclidean distance of session 10, in these standardised units.
Part 3
Put the stocks into k groups, each around a centre. Where should the centres go?
We want to split the 33 stocks into
We need: a number that says how good a split is, and a procedure that makes it small. The recipe of sessions 9 and 10, without the answers.
Give each group a centre, a point in the plane. 1 Each stock is measured against the centre of its own group.
Smallest
Repeat 1 and 2 until no stock changes group.
Choosing groups and centres together is hard. Each alone is easy:
1 If the centres are fixed, the best group for each stock is its nearest centre.
2 If the groups are fixed, the best centre of each group is its mean: the point with the smallest sum of squared distances (session 9: least squares gives the mean).
k-means alternates the two, from random starting centres. This is Lloyd's algorithm (1957).
The crosses are the centres; each stock takes the colour of its nearest one.
The whole method is lines 13–18.
Lines 15–21 of the script, with scikit-learn's KMeans:
Not a bug: in the plane of beta and volatility, Microsoft is closer to the banks. k-means answered the question we asked, "same risk profile", not "same business". Part 6 asks the other question.
The customers of Part 1, standardised,
Each centre is a typical customer of its group: a summary a marketing team can act on, one offer per type. The names are ours; k-means only gives the groups.
k-means always stops at a split that no single step can improve. That split need not be the best one.
The remedy is simple: run it many times from different starts and keep the smallest n_init=10 on line 16 of the script.
The measures point to a range, not a number. In practice
| strengths | weaknesses |
|---|---|
| simple, fast, millions of points | you must choose |
| easy to explain: "nearest centre" | different starts, different answers |
| centres summarise each group | groups are round, of similar size |
| every stock must join a group, outliers too |
The last weakness is why GME is set aside on line 7. With it, k-means spends a whole group on a single stock. Part 7 handles outliers properly.
Part 4
Is a grouping good? Without labels, what can we measure?
Part 1 named three ways to judge without answers: internal measures, stability, meaning. Stability we met in Part 3 (restarts). This part makes the internal measures precise.
We need a measure that combines both, for each stock and for the whole grouping.
For each stock, compare how close it is to its own group with how close it is to the next best group.
The average silhouette over all stocks judges the whole grouping: 0.66 for the five groups of k-means. Above about 0.5 is usually read as a clear structure.
Our stocks are simulated, so we can check once, after the fact. Rows: the five groups; columns: the true sectors.
31 of 33 stocks (94 %) are in a group dominated by their own sector: the purity.
Misplaced: Microsoft (a bank's risk profile) and Visa (with tech). In beta and volatility they do look like those groups: the features limit what can be found.
Internal measures say groups are clear; only meaning says what they are.
Part 5
Microsoft sits between two groups. Can a stock belong partly to both?
Take one feature, volatility. The ticks at the bottom are the 33 stocks.
k-means gives a hard answer: Microsoft is in exactly one group. Often we want a soft one: "probably volatile, possibly middle". A probability for each group, like the classifiers of session 10, but without labels.
Imagine each stock was made in two steps: first its group is drawn, then its volatility, from that group's bell curve.
1
2 Group
The data's density is the weighted sum: a Gaussian mixture model (GMM). Unlike k-means, this is a model of the data, so it has a likelihood (session 9).
GMM: Gaussian mixture model. Gaussian: normal.
1 The probability that stock
Numerator: how likely group
If we knew the groups' parameters, memberships would be one line of arithmetic. But the parameters are what we want to learn.
Again, two easy problems instead of one hard one:
This is the EM algorithm (1977). Each round can only raise the likelihood, as k-means could only lower
EM: expectation–maximisation. E-step: expectation step. M-step: maximisation step.
Each curve is one group's weighted bell curve; the ticks are the stocks.
EM: expectation–maximisation.
The output: Nestlé and JPMorgan belong to one group with near certainty. Microsoft: 92 % volatile, 8 % middle. A soft answer, which k-means cannot give.
EM: expectation–maximisation.
The classic example. Adult heights mix two groups, women and men, whose bell curves overlap. Nobody recorded who is who: only heights.
Mixtures are used wherever a population is made of hidden types: customers, cells in a blood sample, calm and turbulent market periods.
EM: expectation–maximisation.
| k-means | Gaussian mixture, by EM | |
|---|---|---|
| membership | 0 or 1: nearest centre | a probability for each group |
| group shape | round, all alike | each its own spread (and, in 2D, its own tilt) |
| what it is | a procedure that lowers |
a model of the data, with a likelihood |
| alternates | assign ↔ move centres | E-step ↔ M-step |
Make all spreads equal and tiny: memberships become 0 or 1, the E-step becomes "nearest centre", the M-step "move to the mean". k-means is a limiting case of EM.
The number of groups is still hard to choose: with 33 stocks, the data cannot prove three groups beat one. Meaning decides.
EM: expectation–maximisation.
Part 6
Which stocks move together, and at which level do groups join?
The risk manager's question was about movements: if Apple falls, what else falls with it? Beta and volatility say how much a stock moves, not when.
And how many groups? Instead of fixing
Two stocks that always move together have correlation 1: distance 0. Unrelated stocks: correlation 0, distance 1.
With 34 stocks there are 561 pairs, each with its correlation over 1249 days. No features to choose: the distance comes straight from the returns.
Apple is closest to Microsoft, then to JPMorgan, then Nestlé, then Exxon.
Agglomerative clustering:
The record is a dendrogram. Left, six stocks: Coca-Cola and Nestlé merge first, then Apple and Microsoft, then Nvidia joins them. Cut it at any height: a grouping. One tree, every
Step 2 needs a distance between groups: several definitions exist.
Step 2 asks "which two groups are closest?". We know the distance between two stocks; a group holds several. Three common answers, for the same two groups A and B:
Same groups, three distances. Since step 2 merges the closest pair of groups, the choice changes which groups merge first, and so the whole tree.
Two dense clouds, a thin bridge of points between them, and one point far above.
Single linkage follows chains and finds stragglers; complete linkage finds compact groups. Average sits between them, and is what we use for the stocks.
Read it from the right: every stock starts alone; horizontal position is the distance at which groups join. Tickers are coloured by their true sector, which the method never saw.
Why would Apple and JPMorgan look so close? Both have high betas. On most days, both just follow the market.
Every stock follows the market, so every pair of stocks is correlated. That shared part drowns the smaller sector movements.
1 Subtract each stock's beta times the market's return: what is left are its residuals (session 9), the part of its movement the market does not explain.
Between residuals, Apple and Microsoft are still related; Apple and JPMorgan, Nestlé or Exxon no longer are. What remains is the sector.
The same method on residual correlations.
Cut the tree at the dashed line: six groups, the five sectors and GME. Without being told any sector, the method recovered all of them, once the right question ("what moves together beyond the market?") was asked.
closest_pair tries every pair of groups. D.loc[...] picks the rows of one group and the columns of the other: all their pairs; the mean is average linkage.The number of groups is not chosen: it comes out of the cut. Six, the same as the dendrogram.
Each picture is the 34 × 34 table of residual correlations; darker is higher.
Reordering by a dendrogram is a standard way to show structure in a correlation table, in finance and in genetics alike.
Average the 1797 handwritten digits of each class: ten 8 × 8 images. Cluster them by the distance between their 64 pixels.
The same tool draws family trees of species from their DNA, groups languages by shared words, and organises documents by topic.
Part 7
Density-based clustering (DBSCAN). GME fits nowhere. Can a method say so, instead of forcing it into a group?
GME, the "meme stock", has volatility 4.68 %, about 5.0 standard deviations above the others. It is not part of any group.
We want a method that finds groups as dense regions of points, and calls points in empty regions noise. Without being told how many groups there are.
Choose a radius min_samples.
min_samples points (itself included) within The number of groups is not chosen: it comes out. Groups can have any shape, even long and curved. This is DBSCAN (density-based spatial clustering of applications with noise, 1996).
DBSCAN: density-based spatial clustering of applications with noise.
min_samples = 3,
Dense regions that touch become one group: DBSCAN cannot split the band of tech and banks, which k-means cut in the middle. Each method has its own idea of a group.
DBSCAN: density-based spatial clustering of applications with noise.
Three values of min_samples:
DBSCAN trades the choice of
DBSCAN: density-based spatial clustering of applications with noise.
403 card payments, each described by its amount and its distance from home, standardised. Three of them are planted frauds, far from the rest.
DBSCAN with min_samples = 5 finds one dense group, the normal payments, and flags 5 points as noise: the 3 frauds, and 2 genuine but unusual payments.
That is how unsupervised fraud screening works: no list of past frauds, just "unlike everything else". A person then checks the few flagged cases.
DBSCAN: density-based spatial clustering of applications with noise.
| k-means | Gaussian mixture | hierarchical | DBSCAN | |
|---|---|---|---|---|
| you choose | linkage, where to cut | min_samples |
||
| membership | hard | soft: probabilities | hard, at every level | hard, or noise |
| group shape | round | bell-shaped | any | any, follows density |
| outliers | forced into a group | forced, but with low probability | join last | flagged as noise |
| here | risk profiles, 94 % pure | MSFT 92 % volatile | sectors, from movements | GME as noise |
No method is best everywhere: pick the one whose idea of a "group" fits your question.
DBSCAN: density-based spatial clustering of applications with noise.
DBSCAN: density-based spatial clustering of applications with noise; HDBSCAN: its hierarchical version; BIRCH: balanced iterative reducing and clustering using hierarchies.
After scikit-learn's example "Comparing different clustering algorithms on toy datasets" (BSD licence), redrawn with the same data and settings.
Part 8
34 return series. How many things really move them?
What drives the 34 stocks? Their 561 correlations are too many to read.
Principal component analysis (PCA) finds the few directions along which the data vary most.
PCA: principal component analysis.
Each dot is a day: Apple's and Microsoft's returns, standardised. The cloud is long and thin, because the two stocks move together.
That direction is the first principal component (PC1): the direction in which the data spread the most. The second component is at a right angle to it, and carries what is left.
PC1: first principal component.
A direction is a pair of weights
1 Its variance (session 9: variances add, plus twice the covariance) depends on the correlation
PC1, PC2: first and second principal component.
With 34 stocks, the same question: which weights
1 Weights of length 1: otherwise doubling them would inflate the spread for free.
2 The best
np.linalg.eigh computes them in one line.
PC: principal component.
34 standardised stocks have a total variance of 34. Each component carries a part of it, its eigenvalue.
This bar chart is a scree plot, named after the rubble at the foot of a cliff: a steep drop, then flat.
PC1, PC2, PC3: first, second, third principal component.
Left: PC1's weights on the 34 stocks, coloured by sector. All positive, all about the same size (0.12 to 0.21; GME only 0.08). PC1 is close to "the average of all stocks".
Right: PC1 on each day, against VOO's return: correlation 0.937.
PCA was never told about the market. It found it, as the biggest common movement in the data. This is why the raw dendrogram merged tech with banks.
PCA: principal component analysis.
Columns: components. Rows: stocks, coloured by true sector. Red: positive weight, blue: negative.
Each component after the first is a sector factor, found without any sector names.
PC1: first principal component. PC: principal component.
@ is matrix multiplication: every column times every column, summed over days.Same shares as scikit-learn's PCA (line 21).
PCA: principal component analysis. PC1: first principal component.
The first few components carry the common movements. After the sector factors, what is left is each stock's own news, which no common factor explains.
How many depends on the purpose: 5 or 6 to see the structure, many more to rebuild every stock closely.
PC: principal component.
PCA on the 1797 digits: 64 pixels each. Keep
The same idea compresses faces, sounds and survey answers: keep the few directions that carry most of the variation.
PCA: principal component analysis.
A yield curve: the interest rate for each maturity, from 3 months to 30 years. Every day, ten rates move. PCA on their daily changes:
Three numbers a day describe the whole curve; bond desks hedge in these three factors.
PCA: principal component analysis. PC1, PC2, PC3: first, second, third principal component.
PCA looks for the largest variance. Without standardising, the most volatile stocks dominate.
On raw returns, "the main factor" is partly one meme stock. Standardise, unless all columns share a unit and their size is what you mean to study.
PCA: principal component analysis. PC1: first principal component.
Part 9
Is the portfolio diversified, and what would change if it were?
So the ledger holds three things: the market (VOO, and the market part of Apple and Nestlé), tech (Apple), and a little of staples (Nestlé). No energy, no pharma, no banks.
PC1: first principal component.
The ledger's daily return is the value-weighted average of its positions. Its standard deviation: 1.23 % per day.
The groups tell you where to diversify: into the clusters the portfolio does not hold yet.
PC1: first principal component.
A classmate clusters days instead of stocks: each day described by VOO's and Microsoft's returns. k-means with
The report: "The market switches between four regimes: calm, rally, sell-off, and mixed. We should change the portfolio with the regime."
No crash, no warning, four tidy groups. What is wrong?
Right: the same days, uncoloured: one round cloud. No groups to find.
In make_history.py every day is drawn from the same distribution: no regimes exist.
BIC: Bayesian information criterion; lower is better.
PCA: principal component analysis. EM: expectation–maximisation.
The script from the start of the session:
PC1: first principal component. EM: expectation–maximisation.
Next session: neural networks.
PCA: principal component analysis. EM: expectation–maximisation. DBSCAN: density-based spatial clustering of applications with noise.
GENERATED from slides.src.md by tools/codewalk/build.py. Edit the source, not this file.