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.

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-02-25"
# 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 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']
# Set the font scale
sns.set(font_scale=1.2)
# Plot the heatmap using seaborn
plt.figure(figsize=(12, 12))
sns.heatmap(monthly_returns_matrix, annot=True, cmap='RdYlGn', center=0, fmt='.2%', cbar=False)
plt.title('Nifty Monthly Returns by Year and Month', fontsize=20)
plt.xlabel('Month', fontsize=14)
plt.ylabel('Year', fontsize=14)
plt.show()