Heatmaps are great to visualize large amount of data and quickly find extreme events. In this notebook, we’ll create a heatmap of monthly returns for 3 decades starting 1990.
For investors and traders like us, it often helps to look at the history and not loose our cool especially in times when market is touching new highs every day. Let’s look at how market returns to equilibrium after extreme events.
You will need to install jugaad-data, pandas and seabron to execute below code using pip
.
from datetime import date, datetime
import pandas as pd
import calendar
import matplotlib.pyplot as plt
import seaborn as sns; sns.set_theme()
import jugaad_data.nse as nse
Download NIFTY historical data using jugaad-data. Also create columns M
and Y
from the HistoricalDate
column
nifty = nse.index_df(symbol="NIFTY 50", from_date=date(1990, 8,1), to_date=datetime.now().date())
nifty['M'] = nifty['HistoricalDate'].dt.month
nifty['Y'] = nifty['HistoricalDate'].dt.year
nifty
As you can see the data received is newest first, we need to sort oldest first and reset the indices.
nifty.sort_values('HistoricalDate', inplace=True)
nifty.reset_index(drop=True, inplace=True)
nifty.set_index('HistoricalDate', inplace=True)
Take values for last day of every month and calculate monthly returns
nifty_monthly = nifty.resample("M").last()
Calculate monthly returns
nifty_monthly['Returns'] = (nifty_monthly['CLOSE'] - nifty_monthly['CLOSE'].shift(1))*100/nifty_monthly['CLOSE'].shift(1)
nifty_monthly
Create matrix where rows represents years and columns as months
heatmap_ret = pd.pivot_table(nifty_monthly, index='Y', columns='M', values=['Returns'])
heatmap_ret.columns = [calendar.month_name[i] for i in range(1,13) ]
Finally, plot the heatmap using seaborn
plt.figure(figsize=(16, 10))
ax = sns.heatmap(heatmap_ret, cmap='RdYlGn', annot=True)
ax.tick_params(top=True, labeltop=True)
ax.get_figure().savefig('heatmap.png')