Shilpa Santosh Engineer and Aspiring Python Coder at Marketcalls. Love to explore the complexity of the Financial Markets.

A Quick Start Guide to Compute Correlation Matrix in Python using NSEpy & Pandas

1 min read

Here is a quick tutorial in python to compute Correlation Matrix between multiple stock instruments using python packages like NSEpy & Pandas. Generally Correlation Coefficient is a statistical measure that reflects the correlation between two stocks/financial instruments. Determining the relationship between two securities is useful for analyzing intermarket relationships, sector/stock relationships and sector/market relationships.

 

stock-correlation-heatmap

 

Here are some of the essential python libraries required for Correlation Matrix Data Visualization

IPython (Interactive Python)
Pandas (Python Library to handle time-series data )
NSEpy (Fetch Historical data from NSEindia – NSEpy 0.3 ver or higher)
Matplotlib (Python library to handle 2D plotting)

Import the required python modules

i)from nsepy.archives we need to import the get_price_history:-for fetching the stock pricing details
ii) from datetime import we need to import date object :- for giving the date limit for the required stocks
iii) import pandas :- for the creation of dataframe
iv)import matplotlib for plotting the correlation heatmap

Create a list of stocks

https://gist.github.com/bc87b534fb63ec4faae83843fbdc1f39

Fetch Historical Data
Now fetch the price history of each stock based on a specific time limit and appending the last close value into an empty pandas data frame

https://gist.github.com/0256e8d6701a95f9c3d8e21d96ed8b66

Compute and Plot Correlation Matrix
Now compute the percentage change and Pearson correlation using the pandas dataframe functions pct_change() , corr() and plot the correlation matrix using
matplotlib as shown below.

https://gist.github.com/1d2ba65cb5ba1da38cf542947d2885bc

Note : %pylab inline is used as a display variable on ipython notebook.

Sample IPython Notebook to generate Stock Correlation Matrix Map as shown below :

Shilpa Santosh Engineer and Aspiring Python Coder at Marketcalls. Love to explore the complexity of the Financial Markets.

Getting Started with Google Colab

Google Colab also known as Google Colaboratory is a product from Google Research which allows user to run their python code from their browser...
Rajandran R
1 min read

Python Multi-Broker Library for Algomojo – Trade Automation

Presenting a functional python wrapper for algomojo trading api. Algomojo is a multi broker python library for the Algomojo Free API + Free Algo...
Rajandran R
1 min read

Hurst Exponent – Checking for Trend Persistance – Python…

Hurst exponent is originally developed by the famous hydrologist Harold Edwin Hurst to study the Long-Term Storage Capacity of Reservoirs. Hurst is developed to...
Rajandran R
1 min read

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