Codependence Matrix

Calculate how much every pair of assets moves together.

It is the codependence that the hierarchical optimizers (HRP, HERC, NCO) and get_asset_clusters take as their codependence, or the distance they cluster on.

  • Pearson: the correlation of the covariance estimate, distance \(\sqrt{(1 - \rho) / 2}\).
  • Spearman and Kendall: the rank correlations of the returns, distance \(\sqrt{(1 - \rho) / 2}\).
  • Gerber: the Gerber statistic (see get_covariance_estimate), distance \(\sqrt{(1 - \rho) / 2}\).
  • Detoned: the correlation without its first principal components, distance \(\sqrt{(1 - \rho) / 2}\).
  • Distance correlation: dCor = √(dCov²(x, y) / √(dCov²(x, x) dCov²(y, y))) from the doubly centred distances \(\vert x_{s} - x_{t} \vert\) (Székely, Rizzo and Bakirov, 2007), zero only for independent returns; distance √(1 - dCor).
  • Mutual information: I(X, Y) / min(H(X), H(Y)) from histograms with the given bins (natural logarithms); distance the variation of information (H(X) + H(Y) - 2 I(X, Y)) / H(X, Y) (Meilă, 2007).
  • Lower tail dependence: \(P (r_{j} \leq q_{j} (\alpha) \vert r_{i} \leq q_{i} (\alpha))\); distance -ln \(\lambda\) (λ at least 1e-8).
  • Absolute angular: \(\vert \rho \vert\) of the Pearson correlation, distance \(\sqrt{1 - \vert \rho \vert}\) (López de Prado, 2020, chapter 3), and squared angular: \(\rho^{2}\), distance \(\sqrt{1 - \rho^{2}}\), the same construction on the squared correlation, which put assets that move strongly against each other close together, as hedges of one another.
  • GNPR: the Generic Non-Parametric Representation distance of Marti et al. (2016), \(d^{2} = \theta d_{1}^{2} + (1 - \theta) d_{0}^{2}\) with \(\theta\) the GNPR theta, \(d_{1}^{2} = 3 / (T (T^{2} - 1)) \sum_{t} (R_{i,t} - R_{j,t})^{2}\) of the ranks R of the returns (\((1 - \rho_{S}) / 2\) without ties) and \(d_{0}^{2}\) = ½ \(\sum_{b} (\sqrt{g_{i,b}} - \sqrt{g_{j,b}})^{2}\) the squared Hellinger distance between the histograms g of the returns, with bins the GNPR bandwidth wide; codependence \(1 - d^{2}\). \(\theta = 1\) compares only how the assets move together, \(\theta = 0\) only how their returns are distributed.

Also known as: codependence, distance correlation, mutual information, variation of information, tail dependence matrix, correlation distance, angular distance, absolute angular distance, squared angular distance, GNPR, copula distance.

Example · AAPL, MSFT, JNJ, XOM · 2021 to 2025

Install the Finance Toolkit with pip install financetoolkit -U, then call get_codependence_matrix:

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_codependence_matrix(method="distance")

Or, with the Finance Toolkit MCP set up, ask an AI assistant such as Claude or ChatGPT:

How strongly did Apple, Microsoft, Johnson & Johnson and ExxonMobil move together from 2021 to 2025, measured by their distance correlation?

Which returns:

Parameters

get_codependence_matrix accepts the following parameters.

ParameterTypeDescriptionExample
methodstrThe codependence. Options are: “pearson” (Pearson correlation), “spearman” (Spearman correlation), “kendall” (Kendall correlation), “gerber” (Gerber statistic), “detoned” (detoned correlation), “distance” (distance correlation), “mutual_information” (mutual information), “lower_tail” (lower tail dependence), “absolute_angular” (absolute angular codependence), “squared_angular” (squared angular codependence), “gnpr” (GNPR codependence). Defaults to “pearson”."pearson"
periodstrThe 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"
covariancestrThe covariance estimator whose correlation the Pearson codependence is (see get_covariance_estimate). 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"
distanceboolWhether to return the distance matrix the clustering works on instead. Defaults to False.False
gerber_thresholdfloatThe threshold of the Gerber statistic in standard deviations. Defaults to 0.5.0.5
gerber_statisticintThe Gerber statistic. Options are: 0 (the original statistic), 1 (the positive semidefinite variant), 2 (the matrix form). Defaults to 1.1
componentsintThe number of principal components the detoned correlation removes. Defaults to 1.1
binsstr | intThe number of histogram bins of the mutual information, or the rule per pair. Options are: “freedman” (Freedman and Diaconis, skfolio’s default), “hacine_gharbi” (Hacine-Gharbi, López de Prado’s choice), or an integer. Defaults to “freedman”."freedman"
alphafloatThe share of the lowest returns that forms the tail of the lower tail dependence. Defaults to 0.05.0.01
gnpr_thetafloatThe weight \(\theta\) of the co-movement in the GNPR distance, between 0 and 1. Defaults to 0.5.0.5
gnpr_bandwidthfloatThe width of the histogram bins of the GNPR distance, in returns per period. Defaults to 0.01.0.01
include_benchmarkboolWhether to include the benchmark as an asset. Defaults to False.True
roundingint | NoneThe number of decimals to round the results to. Defaults to None, which uses the Toolkit’s rounding.2
show_columnsstr | list[str] | NoneThe 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

References

  • Paper Mantegna, R. N. (1999). “Hierarchical Structure in Financial Markets.” The European Physical Journal B, 11(1), 193-197.
  • Paper Székely, G. J., Rizzo, M. L. and Bakirov, N. K. (2007). “Measuring and Testing Dependence by Correlation of Distances.” The Annals of Statistics, 35(6), 2769-2794.
  • Paper Meilă, M. (2007). “Comparing Clusterings - An Information Based Distance.” Journal of Multivariate Analysis, 98(5), 873-895.
  • Paper Marti, G., Andler, S., Nielsen, F. and Donnat, P. (2016). “Clustering Financial Time Series: How Long Is Enough?” Proceedings of the Twenty-Fifth International Joint Conference on Artificial Intelligence (IJCAI-16), 2583-2589.
  • Paper Hacine-Gharbi, A. and Ravier, P. (2018). “A Binning Formula of Bi-histogram for Joint Entropy Estimation Using Mean Square Error Minimization.” Pattern Recognition Letters, 101, 21-28.
  • Paper López de Prado, M. (2020). “Machine Learning for Asset Managers.” Cambridge University Press, chapter 3.
  • Library Referenced against skfolio’s DistanceCorrelation
  • Library Referenced against skfolio’s MutualInformation
  • Library Referenced against Riskfolio-Lib’s mutual_info_matrix (Hacine-Gharbi bins)
  • Library Referenced against Riskfolio-Lib’s ltdi_matrix
  • Library Shares similar logic as Riskfolio-Lib’s codep_dist
  • Library Shares similar logic as skfolio’s CovarianceDistance (Pearson correlation)
  • Library Shares similar logic as skfolio’s DistanceCorrelation
  • Library Shares similar logic as skfolio’s MutualInformation
  • Library Shares similar logic as Riskfolio-Lib’s dcorr_matrix
  • Library Shares similar logic as Riskfolio-Lib’s var_info_matrix
Share