Help us understand the problem. What is going on with this article?

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

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

ライブラリの読み込み

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした