Technical Analysis | Mastering MACD Calculation in Python

Discover how to leverage Python to compute the MACD indicator and optimize your trading decisions

In this blog, we will cover the below topics

  • What are technical indicators?
  • What is the Moving Average Convergence Divergence?
  • How to access the data from yahoo finance?
  • How to build MACD and visualize it in Python?
  • How to interpret MACD and its limitation?

What are technical indicators?

The technical indicators are mathematical calculations that are carried out on historical data such as open, price, volume, etc that indicate the potential sell or buy proposition. It is widely used in technical analysis and by active traders to analyze price movements and make a profit by timing the entry and exit points. There are various technical indicators and most popular being moving averages, RSI, MACD, and Bollinger Bands. Our focus in this blog will be to explore the MACD.

What is the Moving Average Convergence Divergence (MACD) indicator?

The MACD is based on the relationship between two moving price averages of a given asset. It was developed by Gerald Appel in 1979 and since then it has become the most widely used technical indicator to track emerging price trends, upwards or downward. The MACD comprises 3 components.

MACD: The difference between the 26-day EMA and the 12-day EMA. The blue line in the below chart.

Signal line: The exponential moving average (EMA) for the previous 9 days of the MACD line. The orange line in below the chart.

Histogram: It is the difference between the MACD line and the signal line, oscillating around a zero line. The size of the histogram bars shows how fast the price is moving and its direction.

A typical stock price trend and MACD and signal line look as below. We will develop a similar plot using Python in the subsequent sections of this blog.

Source: Investopedia | Fig 1

How to access the data from yahoo finance?

We will use yahoo finance to load the stock data and use standard Python libraries like pandas and numpy.

import pandas as pd
import numpy as np
import yfinance as yf
import yahoo_fin.stock_info as si
import matplotlib.pyplot as plt
from plotly.subplots import make_subplots
import plotly.graph_objects as go

Accessing data from Yahoo Finance

We will set the stock name and period for data extraction.

ticker = 'MSFT'
start_date = '2022-01-01'
end_date = '2023-01-01'

df = yf.Ticker(ticker).history(start= start_date,
end=end_date)[['Open', 'High', 'Low', 'Close', 'Volume']]
print(df)
Open         High       Low       Close     Volume
Date
2021-12-31 176.548233 177.678363 175.725416 176.032745 64062300
2022-01-03 176.290475 181.296759 176.171519 180.434280 104487900
2022-01-04 181.048914 181.356227 177.569291 178.144272 99310400
2022-01-05 178.055086 178.610235 173.128111 173.405685 94537600
2022-01-06 171.204893 173.782390 170.154072 170.510956 96904000
... ... ... ... ... ...
2022-12-23 130.539854 132.035499 129.263572 131.477127 63814900
2022-12-27 130.998521 131.028433 128.346242 129.652435 69007800
2022-12-28 129.293476 130.649527 125.504514 125.674019 85438400
2022-12-29 127.618359 130.101127 127.359119 129.233658 75703700
2022-12-30 128.037144 129.572665 127.059986 129.552719 77034200
    fig.add_trace(go.Candlestick(
x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
increasing_line_color='green',
decreasing_line_color='red',
showlegend=False
),row=1, col=1, secondary_y=True,
)
fig.add_trace(go.Bar(
x= df.index,
y= df['Volume'],
marker_color='Navy',
showlegend=False,
), row=1, col=1,secondary_y=False,
)
Source: Author | Fig 2

Calculating the MACD

The calculation involves a series of exponential moving averages (EMA) and their differences

  1. Exponential Moving Average — 12 days
emv_12 = df['Close'].ewm(span=12, adjust=False, min_periods=12).mean()

2. Exponential Moving Average — 26 days

emv_26 = df['Close'].ewm(span=26, adjust=False, min_periods=26).mean()

3. Calculate MACD

macd = emv_12 - emv_26

4. Calculate the signal line — EMV of 9 days

signal = macd.ewm(span=9, adjust=False, min_periods=9).mean()

5. Calculate the trigger for convergence and divergence

macd_cross = macd - signal

6. Brind it all together in a data frame

df['macd'] = df.index.map(macd)
df['macd_cross'] = df.index.map(macd_cross)
df['signal'] = df.index.map(signal)

Visualizing the MACD indicator

We will add all 3 components namely macd, macd_s, and the histogram to the previous chart.

fig.append_trace(
go.Scatter(
x=df.index,
y=df['macd'],
line=dict(color='#ff9900', width=2),
name='macd',
# showlegend=False,
legendgroup='2',
), row=2, col=1
)
fig.append_trace(
go.Scatter(
x=df.index,
y=df['signal'],
line=dict(color='#000000', width=2),
# showlegend=False,
legendgroup='2',
name='signal'
), row=2, col=1
)
colors = np.where(df['macd_cross'] < 0, '#000', '#ff9900')
# Plot the histogram
fig.append_trace(
go.Bar(
x=df.index,
y=df['macd_cross'],
name='histogram',
marker_color=colors,
showlegend=False,
), row=2, col=1
)
Source: Author | Fig 3

We have built various components have the chart. Let’s build a consolidated chart with price trends, volume, MACD, signal, and a histogram chart at the bottom. The complete code can be accessed from the GitHub

Source: Author | Fig 4

How to use the MACD indicator?

  • If the MACD line crosses from below to above the signal line, the indicator is considered bullish. The further below the zero line the stronger the signal.
  • The indicator is considered bearish if the MACD line crosses from above to below the signal line. The further above the zero line the stronger the signal.

Limitation of the MACD indicator

  • The MACD generates a lot of positive reversal but when verified with other indicators it is found to be false positive.
  • It is also considered a lagging indicator meaning the reversal or change in trend shows up a little late due to its inherent nature.
  • It works best in trending markets but in case of a slow trend or sideways movement, it tends to indicate a false positive.

The MACD indicator alone is not enough to make trade decisions. It is recommended that MACD should be used in conjunction with other indicators like RSIBollinger bands, Moving average, ADX, DMI, and Fibonacci retracement to confirm the trend changes and build trading strategies.

Closing thoughts

The MACD indicator comprises 3 lines each representing a trend and momentum based on a specific period. Although MACD is a momentum oscillator, it is not used to identify the overbought or oversold conditions, unlike the RSI indicator. Traders and analysts use the MACD to track the recent momentum in stock prices that signal a change in the underlying trend and decide on enter or exit position.

I hope you liked the article and found it helpful.

You can connect with me — on Linkedin and Github

Disclaimer

The blog is only educational and should not be used as professional advice for real-world financial decisions.

References

Investopedia

Leave a Reply

Your email address will not be published. Required fields are marked *