-
-
Save ksv-muralidhar/1baa0a900342fbffe30817d962af0cde to your computer and use it in GitHub Desktop.
gradient_background
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from datetime import datetime | |
from sklearn.preprocessing import MinMaxScaler | |
nifty = pd.read_csv('nifty.csv', usecols=['Date', 'Close'], parse_dates=True) | |
#nifty = Nifty data from Jan 1, 2020 to 18 Sep, 2020 | |
nifty = nifty.loc[(nifty['Date'] >= "2020-01-01") & (nifty['Date'] <= "2020-09-18")].copy() | |
''' | |
slump = Nifty data from 19 Feb, 2020 to 18 May, 2020. | |
This is the period where Nifty slumped due to Covid-19. | |
''' | |
slump = nifty.loc[(nifty['Date'] >= "2020-02-19") & (nifty['Date'] <= "2020-05-18")].copy() | |
''' | |
recovery = Nifty data from 18 May, 2020 till the end i.e. 18 Sep, 2020. | |
This is the period where Nifty showed a decisive recovery from to Covid-19. | |
''' | |
recovery = nifty.loc[(nifty['Date'] > "2020-05-18")].copy() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fig, ax = plt.subplots(1, 1, figsize=(14,6), facecolor='white') | |
# setting the axes color to light gray | |
ax.margins(x=0) | |
ax.spines['bottom'].set_color('lightgray') | |
ax.spines['top'].set_color('lightgray') | |
ax.spines['left'].set_color('lightgray') | |
ax.spines['right'].set_color('lightgray') | |
ax.tick_params(axis='both', colors='lightgray') | |
ax.plot(nifty['Date'], nifty['Close'], color='black') # plotting nifty | |
ax.plot(slump['Date'], slump['Close'], color='red') # plotting slump | |
ax.plot(recovery['Date'], recovery['Close'], color='limegreen') # plotting recovery | |
# selecting every 5th date to display x ticks. | |
x_ticks = [*nifty.Date.reset_index(drop=True)[np.arange(0, len(nifty), 5)]] | |
# selecting every 400th value of close to display y ticks. | |
y_ticks = np.arange(nifty.Close.min(), nifty.Close.max()+400, 400) | |
plt.xticks(x_ticks, rotation=90, color='gray') | |
plt.yticks(y_ticks, color='gray') | |
# date when slump started (2020-02-19) | |
slump_start_date = [*nifty['Date']][35] | |
# value as on slump_start_date (12,125.9) | |
slump_start_value = np.round(float(nifty.loc[nifty['Date'] == slump_start_date, 'Close']), 2) | |
plt.annotate(text=f"Dip due to Covid on\n{slump_start_date} at\n{slump_start_value:,}", xy=[38,12000],color='black',fontsize=11) | |
# date when Nifty began recovering (2020-05-18) | |
recovery_start_date = [*nifty['Date']][91] | |
# value as on recovery_start_date (8,823.25) | |
recovery_start_value = np.round(float(nifty.loc[nifty['Date'] == recovery_start_date, 'Close']), 2) | |
# % drop from top (12,125.9) to recovery_start_value (8,823.25) | |
recovery_pct_change_from_top = np.abs(np.round(((recovery_start_value / slump_start_value) - 1) * 100, 2)) | |
plt.annotate(text=f"Began recovering from Covid on\n{recovery_start_date} at "+ | |
f"{recovery_start_value:,}\nstill down {recovery_pct_change_from_top}% from the top", | |
xy=[92,8300],color='black', fontsize=11) | |
# bottom (7,610.25) | |
bottom = nifty.Close.min() | |
# % drop from top (12,125.9) to bottom (7,610.25) | |
bottom_pct_change_from_top = np.abs(np.round(((bottom / slump_start_value) - 1) * 100, 2)) | |
plt.annotate(text=f"Bottom at {bottom:,}\ndown {bottom_pct_change_from_top}%\nfrom the top", xy=[59,7500],color='black',fontsize=11) | |
# difference in days from (time delta) from slump to recovery | |
recovery_time = (datetime.strptime(recovery_start_date, '%Y-%m-%d') - datetime.strptime(slump_start_date, '%Y-%m-%d')).days | |
plt.annotate(text=f"{recovery_time}", xy=[61,11200],color='dimgray',fontsize=35, fontweight='bold') | |
plt.annotate(text="days of\ncarnage", xy=[59,10600],color='dimgray',fontsize=15, fontweight='bold') | |
plt.title("NIFTY'S JOURNEY THROUGH COVID-19", fontdict={'fontsize': 20, | |
'fontweight': 'bold', | |
'color': 'dimgray', | |
'verticalalignment': 'top'}, | |
loc='left'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fig,ax = plt.subplots(1,1, figsize=(14,6), facecolor='white') | |
# setting the axes color to light gray | |
ax.margins(x=0) | |
ax.spines['bottom'].set_color('lightgray') | |
ax.spines['top'].set_color('lightgray') | |
ax.spines['left'].set_color('lightgray') | |
ax.spines['right'].set_color('lightgray') | |
ax.tick_params(axis='both', colors='lightgray') | |
ax.plot(nifty['Date'], nifty['Close'], color='black') # plotting nifty | |
ax.plot(slump['Date'], slump['Close'], color='red') # plotting slump | |
ax.plot(recovery['Date'], recovery['Close'], color='green') # plotting recovery | |
# selecting every 5th date to display x ticks. | |
x_ticks = [*nifty.Date.reset_index(drop=True)[np.arange(0, len(nifty), 5)]] | |
# selecting every 400th value of close to display y ticks. | |
y_ticks = np.arange(nifty.Close.min(), nifty.Close.max()+400, 400) | |
plt.xticks(x_ticks, rotation=90, color='gray') | |
plt.yticks(y_ticks, color='gray') | |
# date when slump started (2020-02-19) | |
slump_start_date = [*nifty['Date']][35] | |
# value as on slump_start_date (12,125.9) | |
slump_start_value = np.round(float(nifty.loc[nifty['Date'] == slump_start_date, 'Close']), 2) | |
################################################## | |
### Code to generate gradient background START ### | |
################################################## | |
# Calculating 3-day moving average of the time series during the slump | |
low_color_range = slump[['Close']].rolling(3).mean().dropna().copy() | |
# normalizing the moving average values and repeating each value 10 times | |
low_gradient = [*np.repeat(MinMaxScaler(feature_range=(0.15, 1)).fit_transform(low_color_range).ravel(), 10)] | |
# adding the last value 20 times to acommodate the shortfall in the values due to moving average calculation | |
low_gradient.extend([low_gradient[-1]] * 20) | |
# plotting vertical lines by varying the alpha according to low_gradient | |
for n, i in zip(np.arange(0, len(low_gradient), 1), np.arange(35, 91, 0.1)): | |
plt.axvline(x=i, linestyle='-', linewidth=0.3, color='tomato', alpha=np.max(low_gradient) - low_gradient[n]) | |
plt.annotate(text=f"Dip due to Covid on\n{slump_start_date} at\n{slump_start_value:,}", xy=[38,12000],color='black',fontsize=11) | |
# Calculating 3-day moving average of the time series during the recovery | |
recovery_color_range = recovery[['Close']].rolling(3).mean().dropna().copy() | |
# normalizing the moving average values and repeating each value 10 times | |
recovery_gradient = [*np.repeat(MinMaxScaler(feature_range=(0.15, 1)).fit_transform(recovery_color_range).ravel(), 10)] | |
# adding the last value 20 times to acommodate the shortfall in the values due to moving average calculation | |
recovery_gradient.extend([recovery_gradient[-1]] * 20) | |
# plotting vertical lines by varying the alpha according to recovery_gradient | |
for n, i in zip(np.arange(0, len(recovery_gradient), 1), np.arange(91, len(nifty), 0.1)): | |
plt.axvline(x=i, linestyle='-', linewidth=0.3, color='limegreen', alpha=recovery_gradient[n]) | |
################################################## | |
#### Code to generate gradient background END #### | |
################################################## | |
# date when Nifty began recovering (2020-05-18) | |
recovery_start_date = [*nifty['Date']][91] | |
# value as on recovery_start_date (8,823.25) | |
recovery_start_value = np.round(float(nifty.loc[nifty['Date'] == recovery_start_date, 'Close']), 2) | |
# % drop from top (12,125.9) to recovery_start_value (8,823.25) | |
recovery_pct_change_from_top = np.abs(np.round(((recovery_start_value / slump_start_value) - 1) * 100, 2)) | |
plt.annotate(text=f"Began recovering from Covid on\n{recovery_start_date} at "+ | |
f"{recovery_start_value:,}\nstill down {recovery_pct_change_from_top}% from the top", | |
xy=[92,8300],color='black', fontsize=11) | |
# bottom (7,610.25) | |
bottom = nifty.Close.min() | |
# % drop from top (12,125.9) to bottom (7,610.25) | |
bottom_pct_change_from_top = np.abs(np.round(((bottom / slump_start_value) - 1) * 100, 2)) | |
plt.annotate(text=f"Bottom at {bottom:,}\ndown {bottom_pct_change_from_top}%\nfrom the top", xy=[59,7500],color='black',fontsize=11) | |
# difference in days from (time delta) from slump to recovery | |
recovery_time = (datetime.strptime(recovery_start_date, '%Y-%m-%d') - datetime.strptime(slump_start_date, '%Y-%m-%d')).days | |
plt.annotate(text=f"{recovery_time}", xy=[61,11200],color='dimgray',fontsize=35, fontweight='bold') | |
plt.annotate(text="days of\ncarnage", xy=[59,10600],color='dimgray',fontsize=15, fontweight='bold') | |
plt.title("NIFTY'S JOURNEY THROUGH COVID-19", fontdict={'fontsize': 20, | |
'fontweight': 'bold', | |
'color': 'dimgray', | |
'verticalalignment': 'top'}, | |
loc='left'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment