0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

超初心者がPythonで5分足チャートから移動平均線を計算してグラフに表示してみた

Last updated at Posted at 2021-07-20

SMA=Simple Moving Agerage。移動平均線。作業は超簡単。

参考

以下で作成しているコードを数行変更するだけです。

コード

import pandas as pd
import datetime
import mplfinance as mpf

df = pd.read_csv('./temp_historical_data/USDJPY.csv', nrows=2000)
df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)

df5 = pd.DataFrame()
rule = '5T'
df5['Open'] = df['Open'].resample(rule).first()
df5['Close'] = df['Close'].resample(rule).last()
df5['High'] = df['High'].resample(rule).max()
df5['Low'] = df['Low'].resample(rule).min()

mpf.plot(df5, type='candle', mav=(5, 25), 
        datetime_format='%Y/%m/%d %H:%M', xrotation=90, style='yahoo', savefig=dict(fname='./figures/draw_sma.png',dpi=100))

グラフ

draw_sma.png

説明

mpf.plotの引数にmavを追加するだけ。便利すぎるナリ。計算不要。
ちなみにpandasの方を使って計算するには以下のようにする。

df5["SMA5"] = df5["Close"].rolling(window=5).mean()
df5["SMA25"] = df5["Close"].rolling(window=25).mean()

実際にはSMAの値も計算しておいてあれやこれやしたいと思うので、以下みたいな方がいいかもしれない?

df5 = pd.DataFrame()
rule = '5T'
df5['Open'] = df['Open'].resample(rule).first()
df5['Close'] = df['Close'].resample(rule).last()
df5['High'] = df['High'].resample(rule).max()
df5['Low'] = df['Low'].resample(rule).min()

sma = pd.DataFrame()
sma["SMA5"] = df5["Close"].rolling(window=5).mean()
sma["SMA25"] = df5["Close"].rolling(window=25).mean()

addplot = mpf.make_addplot(sma[['SMA5', 'SMA25']])
mpf.plot(df5, type='candle', addplot=addplot,
        datetime_format='%Y/%m/%d %H:%M', xrotation=90, style='yahoo', savefig=dict(fname='./figures/draw_sma.png',dpi=100))
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?