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.
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:
To complete this episode, you need to have the following:
- A dev environment which has Python and TA Lib installed
- Access to historic market data
Previously I've written episodes for both of these requirements, you can access them here:
- Build Your Own Trading Bot Dev Environment that works from Anywhere and includes TA Lib, AI
- Build Your Own Trading Stock Trading Bot with Alpaca Markets: Historical Data Retrieval
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.
- MACD Line. Measures the difference between two EMAs, typically referred to as the 'fast' and 'slow' lines.
- Signal Line. An EMA of the MACD Line.
- 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:
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
Oversold: When the MACD Line is below the MACD Signal line, this can indicate that a stock is in an oversold condition.
Bullish Signal: When the MACD Line crosses above the MACD Signal line, this can be interpreted as a bullish signal.
Bearish Signal: When the MACD Line crosses below the MACD Signal Line, this can be interpreted as a bearish signal.
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:
- Fast Line: 12
- Slow Line: 26
- 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:
- Buy the stock when the MACD Line crosses above the MACD Signal Line
- 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:
- Buy the stock when the MACD Line crosses above the zero line
- 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.
- 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).
- 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
First, head over to your dev environment and navigate to your
TA-Libto the bottom of the file.
- 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:
At the top of
indicators.py import TA Lib using this line of code:
Add the MACD Indicator to Your Trading Bot
Add the following function to the bottom of your
I'll quickly go through this powerful function in order.
- Checks that the MACD values for the faster line, slower line, and signal line are valid
- Calculates the three values of the MACD indicator
- 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:
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:
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:
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!
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?