[Python] Creating a stock price drawdown chart

Code to create a drawdown chart based on exponential data.

Loading the library

python


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

Read ETF data

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

Drawdown chart creation

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")

Run

python


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

A graph like this is created. dd_plot.png

Recommended Posts

[Python] Creating a stock price drawdown chart
"Creating a stock price dataset" and "Implementing AR (1)"
Get stock price with Python
Python: Stock Price Forecast Part 1
[Python] My stock price forecast [HFT]
Write a pie chart in Python
[Python] Creating a scraping tool Memo
Precautions when creating a Python generator
[Python] Chapter 03-01 turtle graphics (creating a turtle)
Creating a simple PowerPoint file with Python
Download Japanese stock price data with python
Creating a python virtual environment on Windows
python: Creating a ramen timer (pyttsx3, time)
Ubuntu18.04.05 Creating a python virtual environment in LTS
Procedure for creating a LineBot made with Python
Get stock price data with Quandl API [Python]
Commands for creating a python3 environment with virtualenv
Procedure for creating a Python quarantine environment (venv environment)
A memo for creating a python environment by a beginner
Let's do web scraping with Python (stock price)
Python & Machine Learning Study Memo ⑦: Stock Price Forecast
Get the stock price of a Japanese company with Python and make a graph
[Grasshopper] When creating a data tree on Python script
Try creating a compressed file using Python and zlib
Notes on creating a python development environment on macOS Catalina
Problems when creating a csv-json conversion tool with python
Store the stock price scraped by Python in the DB
[Time series with plotly] Dynamic visualization with plotly [python, stock price]
[Piyopiyokai # 1] Let's play with Lambda: Creating a Python script
A * algorithm (Python edition)
[Python] Take a screenshot
Creating a Home screen
4. Creating a structured program
A python lambda expression ...
Daemonize a Python process
Creating a scraping tool
Stock Price Forecast 2 Chapter 2
Create a Python environment
Creating a dataset loader
Python3> round (a --b, 7)
Stock Price Forecast 1 Chapter 1
Programming history 1 month Extract NY Dow stock price with Python!
Creating a Python script that supports the e-Stat API (ver.2)
A memo when creating a directed graph using Graphviz in Python
[Python] What a programming inexperienced person did before creating a tool