Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

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

2 min read

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.

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

  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

Install the Libraries using PIP command

pip install yfinance seaborn pandas numpy matplotlib

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()

Plotting Correlation Matric in a Table Format – Code Snippet

# 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  


How Correlation Matrix is Useful for Traders/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.

Rajandran R Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, USDINR and 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. Strongly believe that market understanding and robust trading frameworks are the key to the trading success. Writing about Markets, Trading System Design, Market Sentiment, Trading Softwares & Trading Nuances since 2007 onwards. Author of Marketcalls.in)

[Live Coding Webinar] Build Your First Trading Bridge for…

In this course, you will be learning to build your own trading bridge using Python. This 60-minute session is perfect for traders, Python enthusiasts,...
Rajandran R
1 min read

How to Place Orders Concurrently using ThreadPoolExecutor – Python…

Creating concurrent orders is essential for active traders, especially those handling large funds, as it allows for executing multiple trade orders simultaneously, thereby maximizing...
Rajandran R
2 min read

Host your Python Flask Web Application using pyngrok and…

Ngrok offers several significant advantages for developers, especially when it comes to testing applications or hosting machine learning models. Ngrok allows you to expose...
Rajandran R
1 min read

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