Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Build a Correlation Matrix using Python Pandas and Seaborn

5 min read

Building a correlation matrix in Python with Pandas takes just one line: download closing prices into a DataFrame and call df.corr(). In this tutorial we build a correlation matrix for 10 NSE stocks using yfinance, Pandas and Seaborn, plot it as a heatmap, and then look at an updated 2026 version that fixes a delisted ticker and measures correlation on returns instead of prices.

In finance, a correlation matrix is a matrix that shows the correlation between different variables. It is a powerful tool for analyzing the relationships between different stocks or other financial instruments. In this blog, we will explore how to build a correlation matrix using Python Pandas and Seaborn.

To begin, we will use the yfinance library to download historical stock price data for a set of tickers. We will then extract the closing prices from this data and compute the correlation matrix using Pandas. Finally, we will use Seaborn to visualize the correlation matrix as a heatmap.

Python for traders, the quick way in

BEGINNER FRIENDLY · RATED 5.0

Python for traders, the quick way in

A crash course that gets you from zero to writing your own market data scripts.

  • Python basics with market examples
  • Fetch, clean and chart price data
  • Lifetime access
Start learning →by Marketcalls
Key takeaways
  • DataFrame.corr() returns a Pearson correlation matrix by default; values run from -1 to +1.
  • Seaborn’s heatmap() with annot=True and vmin=-1, vmax=1 gives a readable colour-coded matrix.
  • HDFC.NS was delisted after the July 2023 merger, so the original ticker list now returns an empty column.
  • Correlation of daily returns is more meaningful for trading than correlation of raw prices.

What a correlation matrix in Python tells a trader

Each cell shows the correlation coefficient between two stocks. A value close to +1 means the two usually move in the same direction, close to -1 means they move in opposite directions, and around 0 means there is little linear relationship. The diagonal is always 1 because each stock is perfectly correlated with itself.

Correlation valueHow to read itPractical use
0.7 to 1.0Strong positiveHolding both adds little diversification; candidates for pair trading
0.3 to 0.7Moderate positiveTypical for large caps in the same market
-0.3 to 0.3Weak or noneGood diversifiers for a portfolio
Below -0.3NegativeNatural hedges, for example NIFTY and USDINR over long periods
Rough guide to reading correlation coefficients

Step 1: Download Historical Stock Price Data

First, we need to download historical stock price data for a set of tickers. We will use the yfinance library to do this. The yfinance library provides a simple way to download historical stock price data from Yahoo Finance.

We start by importing the yfinance library and defining the list of tickers we want to analyze. For this example, we will analyze 10 tickers. Next, we can use the yf.download() function to download the historical stock price data for these tickers. We set the period parameter to 20 to download last 20 days of historical data for all the ticker symbols.

import yfinance as yf
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# define the list of tickers
tickers = ['RELIANCE.NS', 'SBIN.NS', 'TCS.NS', 'INFY.NS', 'HDFCBANK.NS', 'HDFC.NS', 'MARUTI.NS', 'TATASTEEL.NS', 'ONGC.NS', 'ITC.NS']

# download historical stock price data from Yahoo Finance
data = yf.download(tickers, period='20d', group_by='ticker')

Step 2: Extract Closing Prices

Next, we need to extract the closing prices from the historical stock price data. We will do this by creating a new DataFrame that contains only the closing prices for each ticker.

# extract the closing prices
close_prices = pd.DataFrame()
for ticker in tickers:
    close_prices[ticker] = data[ticker]['Close']

This creates a new DataFrame called close_prices that contains only the closing prices for each ticker. The DataFrame has one column for each ticker and one row for each date.

Step 3: Compute the Correlation Matrix

Now that we have the closing prices for each ticker, we can compute the correlation matrix using Pandas. Pandas provide a corr() method that computes the correlation matrix for a DataFrame.

# compute the correlation matrix
corr_matrix = close_prices.corr()

This computes the correlation matrix for the close_prices DataFrame. The resulting corr_matrix DataFrame contains the correlation coefficients between each pair of tickers.

By default pandas DataFrame.corr() uses the Pearson method. You can pass method='spearman' or method='kendall' for rank-based correlation, which is less sensitive to outliers.

Step 4: Visualize the Correlation Matrix as Heatmap

Finally, we can visualize the correlation matrix as a heatmap using Seaborn. Seaborn provides a heatmap() function that creates a heatmap of a matrix.

# create a heatmap of the correlation matrix using Seaborn
sns.set(style='white')
fig, ax = plt.subplots(figsize=(10, 10))
sns.heatmap(corr_matrix, annot=True, cmap='RdYlGn', vmin=-1, vmax=1, ax=ax)

# set the axis labels and title
ax.set_xlabel('Stock Tickers')
ax.set_ylabel('Stock Tickers')
ax.set_title('10x10 Correlation Matrix of Stock Prices (20-day period)')

# display the plot
plt.show()

The cmap='RdYlGn' colour map shows negative correlation in red and positive in green, and fixing vmin=-1 and vmax=1 keeps the colour scale comparable between runs. See the seaborn heatmap documentation for other options such as mask to hide the duplicate upper triangle.

Here is the complete Python code for correlation matrix

import yfinance as yf
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# define the list of tickers
tickers = ['RELIANCE.NS', 'SBIN.NS', 'TCS.NS', 'INFY.NS', 'HDFCBANK.NS', 'HDFC.NS', 'MARUTI.NS', 'TATASTEEL.NS', 'ONGC.NS', 'ITC.NS']

# download historical stock price data from Yahoo Finance
data = yf.download(tickers, period='20d', group_by='ticker')

# extract the closing prices
close_prices = pd.DataFrame()
for ticker in tickers:
    close_prices[ticker] = data[ticker]['Close']

# compute the correlation matrix
corr_matrix = close_prices.corr()

# create a heatmap of the correlation matrix using Seaborn
sns.set(style='white')
fig, ax = plt.subplots(figsize=(10, 10))
sns.heatmap(corr_matrix, annot=True, cmap='RdYlGn', vmin=-1, vmax=1, ax=ax)

# set the axis labels and title
ax.set_xlabel('Stock Tickers')
ax.set_ylabel('Stock Tickers')
ax.set_title('10x10 Correlation Matrix of Stock Prices (20-day period)')

# display the plot
plt.show()

Updated version (2026): correlation matrix of returns

Two things have changed since this post was written in 2023. First, HDFC Ltd merged into HDFC Bank with effect from 1 July 2023 and HDFC.NS was delisted, so yfinance now prints “No data found, symbol may be delisted” and the HDFC.NS column comes back empty. Second, current yfinance versions adjust prices by default (auto_adjust=True), so the Close column is already adjusted for splits and dividends.

The updated script replaces HDFC.NS with ICICIBANK.NS, uses a one-year window and computes correlation on daily percentage returns:

import yfinance as yf
import seaborn as sns
import matplotlib.pyplot as plt

# HDFC.NS was delisted after the HDFC-HDFC Bank merger (July 2023), so it is replaced
tickers = ['RELIANCE.NS', 'SBIN.NS', 'TCS.NS', 'INFY.NS', 'HDFCBANK.NS',
           'ICICIBANK.NS', 'MARUTI.NS', 'TATASTEEL.NS', 'ONGC.NS', 'ITC.NS']

# auto_adjust=True is the default in current yfinance; 'Close' is the adjusted close
data = yf.download(tickers, period='1y', progress=False)
close_prices = data['Close'].dropna()

# correlation of daily returns (more meaningful than correlation of price levels)
returns = close_prices.pct_change().dropna()
corr_matrix = returns.corr()
print(corr_matrix.round(2))

sns.set_theme(style='white')
fig, ax = plt.subplots(figsize=(10, 10))
sns.heatmap(corr_matrix, annot=True, fmt='.2f', cmap='RdYlGn', vmin=-1, vmax=1, ax=ax)
ax.set_title('Correlation Matrix of Daily Returns (1 year)')
plt.tight_layout()
plt.show()

Why returns? Two stocks that both trended up for a year will show a high correlation of prices even if their day-to-day moves are unrelated. Returns remove the trend and show whether the stocks actually move together on the same days, which is what matters for hedging and diversification. When I ran this in November 2026, TCS and Infosys had a return correlation of about 0.78, HDFC Bank and ICICI Bank about 0.54, while ONGC was close to zero or slightly negative against the private banks.

Rolling correlation

Correlation is not constant. A rolling window shows how the relationship changes over time:

# rolling 60-day correlation between two stocks
rolling = returns['TCS.NS'].rolling(60).corr(returns['INFY.NS'])
print(rolling.dropna().tail())

A sudden drop in rolling correlation between two normally linked stocks, such as two IT majors, is often the first sign of stock-specific news.

Common mistakes when building a correlation matrix

  • Too little data: the original example uses 20 days, which is good for a quick view but noisy. Use 6 months to 1 year for portfolio decisions.
  • Correlating prices instead of returns: trending prices inflate correlation, as explained above.
  • Missing values: holidays or new listings create NaNs. Use dropna() so all stocks are compared over the same dates.
  • Delisted or renamed tickers: always check the download log for failed symbols before trusting the matrix.
  • Assuming stability: correlations rise sharply in market sell-offs, exactly when you need diversification most.

If you prefer AmiBroker, the same analysis is covered in how to create a correlation matrix table using AmiBroker. For more on downloading data, read the ultimate guide to yfinance.

Frequently Asked Questions

How do you create a correlation matrix in Python?

Load your data into a Pandas DataFrame with one column per variable and call df.corr(). For stocks, download closing prices with yfinance, convert them to returns with pct_change(), then run corr().

How do I plot a correlation matrix as a heatmap?

Pass the matrix to seaborn.heatmap(corr_matrix, annot=True, cmap=’RdYlGn’, vmin=-1, vmax=1). annot prints the values in each cell and the vmin and vmax settings fix the colour scale.

What is a good correlation value for diversification?

Stocks with a return correlation below about 0.3 add real diversification. Values above 0.7 behave almost like the same position.

Which correlation method does Pandas use?

Pearson by default. You can switch to Spearman or Kendall with the method argument when the data has outliers or non-linear relationships.

Python Elite membership

MEMBERSHIP

Python Elite membership

15 Python, AI and algo trading programs in one plan, including QuantFlow and AI Bootcamp live mentorship.

  • Python from fundamentals to trading apps
  • Backtesting, broker APIs and OpenAlgo
  • Live QuantFlow and AI Bootcamp sessions
View Python Elite →by Marketcalls

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More