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.

A Quick Start Guide to Compute Correlation Matrix in Python using yFinance, Seaborn and Pandas

5 min read

To build a stock correlation matrix in Python, download closing prices with yfinance, convert them to daily returns with Pandas, call .corr() on the returns, and plot the result as a heatmap with Seaborn. The whole thing takes about 15 lines of code, and the matrix tells you at a glance which stocks move together and which ones diversify each other.

A correlation matrix is a quantitative tool used in finance, statistics, and other fields to measure and visualize the relationships between multiple variables. In the context of stock trading and investing, a correlation matrix is typically used to analyze the relationships between the price movements of different stocks over a specific time period. The correlation coefficient, which ranges from -1 to 1, is used to quantify the strength and direction of the relationship between two stocks.

Key Takeaways

  • Correlation ranges from -1 (move in opposite directions) to +1 (move together); values near 0 mean little linear relationship.
  • Always compute correlation on returns, not raw prices, or you will get misleadingly high numbers.
  • Newer yfinance versions return adjusted prices in the Close column by default, so the old ['Adj Close'] code can fail. An updated version is below.
  • A 20-day window shows the current regime; a longer window (for example 250 days) shows the structural relationship.
  • In the sample output, ICICI Bank and Reliance had the highest correlation (0.80), while Sun Pharma was negatively correlated with several banks and Tata Steel.

How to Build a Stock Correlation Matrix in Python: Step by Step

To create a correlation matrix table using Seaborn for the given stocks, you need to follow these steps:

OpenAlgo: one API for 35+ Indian brokers

FREE AND OPEN SOURCE

OpenAlgo: one API for 35+ Indian brokers

Self-hosted algo trading platform. Send orders from Python, AmiBroker, TradingView, Excel or a no-code flow through one consistent API.

  • Unified REST and WebSocket API
  • Works with AmiBroker, TradingView, ChartInk and Excel
  • Sandbox mode to test before going live
Get OpenAlgo →by Marketcalls
  1. Install required libraries
  2. Import the libraries
  3. Download stock data using yfinance
  4. Calculate the 20-day correlation
  5. Plot the correlation matrix using Seaborn

Step 1: Install the Libraries

Install the Libraries using PIP command

pip install yfinance seaborn pandas numpy matplotlib

Step 2: Download Data and Plot the 20-Day Correlation Heatmap

Here is a python code that will download the stock data for the given tickers(‘HDFCBANK.NS’, ‘ICICIBANK.NS’, ‘RELIANCE.NS’, ‘MARUTI.NS’, ‘SBIN.NS’, ‘SUNPHARMA.NS’, ‘TATASTEEL.NS’, ‘INFY.NS’, ‘TCS.NS’, ‘AXISBANK.NS’) and calculate the 20-day correlation, and plot the correlation matrix using Seaborn. Note that you may need to adjust the start_date and end_date variables to your desired timeframe.

# Import required libraries
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt

# Define the list of stocks
stocks = ['HDFCBANK.NS', 'ICICIBANK.NS', 'RELIANCE.NS', 'MARUTI.NS', 'SBIN.NS', 'SUNPHARMA.NS', 'TATASTEEL.NS', 'INFY.NS', 'TCS.NS', 'AXISBANK.NS']

# Download stock data using yfinance
data = yf.download(stocks, start='2022-01-01', end='2023-04-06')['Adj Close']

# Compute Percentage Change
rets = data.pct_change()

# Compute 20-day rolling correlation
corr_20_day = rets.rolling(window=20).corr()

# Get the latest correlation matrix
corr_matrix = corr_20_day.iloc[-len(stocks):]

# Plot Correlation Matrix using Matplotlib

plt.figure(figsize=(10, 10))
plt.imshow(corr_matrix, cmap='RdYlGn', interpolation='none', aspect='auto')
plt.colorbar()
plt.xticks(range(len(corr_matrix)), corr_matrix.columns, rotation='vertical')
plt.yticks(range(len(corr_matrix)), corr_matrix.columns)
plt.suptitle('20-Day Rolling Stock Correlations Heat Map', fontsize=15, fontweight='bold')
plt.show()

Step 3: Print the Correlation Matrix as a Table

# Import required libraries
import yfinance as yf
import pandas as pd

# Define the list of stocks
stocks = ['HDFCBANK.NS', 'ICICIBANK.NS', 'RELIANCE.NS', 'MARUTI.NS', 'SBIN.NS', 'SUNPHARMA.NS', 'TATASTEEL.NS', 'INFY.NS', 'TCS.NS', 'AXISBANK.NS']

# Download stock data using yfinance
data = yf.download(stocks, start='2022-01-01', end='2023-04-06')['Adj Close']

# Compute Percentage Change
rets = data.pct_change()

# Compute 20-day rolling correlation
corr_20_day = rets.rolling(window=20).corr()

# Get the latest correlation matrix
corr_matrix = corr_20_day.iloc[-len(stocks):]

# Display the correlation matrix
print(corr_matrix)

Python Output

                         AXISBANK.NS  HDFCBANK.NS  ICICIBANK.NS   INFY.NS  \
Date                                                                        
2023-04-06 AXISBANK.NS      1.000000     0.569418      0.669686  0.323919   
           HDFCBANK.NS      0.569418     1.000000      0.553462  0.505160   
           ICICIBANK.NS     0.669686     0.553462      1.000000  0.532197   
           INFY.NS          0.323919     0.505160      0.532197  1.000000   
           MARUTI.NS        0.089447    -0.117898      0.088857 -0.074389   
           RELIANCE.NS      0.556131     0.561288      0.795301  0.507474   
           SBIN.NS          0.664366     0.655983      0.542818  0.509560   
           SUNPHARMA.NS    -0.267849     0.164081     -0.291801 -0.069568   
           TATASTEEL.NS     0.216665     0.164084      0.177518  0.379145   
           TCS.NS           0.186048     0.415205      0.475583  0.739076   

                         MARUTI.NS  RELIANCE.NS   SBIN.NS  SUNPHARMA.NS  \
Date                                                                      
2023-04-06 AXISBANK.NS    0.089447     0.556131  0.664366     -0.267849   
           HDFCBANK.NS   -0.117898     0.561288  0.655983      0.164081   
           ICICIBANK.NS   0.088857     0.795301  0.542818     -0.291801   
           INFY.NS       -0.074389     0.507474  0.509560     -0.069568   
           MARUTI.NS      1.000000     0.263537  0.337897      0.184349   
           RELIANCE.NS    0.263537     1.000000  0.644776     -0.058505   
           SBIN.NS        0.337897     0.644776  1.000000      0.113177   
           SUNPHARMA.NS   0.184349    -0.058505  0.113177      1.000000   
           TATASTEEL.NS   0.080105     0.168075  0.198621     -0.330021   
...
           SBIN.NS           0.198621  0.469686  
           SUNPHARMA.NS     -0.330021  0.135291  
           TATASTEEL.NS      1.000000  0.252214  
           TCS.NS            0.252214  1.000000  

Updated Version (2026): Fix the ‘Adj Close’ KeyError

The code above was written in April 2023. Since then yfinance changed its default to auto_adjust=True, which adjusts the Open, High, Low and Close columns for splits and dividends and drops the separate Adj Close column (explained here). If you run the original code on a recent yfinance version, ['Adj Close'] can raise a KeyError.

Here is an updated version that uses the adjusted Close column, computes the latest 20-day correlation directly and draws a proper Seaborn heatmap with the values printed in each cell:

# Updated version (2026)
import yfinance as yf
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

stocks = ['HDFCBANK.NS', 'ICICIBANK.NS', 'RELIANCE.NS', 'MARUTI.NS', 'SBIN.NS',
          'SUNPHARMA.NS', 'TATASTEEL.NS', 'INFY.NS', 'TCS.NS', 'AXISBANK.NS']

# auto_adjust=True returns split/dividend-adjusted prices in the 'Close' column
data = yf.download(stocks, start='2024-01-01', end='2026-11-01', auto_adjust=True)['Close']

# Daily returns (no forward-filling of missing prices)
rets = data.pct_change(fill_method=None).dropna()

# Correlation over the latest 20 trading days
corr_matrix = rets.tail(20).corr()
print(corr_matrix.round(2))

# Seaborn heatmap
plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, fmt='.2f', cmap='RdYlGn',
            vmin=-1, vmax=1, square=True, linewidths=0.5)
plt.title('20-Day Stock Correlation Matrix', fontsize=15, fontweight='bold')
plt.tight_layout()
plt.show()

Two details worth noting: rets.tail(20).corr() gives the same numbers as the last window of the rolling correlation in the original code, but as a clean square table; and fixing vmin=-1, vmax=1 keeps the colour scale comparable from one run to the next. If you want to keep the old behaviour instead, pass auto_adjust=False and the Adj Close column comes back. For more on the library, see Mastering yfinance: the ultimate guide.

How to Read a Stock Correlation Matrix

Correlation coefficientWhat it means
+0.7 to +1.0Strong positive: the stocks usually move together
+0.3 to +0.7Moderate positive
-0.3 to +0.3Weak or no linear relationship: good for diversification
-0.7 to -0.3Moderate negative
-1.0 to -0.7Strong negative: the stocks usually move in opposite directions

Applying this to the output above (20 days ending 6 April 2023):

  • ICICIBANK and RELIANCE had the strongest correlation at 0.80, and INFY and TCS were at 0.74, which is expected for two large IT services companies.
  • Banks were moderately correlated with each other: AXISBANK–ICICIBANK at 0.67 and AXISBANK–SBIN at 0.66.
  • SUNPHARMA was negatively correlated with ICICIBANK (-0.29), AXISBANK (-0.27) and TATASTEEL (-0.33), making it the main diversifier in this basket during that window.
  • MARUTI had low correlation with almost everything, so it behaved largely independently.

Rolling vs Full-Period Correlation

A single correlation number hides how the relationship changes. A 20-day window reacts quickly to news and sector rotation, while a 250-day window shows the long-run relationship. To see how a pair’s correlation evolves, plot a rolling series, for example rets['INFY.NS'].rolling(60).corr(rets['TCS.NS']). Sharp drops in a normally high correlation can flag a stock-specific event; a sudden jump in correlation across all stocks usually signals a market-wide sell-off.

How a Correlation Matrix Is Useful for Traders and Investors

Diversification: Traders can use the correlation matrix to identify stocks that are weakly correlated or negatively correlated, thereby helping them to diversify their portfolio. By investing in stocks that do not move in the same direction, traders can potentially reduce the overall risk of their portfolio.

Risk management: Correlation analysis can help traders identify and manage risk by highlighting stocks that tend to move together. By understanding these relationships, traders can adjust their positions and hedge against potential losses.

Trading strategies: Traders can use the correlation matrix to develop and validate trading strategies. For example, pairs trading involves taking long and short positions in two highly correlated stocks, expecting that the spread between their prices will converge or diverge. By identifying such pairs, traders can potentially profit from temporary price discrepancies.

Market sentiment analysis: The correlation matrix can also provide insights into market sentiment. For instance, if most stocks in a sector or market are highly correlated, it may indicate that they are all being influenced by a common factor, such as broad market trends, economic conditions, or geopolitical events. This information can help traders make informed decisions about their investments.

Common Mistakes to Avoid

  • Correlating prices instead of returns. Two trending stocks will show a high price correlation even if their daily moves are unrelated.
  • Using too short a window. 20 days gives only 20 data points, so a single big day can swing the result.
  • Assuming correlations are stable. In crashes, correlations between stocks tend to rise sharply, just when you need diversification most.
  • Reading correlation as causation. Two stocks can move together because of a common factor, such as the overall market, not because one drives the other.

If you want to go further, read how to build a correlation matrix using Python Pandas and Seaborn for a deeper Pandas workflow, see my older correlation study on Nifty stocks for a manual approach, or build the same table in Amibroker with this correlation matrix exploration.

Frequently Asked Questions

How do I calculate a correlation matrix in Python?

Load prices into a Pandas DataFrame with one column per stock, convert to returns with pct_change(), and call .corr(). The result is a square matrix of Pearson correlation coefficients that you can plot with seaborn.heatmap().

Why does my yfinance code give a KeyError for Adj Close?

Recent yfinance versions default to auto_adjust=True, which puts adjusted prices in the Close column and removes Adj Close. Use [‘Close’] instead, or pass auto_adjust=False to get the Adj Close column back.

Should I use price or returns for stock correlation?

Use returns. Prices are trending series, and correlating them overstates how closely two stocks move together. Daily or weekly returns give a far more reliable picture.

What is a good correlation for diversification?

Stocks with correlations below about 0.3, or negative correlations, add the most diversification. Pairs above 0.7 behave almost like the same position.

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.

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