What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?
Title Image for the TradeOxy Blog Post: What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

The Moving Average Convergence Divergence (MACD) technical indicator is a trend and momentum indicator in technical analysis indicators. It's used by traders worldwide in multiple different asset classes.

In this episode, I'm going to share with you some of the research behind the MACD, then show you how to add it to your stock algo trading bot.


What You'll Learn Through My Blog

I'm going to show you everything you need to build your own trading bot from scratch, including:

  • Your own completely customizable development environment, including the worlds most popular technical indicators, and cutting-edge AI from ChatGPT
  • The ability to retrieve historical stock data on over 10,000 US based stocks
  • The power to calculate stock technical indicators on any stock you retrieve
  • The insight to manage your risk

All of this is available in the free episodes of this series.

The premium episodes expand this amazing knowledge base to include:

  • The technical indicators you can include
  • Advanced risk management
  • Advanced strategy building

What You'll Have by the End of this Episode

By then end of this episode, you'll have an understanding of the Relative Strength Index technical indicator, and you'll know how to generate trading signals in your algo trading bot.

GitHub Code

All code for this episode can be found on the something-cool GitHub repository. It is open-sourced under the MIT licence, and you can access it here:

Prior Knowledge

To complete this episode, you need to have the following:

  1. A dev environment which has Python and TA Lib installed
  2. Access to historic market data

Previously I've written episodes for both of these requirements, you can access them here:

  1. Build Your Own Trading Bot Dev Environment that works from Anywhere and includes TA Lib, AI
  2. Build Your Own Trading Stock Trading Bot with Alpaca Markets: Historical Data Retrieval
💡
While completing this episode, please remember that all trading is at your own risk. My goal is to explain and demonstrate, not provide any kind of advice on what will or won't work. Make sure you do your own research before risking any actual money.

Helpful Help from TradeOxy

TradeOxy's mission is to democratize algorithmic trading, and that mission extends to my blog.

If at any point you get stuck in this series, then reach out to us on our Discord chat. I and my team will be more than happy to help out (just make sure it's about our content).


What is the MACD?

The MACD is a technical indicator that uses a combination of exponential moving averages (EMAs) to identify potential momentum in the market. It consists of three components.

  1. MACD Line. Measures the difference between two EMAs, typically referred to as the 'fast' and 'slow' lines.
  2. Signal Line. An EMA of the MACD Line.
  3. Histogram. A visual representation of the difference between the MACD Line and Signal Line, which tends to oscillate around a zero line.

The MACD was created by a person called Gerald Appel in the late 1970's.

Here's an example of what the MACD looks like:

Example of a price chart with MACD added. Part of the TradeOxy Blog Post: What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

What Does the MACD Tell Me?

In its simplest interpretation, the MACD is typically used to identify trading signals such as crossovers, divergences and rapid rises and falls. However, there are multiple different ways to use the MACD, several of which I'll outline in the following sections.

What Does the MACD Line Tell Me?

The MACD Line provides insight into price movements between a shorter-term (fast) EMA and a longer-term (slow) EMA. It does this by subtracting the slow line from the fast line. Therefore, when the MACD Line is positive and growing, then a trader can identify that the gap between the slow and the fast line is increasing.

What Does the MACD Signal Line Tell Me?

The MACD Signal Line takes the moving average lines and performs a second EMA calculation on the MACD Line. Just like the theory behind the original EMA suggests, this has the effect of smoothing the differences between the two original EMA's, which in turn provides insight into the general direction or momentum of the stocks price.

If that sounds a bit complicated, it is. But don't worry, I'll explain how it works in a strategy shortly.

What Does the MACD Histogram Tell Me?

The final component of the MACD is the Histogram. The MACD Histogram measures the difference between the MACD Line and MACD Signal Line. It is the final measurement of relative price pressure as indicated between the MACD Line and MACD Signal Line.

How Does the MACD Identify Overbought or Oversold Conditions?

Enough with the esoteric theory. Let me give you some of the 'rules' or ways that the MACD is used in practice.

The nested EMA of the MACD provides traders with several indicators for future price movement. Here's some examples:

Overbought: When the MACD Line is above the MACD Signal line, this can indicate that a stock is in an overbought condition

Indicative Overbought MACD, indicated by the MACD being above the signal line. Part of the TradeOxy Blog Post: What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

Oversold: When the MACD Line is below the MACD Signal line, this can indicate that a stock is in an oversold condition.

Indicative Oversold MACD, indicated by the MACD line being below the MACD Signal Line. Part of the TradeOxy Blog Post: What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

Bullish Signal: When the MACD Line crosses above the MACD Signal line, this can be interpreted as a bullish signal.

Example of a Bullish Signal from the MACD Technical Indicator. Part of the TradeOxy Blog Post: What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

Bearish Signal: When the MACD Line crosses below the MACD Signal Line, this can be interpreted as a bearish signal.

Example of a Bearish MACD Signal from the MACD Technical Indicator. Part of the TradeOxy Blog Post: What is the MACD in Stocks and How Can I Add it to my Stock Trading Bot?

There are other signals that the MACD Indicator provides, however, I'll save these for a more in-depth MACD article.

What Are the Typical Values for the MACD?

While the MACD input EMA's and Signal Line EMA's can be any value, the below values are considered the standard values:

  1. Fast Line: 12
  2. Slow Line: 26
  3. Signal Line: 9

How Does the MACD Give Me Buy and Sell Signals?

The MACD Indicator provides several different ways to generate buy and sell signals. These strategies tend to try and leverage the momentum and trend direction indicated by the MACD to predict price movement in financial markets.

Simplest MACD Trading Strategy. The simplest MACD trading strategy simply looks at the interaction between the MACD Line and Signal Line, completely ignoring the MACD Histogram. This is called a crossover strategy, and the rules are simple:

  1. Buy the stock when the MACD Line crosses above the MACD Signal Line
  2. Sell the stock when the MACD Line crosses below the MACD Signal Line

I show you how to implement this MACD Strategy in another blog post.

Zero Cross MACD Trading Strategy. Another simple MACD strategy uses the MACD Line and Zero Line to generate buy and sell signals. This is called the Zero Cross Strategy, and to use it you:

  1. Buy the stock when the MACD Line crosses above the zero line
  2. Sell the stock when the MACD Line crosses below the zero line

Other MACD Strategies. Other MACD trading strategies seek to incorporate some of the characteristics of the MACD histogram. For instance, if the size of the histogram is shrinking, then this indicates that the price is reverting back towards the zero line. If you're really keen to calculate things and do technical trading, then you might also be interested in comparing the size of the histogram to its historical average, allowing you identify price pressure.

Entry and exit points. A quick note on the strategies above. You can probably see that I haven't specified any entry and exit points for the above MACD trading strategies. In another episode, I'll show you how to calculate these. For now, just be aware that you should never really trade without things like a Stop Loss, Take Profit and so on.

What are some of the Downsides of the MACD?

If you're planning on using the MACD in your algo trading bot, there are a few things you should consider.

  1. Lagging indicator. The inclusion of nested exponential moving averages in the MACD means that it is a lagging indicator. It is ill suited to sudden price movements (such as news).
  2. No intrinsic value calculation. As a pure technical indicator, the MACD completely ignores the intrinsic value of a stock. If your preferred trading style is more aligned to Value Investing, then this indicator may not be for you.

For this reason, many traders who use the MACD will combine it other technical indicators to improve its accuracy. In this premium episode, I'll show you how to combine the MACD with the RSI indicator to do just that.


How Do I Add the MACD to my Stock Trading Bot?

I hope you enjoyed that quick theory lesson. Let's see how you can add this powerful indicator to your algo trading bot.

Dev Environment Setup

💡
If you've previously added an indicator to your trading bot, then skip this section. If not, carry on below.

First, head over to your dev environment and navigate to your requirements.txt file.

  1. Add TA-Lib to the bottom of the file.
  2. Run the command pip install -r requirements.txt

Next, add a file to your dev environment called indicators.py. Your file structure should look like this:

Algo Trading Bot with an Indicators File added

At the top of indicators.py import TA Lib using this line of code: import talib

💡
Check out this episode to learn more about TA Lib

Add the MACD Indicator to Your Trading Bot

Add the following function to the bottom of your indicators.py file:

I'll quickly go through this powerful function in order.

  1. Checks that the MACD values for the faster line, slower line, and signal line are valid
  2. Calculates the three values of the MACD indicator
  3. Identifies if the MACD is identifying overbought or oversold levels

Finally, let's update calc_indicator to include the MACD. Here's what the completed function looks like:

💡
If you already have other functions from other episodes of my blog, you just need to add it in the if / else statement

Update app.py to See the MACD in Action

To do this, head to your app.py file, which we created in the dev environment setup.

In this file, add a new import statement to the file, below the other import statements. It should say:

import indicators

Now, head to your auto_run_trading_bot() and add update it so that it looks like this:

Here's what mine looked like when I did this:

MACD indicator calculated

Test Out the MACD on Different Stocks and Timeframes

To finish up this episode, I'll show some of the power of the trading bot we're building.

Identifying Multiple Oversold Assets. Let's say you want to identify multiple oversold assets in one go. You can do this by updating the symbols variable, located near the top of your app.py, to this:

symbols = ["AAPL", "GOOGL", "META"]

Testing out Different Timeframes. Many traders have specific timeframes they prefer to work with. You can do this by updating the timeframe variable to whatever timeframe you like. For instance:

timeframe = "1hour"

I'm sure you can already start imaging how powerful this trading bot is becoming!

Wrapping Up

I hope you enjoyed this introduction to the RSI in stocks and enjoyed seeing how to use it in your trading bot!

I'm always interested to hear what my readers and followers want to know more about, so if you've got an idea, why not drop us a suggestion in our suggestion box (aka contact form).

Join the TradeOxy Revolution

At TradeOxy, we're on a mission to democratize algorithmic trading. Why not join our journey and check out our list of amazing indicators and helpful education?

Full Code For app.py

Full Code for indicators.py