,

Mastering the MACD Indicator and MACD Divergence

Posted by

MACD Indicator
Table of Contents

    Introduction

    The Moving Average Convergence/Divergence (MACD) is a powerful oscillator study in technical analysis. It measures the difference between two exponential moving averages of varying lengths. Additionally, a trailing moving average of the MACD, often referred to as the “Signal Line”, “Trigger” line or MACDA, is plotted. The indicator was defined with its default parameter values by Gerald Appel.

    It is a highly effective tool for trend following. When the MACD crosses 0, it signifies that the shorter, more sensitive moving average is crossing over the longer, slower moving average. This can indicate a change in the market environment, such as the emergence of a new trend or a trend reversal.

    The MACD generates two types of trading signals. A cross above zero generates a buy signal, while a cross below zero is a sell signal. Additionally, a cross of the MACD and the MACDA can be used to generate buy and sell signals. This technique can effectively identify the resumption of a trend when the MACD does not cross 0.

    This indicator is an unbounded study, meaning it can follow the market as long as the trend is gaining momentum. However, defining specific overbought/oversold (OB/OS) levels can be challenging due to this unbounded nature. Therefore, it’s recommended not to trade against the MACD simply because it is OB or OS. Instead, one should wait to see deterioration in its behaviour, which can be done by paying greater attention to the MACDA.

    The MACD is also used as a divergence-based indicator. Studies such as MACD Divergence, linked to MACD Steps, can provide further definition in identifying true divergence. This makes it a valuable tool for identifying potential trend continuations and reversals, a key aspect of the MACD strategy.

    In the following sections, we will explore how to calculate the MACD, identify MACD divergences, determine the best MACD settings for day trading, and compare MACD vs RSI. We will also provide a MACD divergence cheat sheet and delve into coding the MACD indicator in Python using VSCode.

    The Birth of the Indicator

    The MACD indicator is a brainchild of Gerald Appel, a renowned technical analyst and trader. Appel introduced the MACD in the late 1970s as a tool to identify changes in the market environment, such as the start of a new trend or a potential trend reversal. The MACD was designed to capture the dynamics between two exponential moving averages, thereby offering traders a more nuanced understanding of market momentum.

    The MACD’s inception was driven by the need for a reliable, easy-to-interpret tool that could provide actionable trading signals. Appel’s creation was a response to this need, and the MACD quickly gained popularity among traders for its simplicity and effectiveness.

    Over the years, the MACD has undergone various refinements to improve its accuracy and usability. Traders have experimented with different settings to optimize the MACD for various trading styles, including day trading. The search for the best MACD settings for day trading is a testament to the indicator’s adaptability and enduring relevance.

    The MACD’s evolution has also seen it compared with other indicators, such as the Relative Strength Index (RSI). The MACD vs RSI debate is a common topic among technical analysts, with each indicator offering unique advantages in different market conditions.

    Calculation

    The MACD Indicator is built upon the relationship between two exponential moving averages (EMAs) of a security’s price. The MACD line is calculated by subtracting the longer EMA from the shorter EMA. In standard settings, the shorter EMA is a 12-period average, and the longer EMA is a 26-period average. The result is the MACD line, which oscillates around zero.

    The formula for the MACD line is as follows:

    MACD Line = 12-period EMA - 26-period EMA

    The MACD also includes a signal line, also known as the MACDA or “Trigger” line. The signal line is a 9-period EMA of the MACD line. The signal line serves as a trigger for buy and sell signals and is used to identify MACD divergences.

    The formula for the signal line is:

    Signal Line = 9-period EMA of the MACD Line

    When the MACD line crosses above the signal line, it generates a bullish signal, suggesting that it might be a good time to buy. Conversely, when the MACD line crosses below the signal line, it generates a bearish signal, indicating that it might be a good time to sell. These crossover points are crucial to the MACD strategy and are particularly useful in identifying MACD divergences.

    Purpose and Design of the Indicator

    The MACD Indicator is designed to capture market momentum and trend strength. It measures the relationship between two moving averages of a security’s price, providing insights into potential trend reversals and continuations.

    The primary purpose of the MACD is to identify changes in the momentum of a security’s price. When the MACD line crosses above the signal line, it indicates increasing upward momentum, suggesting a potential buying opportunity. Conversely, when the MACD line crosses below the signal line, it signifies increasing downward momentum, hinting at a potential selling opportunity. These crossover points are integral to the MACD strategy.

    Another key aspect of the MACD’s design is its ability to identify divergences. A MACD divergence occurs when the price of a security makes a new high or low, but the MACD does not follow suit. For example, in a bullish divergence, the price may make a new low, but the MACD makes a higher low, indicating less downward momentum. Conversely, in a bearish divergence, the price may make a new high, but the MACD makes a lower high, indicating less upward momentum. This divergence between the price and the MACD can often signal a potential trend reversal.

    The indicator also stands out for its adaptability. Traders can adjust the settings of the MACD to suit their trading style. For instance, day traders often seek the best MACD settings for day trading, adjusting the periods of the EMAs to better suit the fast-paced nature of their trading. Suggested settings for day traders are given in the Effective Tips section.

    Decoding MACD Indicator Signals

    The MACD Indicator generates signals through its two components: the MACD line and the signal line. The interaction between these two lines forms the basis of MACD trading signals.

    When the MACD line crosses above the signal line, it’s typically seen as a bullish signal, suggesting a potential buying opportunity. This crossover indicates that the shorter-term momentum of the security is rising faster than its longer-term momentum, which could signal the start of an upward trend.

    On the other hand, when the MACD line crosses below the signal line, it’s generally interpreted as a bearish signal, indicating a potential selling opportunity. This crossover suggests that the shorter-term momentum of the security is falling faster than its longer-term momentum, which could signal the start of a downward trend.

    Another crucial aspect of MACD signals is the concept of divergence. This occurs when the price of a security and the MACD indicator are not in sync, which can often signal a potential trend reversal.

    MACD Divergence Cheat Sheet

    Type of DivergenceDescriptionPotential Signal
    Bullish DivergenceThe price makes a new low, but the MACD does not.A potential upward trend reversal, suggesting a buying opportunity.
    Bearish DivergenceThe price makes a new high, but the MACD does not.A potential downward trend reversal, suggesting a selling opportunity.
    MACD Divergence cheat sheet table

    You can see an example of bearish divergence in action on the AMD stock chart lower down this post.

    Strengths and Weaknesses of the MACD Indicator

    The MACD Indicator offers several advantages but is not infallible. Understanding its strengths and weaknesses can help traders use the MACD more effectively.

    Strengths of the MACD Indicator:

    1. Trend Identification: The MACD is excellent at identifying the direction and strength of a trend. When the MACD line crosses above the signal line, it suggests a potential upward trend. Conversely, when the MACD line crosses below the signal line, it indicates a possible downward trend.
    2. Divergence Detection: The MACD is particularly useful for spotting divergences, which can signal potential trend reversals. This ability to identify MACD divergences is a key aspect of the MACD strategy.
    3. Flexibility: The MACD is adaptable to different trading styles. For instance, day traders often adjust the MACD settings to better suit the fast-paced nature of their trading.

    Weaknesses of the MACD Indicator:

    1. Lagging Indicator: As the MACD is based on moving averages, it is a lagging indicator. This means it tends to react to price movements rather than predict them.
    2. False Signals: The MACD can sometimes produce false signals, particularly in volatile markets. For example, a sudden price movement can cause the MACD to cross the signal line, suggesting a trend that may not materialize.
    3. Inefficiency in Sideways Markets: The MACD is less effective in sideways or range-bound markets, where price movements are minimal.

    MACD vs RSI: A Comparative Overview

    Compared to the RSI indicator, the MACD offers the advantage of being both a trend and momentum indicator. While the RSI primarily measures the speed and change of price movements, the MACD provides insights into both the direction and strength of the trend.

    IndicatorStrengthsWeaknesses
    MACDExcellent for trend identification and divergence detection. Adaptable to different trading styles.Can produce false signals in volatile markets. Less effective in sideways markets.
    RSIEffective at identifying overbought and oversold conditions. Useful for spotting divergences.Can produce false signals in trending markets. Its effectiveness can vary based on the chosen period.
    A table showing the main strengths and weakness comparison of MACD and RSI

    For a more detailed breakdown check out our post on trading with RSI.

    Implementing it in Python with VSCode

    Here’s a step-by-step guide on how to download some stock data, calculate the MACD, and plot it on a chart using Python in VSCode (which is a free download from Microsoft). Follow the step by step guide within VSCode to set up python first.

    Then you’ll need to install the necessary libraries. If you haven’t already, you can install them using pip by adding this in the Terminal window in VSCode and pressing enter:

    Bash
    pip install pandas yfinance mplfinance matplotlib

    Next, create a new .py file e.g. ‘macd.py’ and import the necessary libraries, so you would add the following lines into the top of your new file to do this:

    Python
    import pandas as pd
    import yfinance as yf
    import mplfinance as mpf
    import matplotlib.pyplot as plt
    import matplotlib.lines as mlines
    

    Then, below those lines we add the following lines to download the historical data for the desired time period and symbol. For this example, we’ll use AMD’s stock (AMD):

    Python
    start_date = '2022-06-27'
    end_date = '2023-06-27'
    ticker = 'AMD'
    data = yf.download(ticker, start=start_date, end=end_date)
    

    Underneath that add these lines to calculate the short-term and long-term EMAs. We’ll use 12 periods for the short-term EMA and 26 periods for the long-term EMA:

    Python
    short_EMA = data.Close.ewm(span=12, adjust=False).mean()
    long_EMA = data.Close.ewm(span=26, adjust=False).mean()
    

    Calculate the MACD line and the signal line:

    Python
    MACD = short_EMA - long_EMA
    signal = MACD.ewm(span=9, adjust=False).mean()
    

    Add the MACD and signal line to the data:

    Python
    data['MACD'] = MACD
    data['Signal Line'] = signal
    

    The MACD Histogram is a graphical representation of the difference between the MACD line and the Signal line. It serves as an indicator of the momentum of change.

    The MACD Histogram is particularly useful for identifying when bullish or bearish momentum is increasing or decreasing. For instance, if the MACD Histogram is positive and increasing, it indicates that bullish momentum is increasing. If the MACD Histogram is negative and becoming less negative, it indicates that bearish momentum is decreasing.

    In addition, the MACD Histogram can also be used to spot divergence, which is a situation where the price trend and the MACD trend are moving in opposite directions. This could potentially signal a trend reversal. For example, if the price is making higher highs but the MACD Histogram is making lower highs, it could indicate a bearish divergence, suggesting that the upward trend may soon reverse.

    So let’s calculate the MACD histogram:

    Python
    data['MACD Histogram'] = MACD - signal

    Create subplots to plot MACD, Signal Line, and MACD Histogram below the main chart:

    Python
    macd_plot = mpf.make_addplot(data['MACD'], panel=1, color='b', ylabel='MACD')
    signal_plot = mpf.make_addplot(data['Signal Line'], panel=1, color='r')
    histogram_plot = mpf.make_addplot(data['MACD Histogram'], panel=1, type='bar', secondary_y=False)
    

    Create the candlestick chart with MACD, Signal Line, and MACD Histogram:

    Python
    fig, axes = mpf.plot(data, type='candle', style='yahoo', addplot=[macd_plot, signal_plot, histogram_plot], title='AMD Stock Price with MACD', ylabel='Price ($)', ylabel_lower='Volume', volume=True, volume_panel=2, returnfig=True, panel_ratios=(5,1,1))
    

    Create dummy Line2D objects for the legend:

    Python
    macd_line = mlines.Line2D([], [], color='b', label='MACD')
    signal_line = mlines.Line2D([], [], color='r', label='Signal Line')
    

    Add the legend to the figure:

    Python
    leg = fig.legend(handles=[macd_line, signal_line], loc='center left', bbox_to_anchor=(0,0.5))
    

    Finally, show the plot:

    Python
    plt.show()

    Generate the Chart

    Then save the file and press the play icon in the top right of VSCode to generate the chart. If all has gone to plan you should end up with the same as mine shown below:

    MACD how to calculate
    AMD candle chart with MACD, signal line and histogram created from our Python code


    If you want to make sure your code is producing the right signals, then you can do a comparison to something like Yahoo Finance’s chart of the same stock with MACD on it:

    Python MACD divergence
    Comparing to the Yahoo website you can see we have made the correct calculation and outputs for to use for a MACD strategy

    You might want to adjust the panel ratio in the code to make it taller for a like with like comparison but we can see the curves are in all the right places.

    You can see on the penultimate and final price peaks, the MACD divergence of a lower high instead. This indicates odds may have been in your favour for a short (sell) trade at the time, you could have bolstered that assumption by recognising the double top pattern and the high likelihood that the gap created on the way would be closed. Nothing is ever guaranteed, you are just looking for ways to skew the odds in your favour.

    While you might not think plotting this chart is particularly helpful, consider how you could integrate this code into a screening algorithm. Perhaps you could set up a combination of identified candle formations (we also covered how to code in another post) with divergence detected like the above, perhaps tied to an RSI readout too.

    Even just using free end of day data for 100 stocks that you don’t have time to open charts for every day, you could be alerted to which symbols are triggering these setups. Back test if executing on those would have made you money and determine if it’s a worthwhile strategy swaying the odds in your favour. Obviously you would need to be aware of fundamentals like earning reports throwing a spanner in the works.

    Effective Tips for Utilizing the MACD Indicator in Trading

    While the MACD Indicator is a powerful tool, its effectiveness depends on how it’s used. Here are some best practices for leveraging the MACD indicator in your trading strategy.

    1. Understand the Signals: The indicator generates two types of signals: crossovers and divergences. A crossover occurs when the MACD line crosses the signal line, indicating a potential buying or selling opportunity. A divergence occurs when the price trend and the MACD trend are moving in opposite directions, which could signal a potential trend reversal. Understanding these signals is key to using it effectively.
    2. Use it in Conjunction with Other Indicators: While this indicator can be a powerful tool on its own, it’s often most effective when used in conjunction with other indicators. For example, you might use it to identify potential buy and sell signals, and then use the RSI to confirm these signals.
    3. Adjust the MACD Settings to Suit Your Trading Style: The standard settings are a 12-period EMA, a 26-period EMA, and a 9-period signal line. However, the best MACD settings for day trading might be a faster set-up (e.g., 5-period EMA, 15-period EMA, and a 6-period signal line) providing more effective signals. Experiment with different settings to find the best settings for your specific trading style and goals.
    4. Be Aware of False Signals: Like any indicator, this one can sometimes generate false signals. This is particularly true in volatile markets, where price movements can cause the MACD to cross the signal line, suggesting a trend that may not materialize. Always consider the overall market conditions and use other indicators to confirm signals.
    5. Use the MACD Histogram for Additional Insight: The histogram, which represents the difference between the MACD line and the signal line, can provide additional insight into market momentum. A growing histogram suggests increasing momentum, while a shrinking histogram suggests decreasing momentum.

    Further Reading

    For those interested in learning more about MACD and its applications, consider exploring the following resources:

    Technical Analysis from A to Z by Steven Achelis: This book provides a comprehensive overview of various technical analysis tools, including the MACD.

    Technical Analysis of the Financial Markets by John J. Murphy: This book is a classic in the field of technical analysis and covers a wide range of indicators, including the MACD.

    Leave a Reply

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