参考
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))
グラフ
説明
移動平均線と同時に表示したい場合は以下のようにする
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))
一緒に表示したグラフは以下。