0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】株価ドローダウンチャートの作成

Posted at

指数データをもとにドローダウンチャートを作成するコードです。

#ライブラリの読み込み

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from datetime import datetime
import seaborn as sns
sns.set()

#ETFデータの読み込み
NASDAQサイトで取得したcsvファイルを使ってますが、指数データであれば何でもよいです。

#あらかじめ以下のサイトから保存したCSVファイルの終値を一つにまとめる
#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

#ドローダウンチャート作成

#ドローダウンチャート
def dd_chart(df):

    #全ファンドのドローダウンを計算したdfDD_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']

    #チャートを作成
    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")

#実行

etfs = ['VTI','SPXL']
df = make_df(etfs)
dd_chart(df)

このようなグラフが作成されます。
dd_plot.png

0
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?