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)

Nifty Monthly and Quarterly Returns Heatmap Generation using yfinance and Seaborn

2 min read

Everyone loves to visualize this market in their own way. Python comes in handy when comes to visualization. One of the Awesome programming languages to code any level of complexity. In this blog post, we will explore how to generate a heatmap of monthly returns for the Nifty 50 index using Python libraries yfinance, pandas, and seaborn.

To generate the heatmap, we first need to get the historical data for the Nifty 50 index. We will be using the yfinance library to retrieve the data. yfinance is a Python library that provides an easy way to download historical stock price data from Yahoo Finance.

Nifty Monthly Returns heatmap

Here are some of the essential python libraries required for Stock Market Data Visualization


Seaborn (Statistical Data Visualization Package )
Pandas (Python Library to handle time-series data )
yfinance (Fetch Historical data from Yahoo Finance)
Matplotlib (Python library to handle 2D plotting)

Here is a simple python code that plots the Nifty Returns in a Heatmap format using Seaborn library

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

ticker = "^NSEI"
start_date = "2009-12-31"
end_date = "2023-04-01"

# Download the historical data for Nifty Index
data = yf.download(ticker, start=start_date, end=end_date)

# Resample the data on a monthly basis
data_monthly = data.resample('M').last()

# Calculate the monthly returns
monthly_returns = data_monthly['Adj Close'].pct_change()

# Convert monthly returns to a pandas DataFrame
monthly_returns_df = pd.DataFrame(monthly_returns)

# Pivot the DataFrame to create a matrix of monthly returns by year and month
monthly_returns_matrix = monthly_returns_df.pivot_table(values='Adj Close', index=monthly_returns_df.index.year, columns=monthly_returns_df.index.month)

# Set the column names to the month names
monthly_returns_matrix.columns = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

# Calculate the sum of monthly returns for each year
yearly_returns = monthly_returns_df.groupby(monthly_returns_df.index.year)['Adj Close'].sum()

# Add the yearly returns to the matrix as a new column
monthly_returns_matrix['Yearly'] = yearly_returns

# Set the font scale
sns.set(font_scale=1.2)

# Plot the heatmap using seaborn
plt.figure(figsize=(14, 12))
sns.heatmap(monthly_returns_matrix, annot=True, cmap='RdYlGn', center=0, fmt='.2%', cbar=False)
plt.title('Nifty Monthly and Yearly Returns by Year and Month', fontsize=20)
plt.xlabel('Month', fontsize=14)
plt.ylabel('Year', fontsize=14)
plt.show()

Nifty Quarterly Returns heatmap

Here is a simple python code that plots the Nifty Quarterly Returns in a Heatmap format using Seaborn library

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

ticker = "^NSEI"
start_date = "2009-12-31"
end_date = "2023-04-01"

# Download the historical data for Reliance Industries Limited's stock
data = yf.download(ticker, start=start_date, end=end_date)

# Resample the data on a quarterly basis
data_quarterly = data.resample('Q').last()

# Calculate the quarterly returns
quarterly_returns = data_quarterly['Adj Close'].pct_change()

# Convert quarterly returns to a pandas DataFrame
quarterly_returns_df = pd.DataFrame(quarterly_returns)

# Pivot the DataFrame to create a matrix of quarterly returns by year and quarter
quarterly_returns_matrix = quarterly_returns_df.pivot_table(values='Adj Close', index=quarterly_returns_df.index.year, columns=quarterly_returns_df.index.quarter)

# Set the column names to the quarter names
quarterly_returns_matrix.columns = ['Q1', 'Q2', 'Q3', 'Q4']

# Calculate the yearly returns as the sum of all quarterly returns for that year
yearly_returns = quarterly_returns_df.groupby(quarterly_returns_df.index.year)['Adj Close'].sum()

# Add the yearly returns to the matrix as a new column
quarterly_returns_matrix['Yearly'] = yearly_returns

# Set the font scale
sns.set(font_scale=1.2)

# Plot the heatmap using seaborn
plt.figure(figsize=(10, 12))
sns.heatmap(quarterly_returns_matrix, annot=True, cmap='RdYlGn', center=0, fmt='.2%', cbar=False)
plt.title('Nifty Quarterly and Yearly Returns by Year and Quarter', fontsize=20)
plt.xlabel('Quarter', fontsize=14)
plt.ylabel('Year', fontsize=14)
plt.show()
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)

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

Building a Google Gemini Digital Assistant Slack Bot :…

In an era where efficiency is key, integrating a digital assistant into Slack using Google Gemini's AI technology offers a transformative solution. This guide...
Rajandran R
10 min read

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