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

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