Code to create a drawdown chart based on exponential data.
python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
import seaborn as sns
sns.set()
I am using the csv file obtained from the NASDAQ site, but any exponential data will do.
python
#Combine the closing prices of CSV files saved from the following sites in advance into one
#https://www.nasdaq.com/market-activity/funds-and-etfs/vti/historical
def make_df(etfs):
df = pd.DataFrame()
for etf in etfs:
csvfile = etf +'.csv'
csv_data = pd.read_csv(csvfile)
csv_data.Date = pd.to_datetime(csv_data.Date)
csv_data = csv_data.set_index('Date')
csv_data= csv_data.rename(columns={' Close/Last': etf})
df[etf] = csv_data[etf]
df = df.sort_index().dropna()
return df
python
#Drawdown chart
def dd_chart(df):
#DfDD calculated drawdown for all funds_Create all
dfDD_all = pd.DataFrame()
for i in range(0,df.shape[1]):
dfDD = pd.DataFrame(df.iloc[:,i])
dfDD['max'] = dfDD.iloc[:,0].cummax()
dfDD[dfDD.columns[0]+'_DD'] = dfDD.iloc[:,0] / dfDD['max'] -1
dfDD_all[dfDD.columns[0]+'_DD'] = dfDD[dfDD.columns[0]+'_DD']
#Create a chart
fig = plt.figure()
dfDD_all.plot(figsize = (15, round(dfDD_all.shape[1]/2+0.4,0)*5), subplots=True,
layout=(-1, 2),sharey=True, title ='Drawdown')
plt.savefig('dd_plot.png',bbox_inches="tight")
python
etfs = ['VTI','SPXL']
df = make_df(etfs)
dd_chart(df)
A graph like this is created.
Recommended Posts