Stock パフォーマンスの解析

In [1]:
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
In [13]:
def drawdowns(R):
    """
    R: indexが日付でvalueがリターンであるSeriesかDataFrame
    """
    price = (1+R).cumprod()
    return (price.cummax() - price) / price.cummax()

def plotPrice(dailyPrice, filename=None, title="Stock chart", ylog=False, figsize=(5,4)):
    """
    チャートを描画する
    dailyReturn: 描画したい株価のdataframe or Series
    """
    if type(dailyPrice) is pd.Series:
        dailyPrice = pd.DataFrame(dailyPrice)

    plt.style.use('ggplot')
    fig = plt.figure(figsize=figsize, facecolor="white")
    ax = fig.add_subplot()
    for x in dailyPrice.columns.values:
        y = dailyPrice[x]
        ax = plt.plot(y)
    
    # legend
    ax = plt.legend(dailyPrice.columns.values)
    
    # labels
    ax = plt.xlabel("Date")
    ax = plt.xticks(rotation=45)
    ax = plt.ylabel("Return")
    ax = plt.title(title)
    
    # axes
    if ylog: # 変化量が大きいときはlog scaleに。
        plt.yscale('log')
        
    if filename is not None:
        plt.savefig(filename)
In [9]:
sp500 = yf.download("^GSPC", start="1950-01-01")
[*********************100%***********************]  1 of 1 completed
In [16]:
plotPrice(sp500["Adj Close"], ylog=True, figsize=(10,6))
In [20]:
sp500_return = sp500["Adj Close"].pct_change()
sp500_dd = drawdowns(sp500_return)
plotPrice(1-sp500_dd, title="S&P500 drawdown", figsize=(10,6))