mplfinance

mplfinanceとはファイナンスデータを可視化するためのmatplotlibの拡張です。今回はこれを使って、金融データからグラフを作ってみようと思います。基本的な使い方はmplfinanceのリポジトリの『Tutorial』にて説明されており、これをみながらグラフを作ってみます。

mplfinance is an extension to matplotlib for visualizing finance data. In this article, we will try to create a graph from financial data using mplfinance. The basic usage is explained in the “Tutorial” in the mplfinance repository.

Loading Data

import os
import time
import pandas as pd
import pandas_datareader.data as web
from pandas_datareader._utils import RemoteDataError
def get_finance_data(
    ticker_symbol: str, start="2021-01-01", end="2021-06-30", savedir="data"
) -> pd.DataFrame:
    """Retrieves data recording stock prices

    Args:
        ticker_symbol (str): Description of param1
        start (str): Date of beginning of period, optional.
        end (str): Date of end of period, optional.

    Returns:
        res: Stock Price Data

    """
    res = None
    filepath = os.path.join(savedir, f"{ticker_symbol}_{start}_{end}_historical.csv")
    os.makedirs(savedir, exist_ok=True)

    if not os.path.exists(filepath):
        try:
            time.sleep(5.0)
            res = web.DataReader(ticker_symbol, "yahoo", start=start, end=end)
            res.to_csv(filepath, encoding="utf-8-sig")
        except (RemoteDataError, KeyError):
            print(f"ticker_symbol ${ticker_symbol} が正しいか確認してください。")
    else:
        res = pd.read_csv(filepath, index_col="Date")
        res.index = pd.to_datetime(res.index)

    assert res is not None, "データ取得に失敗しました"
    return res
# ticker symbol, period, and destination file
ticker_symbol = "NVDA"
start = "2021-01-01"
end = "2021-06-30"

df = get_finance_data(ticker_symbol, start=start, end=end, savedir="../data")
df.head()

HighLowOpenCloseVolumeAdj Close
Date
2020-12-31131.509995129.149994131.365005130.55000319242400.0130.413864
2021-01-04136.524994129.625000131.042496131.13499556064000.0130.998245
2021-01-05134.434998130.869995130.997498134.04750132276000.0133.907700
2021-01-06132.449997125.860001132.225006126.14499758042400.0126.013443
2021-01-07133.777496128.865005129.675003133.44000246148000.0133.300842

Plotting OHLC

OHLC is the opening price, high, low, and close, and is one of the graphs we usually look at most often. Let’s plot it as a candlestick and as a line.

import mplfinance as mpf

mpf.plot(df, type="candle", style="starsandstripes", figsize=(12, 4))
mpf.plot(df, type="line", style="starsandstripes", figsize=(12, 4))

png

png

Moving Average

One of the indicators used in technical analysis of stock prices and foreign exchange is the moving average. In current technical analysis, there are many examples where three moving averages (short, medium, and long term) are displayed simultaneously. In daily charts, the 5-day, 25-day, and 75-day moving averages are often used.

Specify the mav option to plot the 5/25/75 day moving average.

mpf.plot(df, type="candle", style="starsandstripes", figsize=(12, 4), mav=[5, 25, 75])

png

Show legend

Add a legend because it is difficult to tell which line represents a moving average over what number of days.

import japanize_matplotlib
import matplotlib.patches as mpatches

fig, axes = mpf.plot(
    df,
    type="candle",
    style="starsandstripes",
    figsize=(12, 4),
    mav=[5, 25, 75],
    returnfig=True,
)
fig.legend(
    [f"{days} days" for days in [5, 25, 75]], bbox_to_anchor=(0.0, 0.78, 0.28, 0.102)
)
<matplotlib.legend.Legend at 0x7f8be96e5b80>

png

Displaying Volume

fig, axes = mpf.plot(
    df,
    title="NVDA 2021/1/B~2021/6/E",
    type="candle",
    style="starsandstripes",
    figsize=(12, 4),
    mav=[5, 25, 75],
    volume=True,
    datetime_format="%Y/%m/%d",
    returnfig=True,
)
fig.legend(
    [f"{days} days" for days in [5, 25, 75]], bbox_to_anchor=(0.0, 0.78, 0.28, 0.102)
)

png

fig, axes = mpf.plot(
    df,
    title="NVDA 2021/1/B~2021/6/E",
    type="candle",
    style="yahoo",
    figsize=(12, 4),
    mav=[5, 25, 75],
    volume=True,
    datetime_format="%Y/%m/%d",
    returnfig=True,
)
fig.legend(
    [f"{days} days" for days in [5, 25, 75]], bbox_to_anchor=(0.0, 0.78, 0.28, 0.102)
)

png

Comments

(Comments will appear after approval)