liveBook · Manning

Distance matrix

As explained in Build a Robo-Advisor with Python (From Scratch)

A distance matrix is a square array whose entries represent pairwise dissimilarities between objects.

A distance matrix is a square table of pairwise dissimilarities. For hierarchical risk parity (HRP), transform an asset correlation matrix R into D with Dᵢⱼ = √[½(1 − Rᵢⱼ)]. An asset’s distance from itself is zero; more highly correlated assets have smaller distances. section 11.2.4

HRP then builds a second matrix, D̄, whose entries are Euclidean distances between columns of D. D̄ measures whether two assets have similar correlation patterns relative to all other assets, rather than merely measuring their direct pairwise correlation. Small values identify candidates for early clustering. section 11.2.4

Eight-asset portfolio

Compute returns for VV, VB, AGG, VEA, BNDX, VWO, EMB, and DJP; derive correlations; then calculate D elementwise as ((1 − corr) / 2) ** .5. Iterate over asset pairs to populate D̄ with vector norms, producing the input used to find close clusters. section 11.2.4

Listing 11.5 Calculating the distance matrix
import itertools

tickers = ['VV', 'VB', 'AGG', 'VEA', 'BNDX', 'VWO', 'EMB', 'DJP']           
rets = yf.download(tickers, start='2014-01-01', end='2021-12-31')['Adj Close']
rets = rets.pct_change().dropna(axis=0, how='any')[tickers]
cov, corr = rets.cov() * 252, rets.corr()

dist = ((1 - corr) / 2.) ** .5

d_bar = dist * 0
for i, j in itertools.permutations(dist.columns, 2):
    d_bar[i][j] = np.linalg.norm(dist[i] - dist[j])

This implementation downloads asset returns, calculates correlation, transforms it into D, and computes D̄ with Euclidean norms. section 11.2.4

How Build a Robo-Advisor with Python (From Scratch) covers it

How deep it goes
Derives two distance matrices and implements both calculations, then defers cluster formation to later steps.
Examples
Uses eight ETF-like tickers and Python calculations of correlations, distances, and pairwise vector norms.
What it assumes
Assumes a correlation matrix of asset returns and teaches the distance transformations from that input.
What you can do after
Build it from scratch by converting return correlations into clustering-ready distance matrices in Python.
How it connects
Connects correlation matrices, Euclidean distance, hierarchical clustering, covariance matrices, and hierarchical risk parity.

Also explained in

Compare how 3 books explain distance matrix →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Robo-Advisor with Python (From Scratch). The section links point to the parts of the book it draws on.