RSM338: Applications of Machine Learning in Finance Winter 2027
Author
Kevin Mott
1 Introduction
Suppose you’re choosing stocks to compare with Microsoft in a risk report. Its sector gives you a list of companies in related businesses. Would that be the same list you’d get by looking at how the stocks trade? Think about Duke Energy. Its business is very different from Microsoft’s. We can use their returns to ask whether their prices behave differently as well.
In Lecture 2 we could compare a fitted return with Apple’s observed return on the same day. Here there is no column with the right peer group for each stock. We have measurements and want to see which stocks resemble one another. Looking for structure in the measurements is unsupervised learning. In this chapter we’ll use clustering, which groups observations by similarity. As we’ll see, deciding what counts as similar is part of the work.
We’ll first fit groups of stocks and compare them with the known sectors. Then we’ll turn to a global investment team choosing country peers for a risk review. This time we have four indicators and no supplied peer list. The way we measure a gap, the number of groups we use, and the algorithm all matter.
2 Can Stock Behaviour Recover Sectors?
2.1 Build one row per stock
The price file contains 1,003 U.S. trading dates from January 3, 2022 through December 31, 2025. The columns are daily U.S. dollar prices adjusted for splits and distributions. We have 18 stocks and SPY, an ETF tracking the S&P 500. SPY gives us the market return for each date. Taking changes leaves 1,002 daily returns.
The price file has a row for each date, but we’re choosing peers for a stock. We need a way to give each stock one row of its own. Use the daily returns to answer three questions about each stock. How much did it earn on average? How much did its return vary? How much did it move with the market? Those three measurements will be its features.
For the first two, start with the mean and sample volatility from Lecture 1. Multiply the daily mean by 252, the conventional number of trading days in a year, for an annualized arithmetic average. Multiply daily volatility by \(\sqrt{252}\), the usual annualization when daily variances add. For the third, use the slope from Lecture 2. In a regression with an intercept, the slope is the stock’s covariance with SPY divided by SPY’s variance. returns.cov()['SPY'] gives us the covariance of each stock with SPY in one column.
The price file uses a different period and market series from Lecture 2. Apple’s beta is now 1.22. Microsoft’s 1.14 means an increase of one percentage point in SPY’s daily return goes with an increase of 1.14 percentage points in the fitted Microsoft return. Duke’s beta is 0.24. A comparison based on beta alone would put them far apart. Their volatilities tell a less tidy story. Microsoft is near Apple in daily price risk on the annual scale, and NextEra Energy, a utility, is near both.
2.2 Fit two groups and open the labels
Beta and volatility suggest different peers. Can we compare all three features together? Start with two groups because we have stocks from two sectors. We need a way to describe each group and decide which stocks belong to it. K-means uses the group’s mean feature row as its representative and puts each stock with its nearest representative. A beta of 1.14 and a volatility of 26.78% use different units. StandardScaler lets us compare gaps in standard deviations from each feature’s mean. We’ll see what that choice does when we fit the country data.
fit_predict estimates the representative rows and gives one group assignment per stock. The model tries 20 starting arrangements and retains the fit with the lowest total squared distance. The seed lets us reproduce the starts. Group numbers 0 and 1 are names. Swapping those names leaves the partition, or division into groups, intact.
Now open the sector labels. We selected ten Utilities stocks and eight Information Technology stocks. Use a cross-tabulation to count the stocks in each combination of known sector and fitted group. Which Information Technology stocks got the same group as the utilities?
All ten utilities land in group 0, with Microsoft, Apple, Adobe and Salesforce. Nvidia, Broadcom, AMD and ServiceNow form group 1. The sector comparison gives us a way to start interpreting the groups after the fit.
Beta and volatility. The circled MSFT has the same coordinates in both panels.
Find Microsoft at about 1.14 beta and 26.78% volatility. The left panel gives its sector. The right gives its fitted group. Then look at the same stock in the other two feature pairs. Nvidia and Broadcom are well above Microsoft on average return. Nvidia and AMD also have more than twice Microsoft’s annualized volatility in this window.
Beta and annualized arithmetic mean return by sector and fitted group.
Volatility and annualized arithmetic mean return by sector and fitted group.
Each figure shows two of the three features. K-means used all three at once. This is an in-sample comparison for a deliberately selected list of stocks, so it describes those stocks and dates. Whether utilities are useful Microsoft peers depends on what you want to compare. A beta comparison might point toward Apple. A comparison of realized volatility could also include NextEra. To decide whether adding a stock would diversify a portfolio, we’d need to know how its returns move with the other holdings.
3 Group Countries by Investment Risk
The sector labels gave us something familiar to compare with the stock groups. The country-risk team from Lecture 2 doesn’t have an existing peer list, so it will need to explain the choices from the indicators themselves. Suppose the team is reviewing Chile. Would you compare it with Canada or Uruguay? A growth analyst might begin with their GDP growth rates. A fund concerned about protecting invested capital might also look at the strength of property rights.
The course snapshot has 122 countries and no missing values in the four indicators. It gives no reference year. Country and abbreviation identify each row. The features have different scales and directions.
Feature
Meaning
Corruption
Corruption Perceptions Index, 0 to 100. Higher means a cleaner public sector.
Peace
Global Peace Index, 1 to 5. Lower means more peaceful.
Legal
Property-rights measure, 0 to 10. Higher means stronger protections.
GDP Growth
Annual GDP growth in percent. Negative means contraction.
GDP growth is similar for all three. Chile’s property-rights score is closer to Uruguay’s, and its Peace score is closer to Uruguay’s too. Looking at just one indicator can hide differences elsewhere. Write country \(i\) as a feature vector\(\mathbf x_i=(x_{i1},x_{i2},x_{i3},x_{i4})\). The first subscript identifies the country. The second identifies the indicator, so \(x_{i2}\) is its Peace score. Stack these rows into a \(122\times4\) matrix \(X\).
To see which indicators tend to move together, look at the scatterplot matrix. Read the horizontal indicator from the column and the vertical indicator from the row. The diagonal shows each indicator’s distribution. The Corruption column and Legal row show a strong upward pattern, with a correlation of \(+0.92\). Cleaner public sectors tend to have stronger property-rights scores. GDP growth varies much more independently, and some countries have unusually low readings.
The four country indicators plotted against each other.
risk.corr().round(2)
Corruption
Peace
Legal
GDP Growth
Corruption
1.00
-0.70
0.92
0.10
Peace
-0.70
1.00
-0.65
-0.20
Legal
0.92
-0.65
1.00
0.12
GDP Growth
0.10
-0.20
0.12
1.00
We want to go from comparing one indicator at a time to making one comparison across all four. What would happen if we just used the differences as printed? In these data Corruption runs from 14 to 90. Peace runs from 1.19 to 3.40. A gap that matters on one scale may look small on another. Let’s see that with Canada and Chile before choosing a scale for the fit.
4 Put the Indicators on a Common Scale
4.1 What should count as a large gap?
Subtract Chile’s row from Canada’s. To combine the four gaps, square them so opposite signs don’t cancel and add the squares. This works like adding the squared gaps in Lecture 2, except that here the four gaps come from different measurements of the same two countries.
The corruption-score gap is 16, which puts 256 into the sum. The peace-score gap is about \(-0.25\), which adds just 0.06. Nearly all of the total, 257.65, comes from Corruption. Would the investment team want that indicator to count for so much just because it uses a wider scale?
4.2 Give the indicators a common unit
We can ask how large each difference is relative to the spread of its own indicator. Standardization does this by subtracting the column mean \(\bar x_j\) and dividing by the column standard deviation \(s_j\). Here \(i\) identifies a country and \(j\) its indicator.
\[z_{ij}=\frac{x_{ij}-\bar x_j}{s_j}.\]
For Corruption the fitted mean is 46.24 and the standard deviation is 19.05. Chile’s 66 becomes \((66-46.24)/19.05\approx1.04\), or about one standard deviation above the sample mean. A positive Peace score after standardizing still means less peaceful than average. Changing a feature’s unit preserves its direction.
fit_transform measures the spreads across the 122 countries and produces the standardized table, risk_z. Use the same scaler to transform the two rows we picked. Their gaps are now comparable in units of standard deviations.
The Legal and Corruption gaps now make similar contributions. Peace contributes too. The four standardized squared gaps add to about 1.73. We have addressed the difference in units. There is still a choice about what to measure. Corruption perceptions and property rights are strongly correlated in this sample, so including both gives related institutional information more influence.
4.3 Do the peers change?
Let’s fit three groups on the raw indicators and three on the standardized indicators. Keep the same countries, features, group count and initialization settings. The cross-tab shows where the memberships move.
Corruption and Legal. Canada and Chile join the same group after scaling.
Follow Canada and Chile in both panels. Their coordinates stay the same because the panels use the original units. The raw fit puts Canada and Uruguay in group 1 and Chile in group 2. On the common scale all three end up together. Each fit uses all four indicators, so the two displayed axes give us part of the explanation. The other five pairs are in the appendix.
4.4 Measuring similarity with distance
We’ve compared two countries by adding their squared gaps. What does that number measure? On the two axes below, walk from Chile to Canada. The horizontal leg is about 0.84 standard deviations on Corruption. The vertical leg is about 0.85 on Legal. The straight line between them is their Euclidean distance on these two features. Pythagoras gives \(\sqrt{0.84^2+0.85^2}\approx1.19\).
The horizontal and vertical gaps form the legs of the distance triangle.
With \(p\) features, subtract each corresponding pair of entries, square the differences, add and take the square root.
Here \(i\) and \(j\) identify countries and \(q\) identifies the feature. The four-feature distance between Canada and Chile is about \(\sqrt{1.73}=1.32\). K-means can compare the squared distances directly because the smallest distance also has the smallest square. Now we can use the same comparison to ask which group’s representative is closest to Chile.
5 How K-Means Finds the Groups
5.1 One distance, then all the distances
We’ve seen that putting indicators on a common scale changes who counts as a peer. What did K-means compare to make that assignment? It gives each group one representative row, the mean of its members on each feature. This is the group’s centroid, written \(\boldsymbol\mu_k\) (mu) for group \(k\). Its entries use the same units as the input features, so we can compare it to Chile using the same four squared gaps we used for Canada.
Calculate the four squared gaps from Chile to each fitted centre and add them. The resulting squared distances to groups 0, 1 and 2 are 14.98, 0.23 and 5.57. Chile goes to group 1. Taking the column means of all 38 countries assigned there gives the fitted centre \((1.25,-0.99,1.20,0.01)\), displayed in standardized units.
chile_z = country_scaler.transform(risk.loc[['Chile']])[0]costs = []for centre in country_model.cluster_centers_: gaps = chile_z - centre costs.append((gaps **2).sum())pd.DataFrame({'Squared distance from Chile': costs}).rename_axis('Group').round(2)
Squared distance from Chile
Group
0
14.98
1
0.23
2
5.57
Chile contributes 0.23 to the fit’s within-cluster sum of squares (WCSS). Canada’s contribution is about 0.94. Every country contributes its squared distance to its assigned centre. Let \(g_i\) denote country \(i\)’s group and \(\mu_{g_i j}\) be the centre’s coordinate for its \(j\)th feature. Then
The inner sum adds one country’s squared gaps across the features. The outer sum adds the country scores. This is a squared-gap calculation like Apple’s training loss. Here we compare each row to the centre that represents it. cluster_centers_[labels_] lines up one centre row with each country. sum(axis=1) adds across the four features. Then add the country scores and compare with inertia_, the fit’s name for WCSS.
Country
Canada 0.94
Chile 0.23
dtype: float64
Total WCSS: 191.13
Model inertia: 191.13
5.2 Assign, update and repeat
Now we know how to score a grouping. How could we improve one? If we keep the centres fixed, we can move a country to a closer centre. If we keep the memberships fixed, we can move a centre to better represent its members. The next figure shows what happens when we alternate those moves on two standardized features, Corruption and GDP Growth. Start with one centre at Canada and one at Argentina. Crosses mark the centres, and the ring follows Romania. The titles show the WCSS before and after each centre update. All 122 countries count, including points below the visible window.
Four K-means assignment and update steps with Romania marked at the same coordinates.
In step 1 Romania’s squared distances are about 4.26 to the Canada centre and 5.19 to the Argentina centre. It starts in Canada’s group. The first centre update brings WCSS from 335.4 down to 156.2. Now hold the new centres fixed and assign the countries again. Romania’s distances are 1.32 and 1.25, so it moves to the other group. This new assignment reduces WCSS to 153.3 before the next centre update. In step 4 the update leaves the score at 151.3. The two-feature illustration has its own objective values. The team’s main fit used four features and three groups.
In general, K-means takes a feature matrix and a number of groups \(K\) and returns assignments and centroids.
Initialize. Place \(K\) centres in feature space. Each has one coordinate per feature.
Assign. Hold the centres fixed and send each observation to its nearest centre. In notation, \(g_i=\arg\min_g\sum_j(x_{ij}-\mu_{gj})^2\). The argmin gives the group number that attains the smallest distance, just as the argmin in Lecture 2 gave the parameters that attained the smallest loss.
Update. Hold the assignments fixed and replace each centroid by the mean of its member rows. On each feature, the mean minimizes the sum of squared gaps to a constant. This is the same least-squares calculation we used for Apple’s constant benchmark.
Repeat. Alternate until the assignments and centres settle, or until the iteration limit. Each of the two moves can only lower WCSS or leave it unchanged.
Different starting centres can give different final groups. Multiple starts improve our chances of finding a lower WCSS. The lowest score among the starts is the best fit we found. Outliers can pull a mean far from most of its members. K-means works best when distance to a centre describes membership reasonably well, as it does for compact groups. An elongated group can be split even when an analyst would want to keep it together. Lloyd (1982)
6 How Many Groups Should We Use?
We started with three groups so we could see how the fit works. Would the team do better with two or four? The minimum possible WCSS can only fall or stay the same as you allow more groups. With a separate centre for every country, every squared gap is zero. A one-page risk summary would then need 122 profiles. We want enough groups to retain useful differences, so we need to see how much an extra group adds.
The elbow method looks for a bend in a graph of WCSS against \(K\). There is a drop from 488.0 to 268.2 when we add a second group. The third takes it to 191.1, and the fourth to 157.1. The savings start to diminish. Use the same standardized inputs across these fits so a change in WCSS describes a change in grouping.
The silhouette compares a country’s average distance \(a(i)\) to the other members of its own group with its average distance \(b(i)\) to the members of the closest other group. To find that other group, take an average for each other group and choose the smallest. Then
\[s(i)=\frac{b(i)-a(i)}{\max\{a(i),b(i)\}}.\]
A score near \(+1\) says the country is much closer on average to its group. A score near zero says the average distances are similar, and a negative score says another group is closer on average. Average across countries to score the whole partition. The calculation requires at least two groups.
The loop fits one partition for each count. inertia_ gives the WCSS for that fit. silhouette_score uses the same standardized rows and their assigned groups to score separation.
from sklearn.metrics import silhouette_scorecounts =list(range(1, 11))wcss = []silhouettes = []for count in counts: fit = KMeans(n_clusters=count, n_init=20, random_state=338) fit.fit(risk_z) wcss.append(fit.inertia_)if count >=2: silhouettes.append(silhouette_score(risk_z, fit.labels_))fig, (left, right) = plt.subplots(1, 2, figsize=(9, 3.2), layout='constrained')left.plot(counts, wcss, marker='o')left.set(xlabel='Number of groups', ylabel='Within-cluster sum of squares')right.plot(counts[1:], silhouettes, marker='o')right.set(xlabel='Number of groups', ylabel='Mean silhouette')plt.show()
Two ways to compare the number of country groups.
The mean silhouette peaks at two groups, about 0.424, and is about 0.407 for three. The elbow also shows a substantial reduction going from two to three. Two groups are a defensible broad summary. Three can be useful if the team wants to distinguish the group with weak growth from a second group with stronger growth and somewhat better institutional indicators. The scores help explain the tradeoff. The reporting question tells us how much the extra detail is worth. Rousseeuw (1987)
7 Hierarchical Clustering
7.1 How much does a merge cost?
Two groups may work for a short risk report, while three give the team more detail. Suppose it wants to add detail without moving countries between its broad coverage areas. Repeating K-means with a new \(K\) can change those memberships. Hierarchical clustering builds nested groups by recording how they form. In an agglomerative fit we start at the bottom, with one group per country, and merge groups one pair at a time.
Ward’s rule chooses the pair whose merger adds the least to WCSS. Each group uses its own centroid before the merge. The combined group uses one shared centroid afterward. For the proposed groups \(A\) and \(B\), the change is
\(A\cup B\) contains all countries in both groups. The first two countries to merge are the Netherlands and Singapore. Their Corruption scores are 83 and 84, their Legal scores are 8.30 and 8.36, and their GDP growth rates are 2.1% and 2.0%. Their Peace scores both round to 1.54. Before merging, each country is its own centre, so each has a WCSS of zero. The shared centre is their midpoint in the standardized features. Adding the squared distances to it gives about 0.0028.
from scipy.cluster.hierarchy import linkage, cut_treemerges = linkage(risk_z, method='ward')first_pair = merges[0, :2].astype(int)pair_rows = risk_z[first_pair]midpoint = pair_rows.mean(axis=0)print('WCSS added by the first merge:', round(((pair_rows - midpoint) **2).sum(), 4))risk.iloc[first_pair].round(2)
WCSS added by the first merge: 0.0028
Corruption
Peace
Legal
GDP Growth
Country
Netherlands
83
1.54
8.30
2.1
Singapore
84
1.54
8.36
2.0
At the next step the Netherlands–Singapore group can be compared with other groups. Score the candidate pairs, merge the pair with the smallest increase and record the join. Continue until all countries are in one group. This gives 121 merges. Earlier merges carry through to coarser levels. Single, complete and average linkage instead use the smallest, largest or average distance across pairs of members from the two groups. Those criteria can give a different tree. Ward (1963)
7.2 Read and cut the tree
A dendrogram shows the join history from bottom to top. The figure abbreviates the lower levels to make the major branches readable. An abbreviation names one country. A count in parentheses gives the number of countries under that branch. Higher joins on this Ward tree mean a costlier increase in WCSS. The plotted height is a distance scale, equal to \(\sqrt{2\Delta}\) for SciPy’s Ward linkage on these Euclidean inputs.
Ward’s tree with a horizontal cut just above height 11.
The height of the merge leaving three groups is about 9.92. The next merge is at 12.17. A cut halfway between them, about 11.05, crosses three vertical branches. Raising the cut above 12.17 joins two branches and leaves two groups. A large vertical gap tells you how far you can move the cut before the membership changes again.
Compare memberships by following the rows. Every member of K-means group 1 stays together in Ward group 2, which gains another 15 countries. K-means group 2 is spread across all three Ward groups. Find Canada and Chile in the next figure. They remain peers in both fits, though the rest of their group changes. Both algorithms used the same standardized inputs. Ward makes a sequence of least-cost joins. K-means can reassign a country as its centres move. The different search procedures can produce different peer lists.
Three groups from each method on the same Corruption and GDP Growth axes.
8 What Should the Investment Team Take Away?
Come back to the decision for Chile. Canada’s higher property-rights score would make it an informative comparison for institutional conditions. Uruguay is closer on both Legal and Corruption. All three are in the standardized K-means group with the strongest average institutional readings. If the fund’s immediate question is which country looks more like Chile on those particular indicators, Uruguay provides one defensible peer. The group gives a starting list, and the underlying rows explain what individual comparisons mean.
The profiles are group means in the original units. A fund concerned primarily with capital protection would put group 1 ahead of group 2 because it has stronger institutional readings and greater peacefulness on average. Group 2 has the highest growth. An analyst focused on near-term growth might give that column more weight. Group 0 has both a weaker institutional profile and negative average growth. The group numbers themselves have no risk order.
The snapshot has no dated currency, liquidity or portfolio exposure information. A high growth rate can reflect recovery from a low base. For a diversification decision, check current country information and how the returns of the actual exposures move together. The model has answered a narrower question about similarities across four measured indicators.
9 Summary
Clustering starts with a choice of features and a definition of distance. In the country data, standardizing changes what counts as a large gap. Read the resulting groups in original units so the team can put a financial interpretation on them.
Method
Model or output
Loss or criterion
Learning algorithm
K-means
\(K\) groups, each with a centroid
Total squared distance to the assigned centres
Assign to the nearest centre and update each centre to its members’ mean. Repeat from several starts.
Agglomerative clustering with Ward linkage
A nested tree of groups
Increase in WCSS at each merge
Start with single observations. Repeatedly merge the pair that adds the least WCSS.
K-means gives a compact summary when you have a useful group count and centroids make good representatives. Elbow and silhouette plots help you choose the count. A Ward tree helps you examine several levels of coverage, at the cost of scoring pairs of groups and carrying early merges forward. Use the membership comparison to see which peers are robust to that choice and which depend on how you built the groups.
10 Appendix: Other Views of the Country Groups
The points below stay in their original units. The panels colour them by the fit on the raw features and by the fit on standardized features. In both cases the fit uses all four indicators. Follow Canada and Chile from one pair of axes to the next.
Corruption and Peace.
Corruption and GDP Growth.
Peace and Legal.
Peace and GDP Growth.
Legal and GDP Growth.
10.1 Data Sources
The frozen stock price file contains Yahoo Finance data obtained through yfinance with adjusted closes. Yahoo Finance and its providers retain rights to their data. The country snapshot is adapted from John C. Hull, Jacky Chen, Zissis Poulos and Jun Yuan, Machine Learning in Business (2025). It uses indicators from Transparency International, the Institute for Economics and Peace, the Property Rights Alliance and the International Monetary Fund.