Technical Indicators MACD and Its Use for Financial Market Analysis with Python


MACD (Moving Average Convergence / Divergence) is a technical indicator that measures the strength of the price movement. It is made up of two MACD and Signal Lines and a Histogram. The author did it thinking about the daily charts, so he decided that they were 12 and 26 which is approximately the Moving Average of half a month and a month of stock trading days. As it is of the Oscillator type, it allows us to measure the momentum of trends, in addition to detecting overbought or oversold states, that is, when the trend has gone too far and is ready for a short- term consolidation [1].

The Moving Average of Convergence / Divergence (MACD)

MACD is commonly used by analyzing crossovers, divergences, and periods of steep slope (positive or negative). It is calculated through the Difference between two exponential moving average lines of 12 and 26 periods [2]. This difference can be seen on a separate chart (called the MACD line). It also has a 9-period moving average [1,3] line called the signal line (See Figure 1).

Figure 1: MACD and Signal Lines

So to understand how the MACD oscillator is built we can see that when the 2 (MA) [2] above approach the main line of the MACD approaches its zero line, the central line measures the difference between the two Moving Averages (MA) when they touch, the main line MACD will show zero, there is no distance between them (See Figure 2). On the contrary, when the MAs separate, the main line moves away from 0 either above or below depending on which (MA) is above the other, thus indicating a possible upward or downward trend [4].

Figure 2: MA in the MACD Behavior

The histogram, which are these bars that are seen on the MACD chart, is nothing more than the difference between the main and signal lines (See Figure 3) [4].

Figure 3: Histogram in MACD

With these three elements main line, signal line and histogram we can obtain information that can be incorporated into our trading system. The MACD is very versatile and serves both to detect trends and states of overbought or oversold. The most common signals that the MACD throws are the following: when the main line crosses the 0 either up or down it could be indicating a possible change in trend and that is when the fast (MA) the 12 is above the slow at 26, the main MACD line will be above 0 indicating that the (MA) are aligned for a possible uptrend (See Figure 4). Otherwise, if the fast is below the slow, the main MACD line will be below zero [4].

Figure 4: MACD in Overbought and Oversold Behavior

Traders will then look for a long position when the MACD line crosses the signal line from the bottom up, and will take a short position when the MACD line crosses the signal line from the top down. On the other hand, it is also possible to find valuable information on the divergence between the MACD line and the current price.

Divergences (See Figure 5) are another type of signals that the MACD offers us, a divergence occurs when the price chart offers new highs or new lows during a trend and the main line of the MACD does not accompany, that is, they do not make the new ones. Highs new lows and we have two types of divergence, the bearish and bullish divergence, the bearish divergence occurs when the main MACD line does not accompany making new maximums of the trend and in this case it is warning us that the uptrend is losing momentum or momentum and could be preparing to turn around, the bullish divergence which is just the opposite when the price chart is making new lows in a downtrend and the main MACD line does not accompany indicating loss of bearish momentum and possible exhaustion of the pure downtrend common sense because then because if a divergence occurs it means that the two (MA) [2] with which it is co It builds the MACD and generally those of 12 and 26 are getting progressively closer although new highs or lows are being produced which is a clear indication that the trend is losing strength I have used this signal a lot as confirmation of exhaustion patterns if you have a Exhaustion pattern with divergence in the MACD and breakout of the confirmation line is quite likely to produce some anti-trend movement.

Figure 5: MACD Divergence Behavior

Python implementation MACD

To create a program that uses MACD, we must first understand the ATR indicator. It is an instrument for determining the strength of the price movement. MACD is commonly used by analyzing crossovers, divergences, and periods of steep slope (positive or negative). It is made up of two MACD and Signal Lines.

These are the prerequisites for the program. Yahoo Finance API is used to download stock data, MACD is to calculate the indicator values. Matplotlib of course is to plot the data as a graph. Extracting closing price data of Yahoo Finance stock for the aforementioned time-period and Observe general price variation of the closing price for the give period. For this example, I have taken the 4 years of historical data of APY Yahoo Finance stock from 1st March 2017 to 1st Feb 2021.

We start by installing API Yahoo Finance pip install yahoo finance after importing libraries #importing variables

import pandas as pd

import numpy as np

import datetime as dt

import pandas_datareader as pdr import seaborn as sns

import matplotlib.pyplot as plt

#extracting data from Yahoo Finance API with two índices AAPN and NFLX from 1990 to date today. tickers = ['AAPL','NFLX']

all_data = pd.DataFrame()

test_data = pd.DataFrame()

no_data = []

for i in tickers: try:

test_data = pdr.get_data_yahoo(i, start = dt.datetime(1990,1,1), end = test_data['symbol'] = i

all_data = all_data.append(test_data)

except: no_data.append(i)

Now we will calculate MACD and Signal Lines. It’s calculated through the Difference between two exponential moving average lines of 12 and 26 periods and It also has a 9-period moving average line called the signal line.

all_data['12Ewm'] = all_data.groupby('symbol')['Close'].transform(lambda x: x.ewm(span=12, adjust=False).mean())

all_data['26Ewm'] = all_data.groupby('symbol')['Close'].transform(lambda x: x.ewm(span=26, adjust=False).mean())

all_data['MACD'] = all_data['26Ewm'] - all_data['12Ewm'] all_data['9Ewm']=all_data['MACD'].transform(lambda x: x.ewm(span=9, adjust=False).mean())

Now Plotting (MACD, MAs, Signal Line)

start = dt.datetime.strptime('2019-01-01', '%Y-%m-%d') end = dt.datetime.strptime('2019-12-31', '%Y-%m-%d') sns.set()

fig = plt.figure(facecolor = 'white', figsize = (20,10))

ax0 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4) ax0.plot(all_data[all_data.symbol=='AAPL'].loc[start:end,['Close','12Ewm','26Ewm']]) ax0.set_facecolor('ghostwhite')

ax0.legend(['Close','12Ewm','26Ewm'],ncol=3, loc = 'upper left', fontsize = 15) plt.title("Apple Price with MACD difference between slow and long indicator", fontsize = 20)

ax1 = plt.subplot2grid((6,4), (5,0), rowspan=1, colspan=4, sharex = ax0) ax1.plot(all_data[all_data.symbol=='AAPL'].loc[start:end,['MACD','9Ewm']])

ax1.legend(['MACD','9Ewm'],ncol=3, loc = 'upper left', fontsize = 12) ax1.set_facecolor('silver')

plt.subplots_adjust(left=.09, bottom=.09, right=1, top=.95, wspace=.20, hspace=0)

Other stocks closing price data of NASDAQ (National Association of Securities Dealers Automated Quotation) and Dow Jones (Dow Jones Industrial Average).


We have seen the amount of profits that an indicator as versatile as the MACD, it is widely used because it is simple and easy, since it provides information about the strength of the trend (up or down), but also about the strength of the trends (buy and sell) signals. Its disadvantage is that it is a Short-Term Indicator, since its longest average is 26 days, which could not be useful for long-term investments. As it is also a trend-following indicator, this means that the indicator communicates a signal when the trend takes place, not before it begins.


[1] CobuildLab 2021. Technical Indicators for Trading.

[2] CobuildLab 2021. Technical Specifically Moving Average and Its Use for Financial Market Analysis with python.

[3] Implementing MACD in Python python-cc9b2280126a. 2020

[4] FD Life&trading Portal. El Indicador MACD. 2019.