2
8

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分足チャートからMACDを計算してグラフに表示してみた

Last updated at Posted at 2021-07-20

参考

MACDの計算部分以外は以下とほぼ一緒!

コード

import pandas as pd
import datetime
import mplfinance as mpf

df = pd.read_csv('./temp_historical_data/USDJPY.csv', nrows=500)
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()

macd = pd.DataFrame()
macd['Close'] = df5['Close']
macd['EMA12'] = df5['Close'].ewm(span=12).mean()
macd['EMA26'] = df5['Close'].ewm(span=26).mean()
macd['MACD'] = macd['EMA12'] - macd['EMA26']
macd['Signal'] = macd['MACD'].ewm(span=9).mean()
macd.head()

macdplot = mpf.make_addplot(macd[['MACD', 'Signal']])

mpf.plot(df5, type='candle', addplot=[macdplot],
        datetime_format='%Y/%m/%d %H:%M', xrotation=90, style='yahoo', savefig=dict(fname='./figures/draw_macd.png',dpi=100))

グラフ

draw_macd.png

説明

移動平均線と同時に表示したい場合は以下のようにする


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

# 中略

smaplot = mpf.make_addplot(sma[['SMA5', 'SMA25']])

mpf.plot(df5, type='candle', addplot=[smaplot, macdplot],
        datetime_format='%Y/%m/%d %H:%M', xrotation=90, style='yahoo', savefig=dict(fname='./figures/draw_macd.png',dpi=100))

一緒に表示したグラフは以下。

draw_macd.png

2
8
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
2
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?