MACD, or Moving Average Convergence Divergence, is a momentum indicator that compares a short-term exponential moving average with a long-term exponential moving average. It helps identify potential buying or selling opportunities through momentum and crossover signals. section 10.2.2
Calculate and interpret MACD through three related series:
- MACD line: subtract the 26-period EMA from the 12-period EMA. section 10.2.2
- Signal line: calculate a 9-period EMA of the MACD line. section 10.2.2
- Histogram: plot the difference between the MACD and signal lines; values above zero indicate bullish momentum, while values below zero indicate bearish momentum. section 10.2.2
- Treat crossovers as signals: a MACD line crossing above the signal line is bullish, while a crossing below it is bearish. section 10.2.2
Listing 10.5 Moving Average Convergence Divergence
import pandas as pd
import matplotlib.pyplot as plt
def calculate_macd(data, short_window=12, long_window=26, signal_window=9):
data['EMA_12'] = data['Close'].ewm(
span=short_window, adjust=False).mean() #1
data['EMA_26'] = data['Close'].ewm(
span=long_window, adjust=False).mean() #1
data['MACD'] = data['EMA_12'] - data['EMA_26'] #1
data['Signal_Line'] = data['MACD'].ewm(
span=signal_window, adjust=False).mean() #1
return data
def plot_macd(data):
plt.figure(figsize=(12,6))
plt.plot(data.index, data['MACD'], label='MACD', color='blue')
plt.plot(data.index, data['Signal_Line'],
label='Signal Line', color='red')
plt.bar(data.index, data['MACD'] - data['Signal_Line'],
label='Histogram', color='gray', alpha=0.5)
plt.legend(loc='best')
plt.title('MACD Indicator')
plt.xlabel('Date')
plt.ylabel('MACD Value')
plt.grid()
plt.show()
import yfinance as yf
ticker = "NVDA"
df = yf.Ticker(ticker).history(start="2024-01-01")
df = calculate_macd(df)
plot_macd(df)
The implementation calculates the 12- and 26-period EMAs with pandas, derives the MACD and signal line, and plots the histogram. section 10.2.2
Crossovers are historical indicators rather than guarantees. A signal can produce losses when a broader strong uptrend makes a sell crossover misleading, so MACD signals require cautious interpretation and later backtesting. section 10.2.2
