# Asset Correlation Heatmap in Python: Returns, Clustering and Rolling Correlation

> Make an asset correlation heatmap in Python: compute returns with pct_change, call returns.corr(), draw it with sns.heatmap, order assets by clustering and plot rolling correlation between two assets.

Source: https://www.pythoncharts.com/python/asset-correlation-heatmap-python/ | Published: 2026-12-05 | Author: Alex Scott | Category: Python | Tags: correlation, heatmap, portfolio, asset-correlation, rolling-correlation, hierarchical-clustering, seaborn, pandas, financial-chart

To make an asset correlation heatmap in Python, compute daily returns with `prices.pct_change()`, take `returns.corr()`, and pass the matrix to `sns.heatmap()` with a diverging colormap and `vmin=-1, vmax=1`. Correlate returns, not prices: price levels trend, so their correlation is mostly an accident of direction. This post covers the finance-specific parts. For the general chart, see [Seaborn Heatmaps](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/) and [Correlation Matrix Heatmap with Annotations](https://www.pythoncharts.com/matplotlib/correlation-matrix-heatmap-annotations/).

## Quick Example

The ten "assets" are simulated from a few shared factors (a market factor, an interest-rate factor and a commodity factor), so the correlations have a realistic structure. In a stretch of the sample, bonds start moving with stocks, which matters later. Replace `prices` with a DataFrame of your own closing prices, one column per asset.

```python
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

rng = np.random.default_rng(3)
n = 1300
dates = pd.bdate_range("2021-01-04", periods=n, name="Date")
factors = pd.DataFrame({"market": rng.normal(0.0004, 0.010, n),
                        "rates": rng.normal(0, 0.004, n),
                        "commodity": rng.normal(0, 0.008, n)}, index=dates)
stress = np.zeros(n, dtype=bool)
stress[800:1050] = True                       # stocks and bonds fall and rise together

# loadings on (market, rates, commodity) and idiosyncratic volatility
spec = {
    "US Large":   (1.00, 0.0, 0.0, 0.004),
    "US Small":   (1.25, 0.0, 0.0, 0.008),
    "Europe":     (0.90, 0.0, 0.1, 0.007),
    "Japan":      (0.70, 0.0, 0.0, 0.008),
    "Emerging":   (0.95, 0.0, 0.4, 0.010),
    "Gov Bonds":  (-0.12, 1.0, 0.0, 0.002),
    "Corp Bonds": (0.10, 0.8, 0.0, 0.003),
    "Real Estate": (0.80, 0.5, 0.0, 0.009),
    "Gold":       (0.05, -0.4, 0.5, 0.008),
    "Oil":        (0.35, 0.0, 1.5, 0.014),
}
cols = {}
for name, (b_mkt, b_rate, b_com, idio) in spec.items():
    b = np.full(n, b_mkt)
    if name in ("Gov Bonds", "Corp Bonds"):
        b = np.where(stress, 0.45, b_mkt)
    cols[name] = b * factors["market"] + b_rate * factors["rates"] + b_com * factors["commodity"] + rng.normal(0, idio, n)
returns = pd.DataFrame(cols, index=dates)
prices = 100 * (1 + returns).cumprod()

corr = prices.pct_change().dropna().corr()
mask = np.triu(np.ones_like(corr, dtype=bool), k=1)   # hide the duplicate upper triangle

fig, ax = plt.subplots(figsize=(9, 7.5))
sns.heatmap(corr, mask=mask, annot=True, fmt=".2f", cmap="BrBG", vmin=-1, vmax=1, center=0,
            square=True, linewidths=0.5, cbar_kws={"label": "Correlation of daily returns", "shrink": 0.8}, ax=ax)
ax.set_xlabel("")
ax.set_ylabel("")
plt.show()
```

![Lower-triangle correlation heatmap of ten simulated assets, with strong positive correlations among stock indexes and weak or negative values for bonds and gold](https://www.pythoncharts.com/python/asset-correlation-heatmap-python/images/asset-corr-quick-example.png)

The stock indexes form a block of positive correlations: US Large and US Small are the closest pair at 0.76, and Japan is the least tied to the others (0.44 to 0.59). Real Estate sits with the stocks at 0.42 to 0.60. Government and corporate bonds correlate with each other at 0.63, but government bonds are about zero with every stock index (−0.03 to −0.07). Gold has the most negative values (−0.19 against government bonds and −0.13 against corporate bonds) and is close to zero against stocks. The mask hides the upper triangle, which would repeat the same numbers.

## Why correlate returns and not prices?

Prices wander. Two unrelated random walks will often drift in the same direction for years, which produces a high correlation that means nothing (a spurious correlation). Returns are close to stationary, so their correlation reflects how the assets move together day to day. The comparison on the same data:

```python
price_corr = prices.corr()
return_corr = prices.pct_change().dropna().corr()

fig, axes = plt.subplots(1, 2, figsize=(13, 6), sharey=True)
for ax, matrix, title in [(axes[0], price_corr, "Correlation of price levels"),
                          (axes[1], return_corr, "Correlation of daily returns")]:
    sns.heatmap(matrix, cmap="BrBG", vmin=-1, vmax=1, center=0, square=True, cbar=False, ax=ax)
    ax.set_title(title)
plt.tight_layout()
plt.show()
```

![Two heatmaps of the same ten assets: price level correlations show large blocks of strong positive and negative values, return correlations show a much cleaner structure](https://www.pythoncharts.com/python/asset-correlation-heatmap-python/images/asset-corr-prices-vs-returns.png)

The price-level matrix on the left is dominated by strong values: the average absolute off-diagonal correlation is 0.63 and the range runs from −0.72 to 0.97. On the returns matrix on the right the average is 0.30, and the most extreme price pair, government bonds and oil at −0.72, is −0.06 on returns. The price numbers describe where each series trended over these five years. They say little about whether the assets move together.

## How do I order the assets so related ones sit together?

The default order is whatever the columns happen to be. Hierarchical clustering on the distance `1 - correlation` puts similar assets next to each other so blocks appear. `scipy.cluster.hierarchy.leaves_list()` gives the new order:

```python
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import squareform

distance = 1 - return_corr
link = linkage(squareform(distance.values, checks=False), method="average")
order = return_corr.columns[leaves_list(link)]
print(list(order))

fig, ax = plt.subplots(figsize=(8, 6.5))
sns.heatmap(return_corr.loc[order, order], annot=True, fmt=".2f", cmap="BrBG", vmin=-1, vmax=1, center=0,
            square=True, linewidths=0.5, cbar=False, ax=ax)
ax.set_xlabel("")
ax.set_ylabel("")
plt.show()
```

![Correlation heatmap with assets reordered by hierarchical clustering so the equity assets form one block and the bonds another](https://www.pythoncharts.com/python/asset-correlation-heatmap-python/images/asset-corr-clustered.png)

The new order is `['Gov Bonds', 'Corp Bonds', 'Japan', 'Real Estate', 'Emerging', 'Europe', 'US Large', 'US Small', 'Gold', 'Oil']`. The bonds are now at the top-left, and the stock indexes and Real Estate form one block that runs down the middle. Gold and oil end up together at the bottom-right with the weakest ties to everything else. `method="average"` links clusters by their mean distance. Other methods (`"complete"`, `"ward"`) can change the order a little, but the blocks are the same.

For a one-call version that also draws the dendrogram, use `sns.clustermap(return_corr, ...)`, covered in [Seaborn Clustermap](https://www.pythoncharts.com/seaborn/seaborn-clustermap/).

## Does correlation stay constant over time?

No, and a single heatmap averages over regimes. Plot a rolling correlation between two assets to see it move. In the simulated data bonds hedge stocks for most of the sample but not during the stress period (days 800 to 1049, shaded):

```python
pair = returns["US Large"].rolling(60).corr(returns["Gov Bonds"])

fig, ax = plt.subplots(figsize=(10, 4.5))
ax.axvspan(dates[800], dates[1049], color="#e9c46a", alpha=0.3, label="Stress period")
ax.plot(pair, color="#01665e", lw=1.4)
ax.axhline(0, color="#555555", lw=0.8)
ax.set_ylabel("60-day correlation")
ax.set_title("US Large vs Gov Bonds")
ax.legend(loc="upper left")
plt.show()
print(f"full-sample correlation: {returns['US Large'].corr(returns['Gov Bonds']):.2f}")
```

![Line chart of the 60 day rolling correlation between US Large stocks and government bonds, negative for most of the sample and positive during the shaded stress period](https://www.pythoncharts.com/python/asset-correlation-heatmap-python/images/asset-corr-rolling.png)

```text
full-sample correlation: -0.06
```

The full-sample number of −0.06 hides two different regimes. Before the stress period the correlation is negative (−0.28 on average), and bonds cushion stock losses. Inside it, the 60-day correlation rises to 0.68 and is above zero on 92% of the days, and the correlation over those 250 days is 0.59. A portfolio built on the average would have found its hedge gone exactly when it was needed. The heatmap is a summary; the rolling line shows whether the summary is stable.

## Practical Tips

- **Use returns, and the same frequency for every asset.** Mixing daily and monthly data, or assets that trade on different calendars, distorts the matrix. Align them with `pd.concat(..., axis=1).dropna()` first.
- **Fix the color range at -1 to 1** (`vmin=-1, vmax=1, center=0`) so colors mean the same thing in every heatmap you make. Letting seaborn auto-scale makes a 0.3 to 0.6 range look like a full spectrum.
- **A diverging colormap matters here** because the sign is the point. Sequential colormaps hide the difference between 0.8 and -0.8.
- **Mask the upper triangle** (`np.triu`) because the matrix is symmetric and the diagonal is always 1.
- **Pearson correlation measures linear co-movement.** In crashes, assets can move together more than the full-sample number suggests. Check a rolling window or a stress subset (`returns[returns["US Large"] < -0.02].corr()`).
- **With few observations the matrix is noisy.** With 10 assets and 60 daily returns, many entries move by 0.1 or more from sample to sample.

## Similar Topics

- [Seaborn Heatmaps](https://www.pythoncharts.com/seaborn/heatmaps-seaborn/)
- [Seaborn Clustermap](https://www.pythoncharts.com/seaborn/seaborn-clustermap/)
- [Plot the Distribution of Stock Returns in Python](https://www.pythoncharts.com/python/stock-returns-distribution-python/)
