[PYTHON] Display candlestick chart, volume, moving average, Bollinger band with mplfinance

Let's display a common chart with mplfinance.

Take Locondo (3358), which has increased 3.5 times in 3 months, as an example. The environment is Google Colaboratory.

Advance preparation

Create a method that can get stock price data with stooq.

import pandas as pd
import pandas_datareader.data as pdr
import numpy as np
from pandas.testing import assert_frame_equal

def makeDataFrame(code):
  df_temp = pdr.DataReader("{}.JP".format(code), "stooq")
  df = df_temp.loc[:,['Open','High','Low','Close','Volume']].sort_values('Date')
  return df

Verification Get the data for the last 100 business days.

df = makeDataFrame(3558).tail(100)
df.tail()

スクリーンショット 2020-08-29 14.07.00.png

mplfinance installation

Install with pip. スクリーンショット 2020-08-29 13.49.59.png

Display candlestick chart

You can display it just by specifying the type and plotting.

import mplfinance as mpf
mpf.plot(df, type='candle')

スクリーンショット 2020-08-29 13.46.06.png

Show volume

Just add the option volume = True.

スクリーンショット 2020-08-29 13.47.42.png

Display moving average line

The moving average line can be displayed by specifying the date with the mav option. This is an example of displaying the 5, 25, 75 day line.

mpf.plot(df, type='candle', mav=(5, 25, 75), volume=True)

スクリーンショット 2020-08-29 14.00.05.png

Bollinger Bands display

Installation of pyti library

Install the library pyti that calculates Bollinger Bands.

スクリーンショット 2020-08-29 13.50.58.png

Bollinger Bands Calculation

Calculate at reference line 20.

from pyti.bollinger_bands import upper_bollinger_band as bb_up
from pyti.bollinger_bands import middle_bollinger_band as bb_mid
from pyti.bollinger_bands import lower_bollinger_band as bb_low

data = df['Close'].values.tolist()
period = 20
bb_up = bb_up(data,period)
bb_mid = bb_mid(data,period)
bb_low = bb_low(data,period)
df['bb_up'] = bb_up
df['bb_mid'] = bb_mid
df['bb_low'] = bb_low

Verification

Let's plot and check if it can be calculated. スクリーンショット 2020-08-29 13.54.11.png

Display with mplfinance

By default, mplfinance only recognizes'Open',' High',' Low',' Close', and'Volume'. Make mplfinance recognize the item you want to add with make_addplot. When displaying, specify the items to be displayed together with the option of addplot.

apd = mpf.make_addplot(df[['bb_up', 'bb_mid', 'bb_low']])
mpf.plot(df, type='candle', addplot=apd, volume=True)

スクリーンショット 2020-08-29 13.57.58.png

Recommended Posts

Display candlestick chart, volume, moving average, Bollinger band with mplfinance
Candlestick chart and moving average plot
Moving average with numpy
I tried to implement a volume moving average with Quantx