Skip to content

Instantly share code, notes, and snippets.

@yongghongg
Created July 24, 2022 10:52
Show Gist options
  • Save yongghongg/17d0902e40f2ffea036871a33f071d04 to your computer and use it in GitHub Desktop.
Save yongghongg/17d0902e40f2ffea036871a33f071d04 to your computer and use it in GitHub Desktop.
# Add MACD as subplot
def MACD(df, window_slow, window_fast, window_signal):
macd = pd.DataFrame()
macd['ema_slow'] = df['Close'].ewm(span=window_slow).mean()
macd['ema_fast'] = df['Close'].ewm(span=window_fast).mean()
macd['macd'] = macd['ema_slow'] - macd['ema_fast']
macd['signal'] = macd['macd'].ewm(span=window_signal).mean()
macd['diff'] = macd['macd'] - macd['signal']
macd['bar_positive'] = macd['diff'].map(lambda x: x if x > 0 else 0)
macd['bar_negative'] = macd['diff'].map(lambda x: x if x < 0 else 0)
return macd
macd = MACD(df, 12, 26, 9)
macd_plot = [
mpf.make_addplot((macd['macd']), color='#606060', panel=2, ylabel='MACD', secondary_y=False),
mpf.make_addplot((macd['signal']), color='#1f77b4', panel=2, secondary_y=False),
mpf.make_addplot((macd['bar_positive']), type='bar', color='#4dc790', panel=2),
mpf.make_addplot((macd['bar_negative']), type='bar', color='#fd6b6c', panel=2),
]
mpf.plot(df, type='candle', volume=True, addplot=macd_plot)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment