Heatmap
Stock Correlation Clustermap
Hierarchical clustering of stock price correlations
Output
Python
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage, leaves_list
from scipy.spatial.distance import pdist
from matplotlib.colors import LinearSegmentedColormap
np.random.seed(123)
data = np.random.randn(12, 12)
data[:4, :4] += 2
data[6:10, 6:10] -= 1.5
data[4:6, :] += 1
colors = ['#4f46e5', '#a5b4fc', '#e0e7ff', '#ffffff', '#fef3c7', '#fbbf24', '#d97706']
cmap = LinearSegmentedColormap.from_list('IndigoAmber', colors, N=256)
row_linkage = linkage(pdist(data), method='ward')
col_linkage = linkage(pdist(data.T), method='ward')
row_order = leaves_list(row_linkage)
col_order = leaves_list(col_linkage)
data_ordered = data[row_order][:, col_order]
fig = plt.figure(figsize=(9, 9), facecolor='white')
ax_heatmap = fig.add_axes([0.2, 0.1, 0.6, 0.6])
ax_col_dend = fig.add_axes([0.2, 0.71, 0.6, 0.15])
ax_row_dend = fig.add_axes([0.04, 0.1, 0.15, 0.6])
ax_cbar = fig.add_axes([0.83, 0.3, 0.03, 0.2])
im = ax_heatmap.imshow(data_ordered, cmap=cmap, aspect='auto', vmin=-3, vmax=3)
ax_heatmap.set_xticks([])
ax_heatmap.set_yticks([])
for spine in ax_heatmap.spines.values():
spine.set_linewidth(0.5)
spine.set_color('#cccccc')
dendrogram(col_linkage, ax=ax_col_dend, color_threshold=0, above_threshold_color='k',
link_color_func=lambda k: 'k', no_labels=True)
ax_col_dend.axis('off')
dendrogram(row_linkage, ax=ax_row_dend, orientation='left', color_threshold=0,
above_threshold_color='k', link_color_func=lambda k: 'k', no_labels=True)
ax_row_dend.axis('off')
cbar = plt.colorbar(im, cax=ax_cbar)
cbar.outline.set_linewidth(0.5)
cbar.ax.tick_params(labelsize=9, width=0.5)
cbar.set_label('Correlation', fontsize=10)
ax_col_dend.set_title('Stocks', fontsize=11, pad=5)
ax_row_dend.set_ylabel('Stocks', fontsize=11, labelpad=10)
ax_row_dend.yaxis.set_label_position('left')
plt.show()
Library
Matplotlib
Category
Heatmaps & Density
More Heatmap examples
☕