はじめに
yfinanceで取得した株価データを使って、ローソク足、出来高、移動平均線をグラフにしたい場合、mplfinance
を使うと簡単に出力できる。
目次
株価を取得する
株価の取得にはyfinance
のライブラリを使う。yf.download
で取得できる。各パラメータは下記の通り。
内容 | パラメータ | 指定する値 |
---|---|---|
銘柄 | tickers | 銘柄のシンボルを指定。 |
取得期間 | period | 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max |
取得間隔 | interval | 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo |
開始時期 | start | YYYY-MM-DD |
終了時期 | end | YYYY-MM-DD |
yf_example
import yfinance as yf
# 最大期間取得
stock_AAPL = yf.download(tickers="AAPL", period="max")
print(stock_AAPL)
# [*********************100%***********************] 1 of 1 completed
# Price Close High Low Open Volume
# Ticker AAPL AAPL AAPL AAPL AAPL
# Date
# 1980-12-12 0.098726 0.099155 0.098726 0.098726 469033600
# 1980-12-15 0.093575 0.094005 0.093575 0.094005 175884800
# ... ... ... ... ... ...
# 2025-05-01 213.320007 214.559998 208.899994 209.080002 57365700
# 2025-05-02 205.350006 206.990005 202.160004 206.089996 100912500
yfinance
の使い方の詳細は下記の記事を参照。
グラフにする
mplfinance
にパラメータを設定すると、簡単にグラフができる。
注意点として、yfinanceで株価を取得する際、データフレームのヘッダを取り除くためmulti_level_index=False
を指定して👇のTicker行を削除する。そうしないと、「float か int のデータじゃない。」というエラーが出る。
Price Close High Low Open Volume
Ticker AAPL AAPL AAPL AAPL AAPL
Date
1980-12-12 0.098726 0.099155 0.098726 0.098726 469033600
-----
raise ValueError('Data for column "'+str(col)+'" must be ALL float or int.')
ValueError: Data for column "Open" must be ALL float or int.
パラメータ | 意味 |
---|---|
title | グラフのタイトル |
type | 表示タイプ 'candle' , 'line'など |
volume | 出来高 True or False |
mav | 移動平均線 日数を並べる 例は 300日 1000日 |
style | 表示スタイル |
import yfinance as yf
import mplfinance as mpf
# 株価取得
stock_AAPL = yf.download(tickers="AAPL", period="max",multi_level_index=False)
# チャートの描画
mpf.plot(stock_AAPL, title='AAPL', type='candle', volume=True , mav=(300, 1000) ,style='yahoo')
期間を絞りたい場合は、株価の日時を絞れは良い。yf.download()
の取得時点で日時を絞っても良いし、下記のように取得したデータフレームを日付でフィルタしても良い。
import yfinance as yf
import mplfinance as mpf
# 株価取得
stock_AAPL = yf.download(tickers="AAPL", period="max",multi_level_index=False)
# 2025年01月01日~2025年05月01日のデータにフィルタ
stock_AAPL = stock_AAPL.loc["2025-01-01":"2025-05-01"]
# ローソク足チャートの描画
mpf.plot(stock_AAPL, type='candle', volume=True, title='AAPL', mav=(5,10,20),style='yahoo')
パラメータの詳細はmpf.kwarg_help('plot')
で確認できる。
パラメータの詳細はこちら。
mpf.kwarg_help('plot') # 一覧出力
print(f'style:{mpf.available_styles()}') # スタイル一覧
------------------------------------------------------------------------------
Kwargs for func_name "plot":
Kwarg Default Description
------------------------ ------- -----------------------------------------------
columns None Column names to be used when plotting the data.
Default: ("Open", "High", "Low", "Close",
"Volume")
type 'ohlc' Plot type: ['candle', 'ohlc', 'line', 'renko',
'pnf', 'hollow_and_filled', 'candlestick',
'ohlc_bars', 'hollow_candle', 'hollow', 'hnf']
style None plot style; see `mpf.available_styles()`
volume False Plot volume: True, False, or set to Axes object
on which to plot.
mav None Moving Average window size(s); (int or tuple of
ints)
ema None Exponential Moving Average window size(s); (int
or tuple of ints)
mavcolors None color cycle for moving averages (list or tuple
of colors)(overrides mpf style mavcolors).
renko_params {} dict of renko parameters; call
`mpf.kwarg_help("renko_params")`
pnf_params {} dict of point-and-figure parameters; call
`mpf.kwarg_help("pnf_params")`
study None kwarg not implemented
marketcolor_overrides None sequence of color objects to override market
colors.sequence must be same length as ohlc(v)
DataFrame. Eachcolor object may be a color,
marketcolor object, or None.
mco_faceonly False True/False marketcolor_overrides only apply to
face of candle.
no_xgaps True deprecated
show_nontrading False True/False show spaces for non-trading
days/periods
figscale None Scale figure size up (if > 1) or down (if < 1)
figratio None Aspect ratio of the figure. Default:
(8.00,5.75)
figsize None Figure size: overrides both figscale and
figratio, else defaults to figratio*figscale
fontscale None Scale font sizes up (if > 1) or down (if < 1)
linecolor None Line color for `type=line`
title None Figure Title (see also `axtitle`)
axtitle None Axes Title (subplot title)
xlabel None label for x-axis of plot
ylabel 'Price' label for y-axis of main plot
ylabel_lower None label for y-axis of volume
addplot None addplot object or sequence of addplot objects
(from `mpf.make_addplot()`)
savefig None file name, or BytesIO, or dict with key `fname`
plus other keys allowed as kwargs to
matplotlib `Figure.savefig()`
block None True/False wait for figure to be closed before
returning
returnfig False return Figure and list of Axes objects created
by mplfinance; user must display plot when
ready, usually by calling `mpf.show()`
return_calculated_values None set to a variable containing an empty dict;
`mpf.plot()` will fill the dict with various
mplfinance calculated values
set_ylim None deprecated
ylim None Limits for y-axis as tuple (min,max), i.e.
(bottom,top)
xlim None Limits for x-axis as tuple (min,max), i.e.
(left,right)
set_ylim_panelB None deprecated
hlines None Draw one or more HORIZONTAL LINES across entire
plot, by specifying a price, or sequence of
prices. May also be a dict with key `hlines`
specifying a price or sequence of prices, plus
one or more of the following keys: `colors`,
`linestyle`, `linewidths`, `alpha`.
vlines None Draw one or more VERTICAL LINES across entire
plot, by specifying a date[time], or sequence
of date[time]. May also be a dict with key
`vlines` specifying a date[time] or sequence of
date[time], plus one or more of the following
keys: `colors`, `linestyle`, `linewidths`,
`alpha`.
alines None Draw one or more ARBITRARY LINES anywhere on
the plot, by specifying a sequence of two or
more date/price pairs, or by specifying a
sequence of sequences of two or more date/price
pairs. May also be a dict with key `alines` (as
date/price pairs described above), plus one or
more of the following keys: `colors`,
`linestyle`, `linewidths`, `alpha`.
tlines None Draw one or more TREND LINES by specifying one
or more pairs of date[times] between which each
trend line should be drawn. May also be a dict
with key `tlines` as just described, plus one
or more of the following keys: `colors`,
`linestyle`, `linewidths`, `alpha`,
`tline_use`,`tline_method`.
panel_ratios None sequence of numbers indicating relative sizes
of panels; sequence len must be same as number
of panels, or len 2 where first entry is for
main panel, and second entry is for all other
panels
main_panel 0 integer - which panel is the main panel for
`.plot()`
volume_panel 1 integer - which panel is the volume panel
num_panels None total number of panels
datetime_format None x-axis tick format as valid `strftime()` format
string
xrotation 45 Angle (degrees) for x-axis tick labels;
90=vertical
axisoff False `axisoff=True` means do NOT display any axis.
closefig 'auto' True|False close the Figure before returning
fill_between None fill between specification as y-value, or
sequence of y-values, or dict containing key
"y1" plus any additional kwargs for
`fill_between()`
tight_layout False True|False implement tight layout (minimal
padding around Figure) (see also
`scale_padding` kwarg)
scale_padding 1.0 Increase, > 1.0, or decrease, < 1.0, padding
around figure. May also be a dict containing
one or more of the following keys: "top",
"bottom", "left", "right", to individual scale
padding on each side of Figure.
width_adjuster_version 'v1' specify version of object width adjustment
algorithm: "v0" or "v1" (See also "widths"
tutorial in mplfinance examples folder).
scale_width_adjustment None scale width of plot objects wider, > 1.0, or
narrower, < 1.0 may also be a dict to scale
individual widths. (See also "widths" tutorial
in mplfinance examples folder).
update_width_config None dict - update individual items in width
configuration. (See also "widths" tutorial in
mplfinance examples folder).
return_width_config None empty dict variable to be filled with width
configuration settings.
saxbelow True set the volume Axes below (behind) all other
Axes objects
ax None Matplotlib Axes object on which to plot
volume_exponent None integer exponent on the volume axis (or set to
"legacy" for old mplfinance style)
tz_localize True True|False localize the times in the
DatetimeIndex
yscale None y-axis scale: "linear", "log", "symlog", or
"logit"
volume_yscale None Volume y-axis scale: "linear", "log", "symlog",
or "logit"
volume_ylim None Volume y-axis limits as tuple (min,max), i.e.
(bottom,top)
volume_alpha None opacity for Volume bar: 0.0 (transparent) to
1.0 (opaque)
warn_too_much_data 599 Tolerance for data amount in plot. Default=599
rows. Values greater than 'warn_too_much_data'
will trigger a warning.
style:['binance', 'binancedark', 'blueskies', 'brasil', 'charles', 'checkers', 'classic', 'default', 'ibd', 'kenan', 'mike', 'nightclouds', 'sas', 'starsandstripes', 'tradingview', 'yahoo']
以上