Optimal Number of Clusters
The Optimal Number of Clusters (ONC) algorithm of López de Prado and Lewis (2019) finds the number of clusters itself. Every asset is the point given by its row of the distance matrix; for every number of clusters from 2 to N - 1, k-means runs ten times from k-means++ starts, and the clustering with the highest quality is kept. The clusters of below-average quality are then clustered again on their own, and their new clusters kept when they raise the average quality (López de Prado, 2020, snippets 4.1 and 4.2).
The formula for the Optimal Number of Clusters starts from the silhouette \(S_{i}\) of every asset, with \(a_{i}\) its average distance to the assets of its own cluster and \(b_{i}\) that to the assets of the nearest other cluster:
\[S_{i} = \frac{b_{i} - a_{i}}{\max\left(a_{i}, b_{i}\right)}\]The quality q of a clustering is the mean of the silhouettes over their standard deviation:
\[q = \frac{\operatorname{mean}\left(S\right)}{\operatorname{std}\left(S\right)}\]A silhouette close to 1 means an asset sits well inside its cluster, one below 0 that it lies closer to another cluster. It needs no tree and suits groups of uneven size.
Group the assets into clusters of assets that move together, the clusters that HERC and NCO allocate across.
Clustering groups the assets by how much they move together, on the distance of a codependence (see get_codependence_matrix), so that a portfolio can spread its risk across groups rather than across individual assets that partly duplicate each other. The methods differ in whether they need a number of clusters and in the shape of the groups they find.
Also known as: ONC, k-means clustering, silhouette clustering.
In the Finance Toolkit this is get_asset_clusters with method="onc", the same function as Asset Clusters.
Example · AAPL, MSFT, JNJ, XOM · 2021 to 2025
Install the Finance Toolkit with pip install financetoolkit -U, then call get_asset_clusters:
from financetoolkit import Toolkit
toolkit = Toolkit(
["AAPL", "MSFT", "JNJ", "XOM"],
api_key="FINANCIAL_MODELING_PREP_KEY",
start_date="2021-01-01",
end_date="2025-12-31",
)
toolkit.portfolio.get_asset_clusters(method="onc")
| Parameter | Type | Description | Example |
|---|---|---|---|
method | str | The clustering. Options are: “hierarchical” (Hierarchical Clustering), “ftca” (Fast Threshold Clustering Algorithm), “onc” (Optimal Number of Clusters). Defaults to “hierarchical”. | "hierarchical" |
period | str | The frequency of the returns. Options are: “daily” (daily returns), “weekly” (weekly returns), “monthly” (monthly returns), “quarterly” (quarterly returns), “yearly” (yearly returns). Defaults to “daily”. | "weekly" |
codependence | str | The codependence the assets are clustered on (see get_codependence_matrix). Options are: “pearson” (the linear correlation of the covariance matrix), “spearman” (the rank correlation of the returns, Spearman, 1904), “kendall” (the rank correlation \(\tau_{b}\) of the returns, Kendall, 1938), “gerber” (co-movements beyond half a standard deviation, Gerber et al., 2022), “detoned” (the correlation without the market component, López de Prado, 2020), “distance” (the distance correlation, Székely et al., 2007, through √(1 - dCor)), “mutual_information” (through the variation of information, Meilă, 2007), “lower_tail” (how often two assets fall into their lowest 5% of returns together, through -ln \(\lambda\)), “absolute_angular” (\(\vert \rho \vert\) through \(\sqrt{1 - \vert \rho \vert}\), López de Prado, 2020), “squared_angular” (\(\rho^{2}\) through \(\sqrt{1 - \rho^{2}}\), López de Prado, 2020), “gnpr” (the rank co-movement and the difference between the return distributions, \(\theta = 0.5\), Marti et al., 2016). Defaults to “pearson”. | "pearson" |
covariance | str | The covariance estimator whose correlation the Pearson codependence is. Options are: “sample” (sample covariance), “ledoit_wolf” (Ledoit-Wolf), “ledoit_wolf_constant_correlation” (Ledoit-Wolf constant correlation), “ledoit_wolf_single_factor” (Ledoit-Wolf single factor), “oas” (Oracle Approximating Shrinkage), “shrunk” (fixed shrinkage), “semicovariance” (semicovariance), “exponential” (exponentially weighted), “denoised” (denoised, constant residual eigenvalue), “denoised_spectral” (denoised, spectral), “denoised_shrink” (denoised, targeted shrinkage), “gerber” (Gerber), “factor” (factor model), “minimum_covariance_determinant” (Minimum Covariance Determinant), “jlogo” (j-LoGo), “geodesic” (geodesic shrinkage), “regime_adjusted_ew” (regime adjusted exponentially weighted), “nercome” (NERCOME), “ccc_garch” (CCC-GARCH), “mm” (MM-estimator), “rocke” (Rocke’s S-estimator). Defaults to “sample”. | "sample" |
linkage_method | str | The linkage of the hierarchical clustering. Options are: “single” (single linkage), “complete” (complete linkage), “average” (average linkage), “ward” (Ward’s method), “dbht” (the Directed Bubble Hierarchical Tree of Song, Di Matteo and Aste, 2012, which finds the number of clusters itself in the TMFG planar graph of the codependence). Defaults to “ward”. | "ward" |
clusters | int | None | The number of clusters of the hierarchical clustering, or the most clusters ONC tries. Defaults to None, chosen by the two-order difference of the gap statistic (by the DBHT itself for its linkage; up to N - 1 for ONC). | None, chosen by the two-order difference of the gap statistic (by the DBHT itself for its linkage; up to N - 1 for ONC) |
cluster_criterion | str | How the hierarchical clustering chooses the number of clusters when it is not given. Options are: “two_difference_gap” (the two-order difference of the gap statistic), “standardized_silhouette” (the highest mean over standard deviation of the silhouette coefficients). Defaults to “two_difference_gap”. | "two_difference_gap" |
threshold | float | The codependence above which FTCA puts assets in one cluster. Defaults to 0.5. | 0.5 |
seed | int | None | The seed of the k-means starts of ONC (numpy’s default generator), so the same returns give the same clusters. Defaults to 0. | 42 |
include_benchmark | bool | Whether to include the benchmark as an asset. Defaults to False. | True |
show_columns | str | list[str] | None | The columns to keep, a name or a list of names, matched on every column level, or the rows when no column has those names (such as the line items of a financial statement). Names that do not exist are logged, and when none exist the result is returned in full. Defaults to None, which keeps every column. | None, which keeps every column |
Which returns:
| Item | Cluster |
|---|---|
| AAPL | 1 |
| MSFT | 1 |
| JNJ | 2 |
| XOM | 2 |
References
- Paper López de Prado, M. and Lewis, M. J. (2019). “Detection of False Investment Strategies Using Unsupervised Learning Methods.” Quantitative Finance, 19(9), 1555-1565.
- Paper López de Prado, M. (2020). “Machine Learning for Asset Managers.” Cambridge University Press.
- Library Shares similar logic as RiskLabAI’s cluster_k_means_top (Optimal Number of Clusters, López de Prado, Machine Learning for Asset Managers, snippet 4.2)