# MACD Trading Strategy – Indicator Explained (Backtest, Setup, Rules, Performance and Settings)

Last Updated on May 19, 2023

Can we use the **MACD indicator** and the **MACD histogram** to make a profitable * MACD trading strategy*?

This article looks at the MACD-indicator, what it is, and how you can use it. Does the MACD indicator work? In which markets does it work best? Which time frame is best?

**The MACD indicator is a useful tool and seems to work on stock indices. How do you trade with MACD strategy? We find the MACD useful for trading strategies.**

The MACD was first mentioned as long back as in the 1970s. MACD is an abbreviation for *moving average convergence/divergence*. It’s simply an indicator that consists of two moving averages and how these two lines converge and diverge from each other.

If you find this article useful, you might want to have a look at our landing pages for a lot of other trading strategies and edges:

## How to calculate the MACD:

Let’s start by looking at how to calculate the MACD indicator, which is done in two steps. We include a third step, which is calculating the MACD histogram.

The first step is to calculate the MACD line:

### The fast MACD line

The MACD line is also called the fast line. This is the 12-day exponential moving average deducted from the 26-day exponential average. In Amibroker, the code looks like this:

EMA(c,12) – EMA(c,26)

The fast MACD line is, in other words, the difference between the short and the long moving average. The line is often referred to as the MACD line.

Read this article for an explanation of why we use Amibroker:

### The slow MACD line/the signal line

The second step is to calculate the slow line which is the 9-day exponential moving average of the fast MACD line. This is called the signal line. The lagging signal line is often used as a reversal signal, something we’ll explain later.

### The MACD histogram

This is a deviation from the original MACD indicator, which was developed later, we believe by Alexander Elder in the book called *Trading For A Living*. The histogram is the fast line subtracted the slower signal line. This relationship is quite important, and back in 2012, we published an article about developing a strategy based on the MACD-histogram.

### Why the parameters of 12, 26, and 9?

In all trading software, books, seminars, etc., the default settings are 12, 26, and 9 days. Why is that? We assume only the inventor of the MACD, Gerald Appel, can answer that. There is, of course, nothing stopping you from changing the parameters. However, the above settings have somehow been “stuck” with the indicator.

The chart below shows how the MACD oscillates back and forth:

The red line is the MACD line (the fast line), while the blue line is the slow signal line. The bars oscillating around zero is the MACD-histogram.

## How does the MACD indicator work?

The MACD is an oscillating indicator that can capture both momentum, reversal, and trend. As always, there is no definitive answer on how to use the MACD. Most likely, you will find the best use not mentioned in any books or articles!

## Which MACD setting is best? What is the best time frame for the MACD?

You have to play around with the values. The default values are just suggestions, and you need to play around with the values in order to see if you spot any patterns.

For example, the market indices move fast up and down, and you are probably better off if you use a shorter time frame.

Again, there is no definitive answer, and you must test yourself what works and what doesn’t. Be careful to generalize to other markets. No indicator works well on all markets! Something that works on the S&P 500 doesn’t necessarily work on the gold price.

## MACD trading strategy

Let’s make a **MACD trading strategy** on the S&P 500.

### Buy when the fast line crosses above the slow signal line

The above criterion is taken from Alexander Elder’s *Trading For A Living*. Elder didn’t test the strategy, even though this strategy is easily tested.

- Buy on the close when the fast MACD line crosses above the slow signal line.
- Sell on the close when the slow signal line crosses above the fast MACD line.

This is all there is to it. On the S&P 500, we get this equity curve for the MACD trading strategy:

The CAGR is 4.19%, the average gain per trade is 0.44%, the profit factor is 1.65, and the maximum drawdown is 30%.

The code in Amibroker is like this:

Fast = EMA(C,12) – EMA(C,26);

Slow = EMA(Fast,9);Buy = Cross(Fast, Slow);

buyPrice = Close;

Sell = Cross(Slow, Fast);

sellPrice = Close ;

The strategy is certainly untradeable. If we start optimizing to find the best MACD parameters settings, what are the best parameters?

To make a strategy optimization we need to rewrite the code:

Opt1 = Optimize(“ShortEMA”,2,2,15,1);

Opt2 = Optimize(“LongEMA”,20,6,25,1);

Opt3 = Optimize(“Slow”,5,5,15,1);Fast = EMA(C,Opt1) – EMA(C,Opt2);

Slow = EMA(Fast,Opt3);Buy = Cross(Fast, Slow);

buyPrice = Close;

Sell = Cross(Slow, Fast);

sellPrice = Close ;

This gives 3080 optimization steps. Amibroker is lightning fast and the optimization is done in 13 seconds. The results indicate the best parameters are somewhat in the vicinity of the default settings.

Let’s change the strategy to include a new variable but keep the same parameters in the MACD crossover:

We have reasons to suspect a MACD crossover is more bullish if it happens when the slow line is in negative territory. Is this correct? Let’s test by adding a new variable (in bold):

Fast = EMA(C,12) – EMA(C,26);

Slow = EMA(Fast,9);Buy = Cross(Fast, Slow)

and Slow<0;

buyPrice = Close;

Sell = Cross(Slow, Fast);

sellPrice = Close ;

When the slow signal line is below zero when the crossover happens, we slightly improve the results, but the number of trades is more than halved:

The CAGR is 3.44%, the average gain per trade is 0.79%, the profit factor is 1.72, and the maximum drawdown is 25%.

If we add a long-term trend filter, for example, a 200-day average, the results improve and the success rate improves.

(Many traders like to use python instead of for example Amibroker. That is fine, but trading is all about being efficient and we honestly believe you are better off using a platform that has already many of the functions ready).

### MACD as overbought and oversold trading strategy

The MACD can additionally help us to find overbought and oversold conditions. We have already mentioned the MACD-histogram, and this indicator shows the difference between the fast and the slow signal line. When the distance is increasing, it means the speed of the fast line is picking up more than the slow signal line.

Let’s try a new twist of the MACD by using the MACD-histogram. For simplicity, we use the same strategy as in this article about MACD histogram strategy. The requirements are the following:

- The MACD histogram bar must have fallen 4 days in a row.
- The fourth latest bar must have been below zero.
- The current close of the ETF must be lower than the day before.
- If the above three criteria are true, then enter at the close.
- Exit on the close when today’s close is higher than yesterday’s high.

The Amibroker code is like this:

Fast = EMA(C,12) – EMA(C,26);

Slow = EMA(Fast,9);

Histogram = Fast – slow;Buy= C<Ref(C,-1) AND Ref(Histogram,-4) < 0 AND Ref(Histogram,-4) > Ref(Histogram,-3) AND Ref(Histogram,-3) > Ref(Histogram,-2) AND Ref(Histogram,-2) > Ref(Histogram,-1) AND Ref(Histogram,-1) > Histogram;

buyPrice = Close;

Sell = Close > Ref(H,-1);

sellPrice = Close ;

Here is an example of such a trade signal (using 3, 10, and 5-day lookback period):

By using 12, 26, and 9-day lookback periods, we get the following equity curve on the S&P 500 (compounded):

The CAGR is 4.79%, the average gain per trade is 0.95%, the profit factor is 4.22, and the maximum drawdown is 16%. This shows some promise, and it works pretty well on several other ETFs as well.

## Combining MACD Histogram and the RSI indicator into a strategy

In a previous article, we covered how the RSI indicator works. The RSI indicator has proven to be a useful mean revertive indicator, and it might add value combined with the MACD histogram. Let’s add a “slow histogram” and combine that with a two-day RSI. The idea is that we only buy on a low RSI but it must be combined with a low histogram reading. This is the code in Amibroker:

Fast= EMA(C,12) – EMA(C,26);

Slow= EMA(Fast,9);

Histogram= Fast – Slow;

HistogramSlow= MA(Histogram,5);Buy= RSI(2) < 10 AND HistogramSlow < Ref(HistogramSlow,-5) ;

buyPrice= Close;

Sell= Close > Ref(H,-1);

sellPrice= Close ;

The compounded equity curve for the S&P 500 looks like this:

The CAGR is 6.36%, the average gain per trade is 0.76%, the profit factor is 2.45, and the maximum drawdown is 16%. Compared to the MACD histogram strategy it has more trades and works better compared to only trading the two-day RSI without any other criteria.

## MACD and Crypto

We have tested the MACD indicator on crypto and bitcoin, but we had only moderate success. The reason why is that crypto this far has not been very mean revertive.

## Benefits of MACD Trading Strategy

The MACD trading strategy offers several benefits to traders who incorporate it into their trading approach. Here are some key advantages of using the MACD indicator:

- Signal Confirmation: The MACD indicator helps confirm potential trade signals by providing visual cues of momentum shifts in the market. Traders can use the convergence and divergence of the MACD lines to validate the strength of a trend or identify potential reversals.
- Trend Identification: The MACD indicator is effective in identifying the prevailing trend in a market. By observing the relationship between the MACD line and the signal line, traders can determine whether the market is experiencing an uptrend or a downtrend, enabling them to align their trades accordingly.
- Entry and Exit Points: The MACD strategy provides clear entry and exit points for trades. Traders can initiate a buy trade when the fast MACD line crosses above the slow signal line, indicating a potential bullish trend. Conversely, a sell trade can be initiated when the slow signal line crosses above the fast MACD line, suggesting a possible bearish trend.
- Divergence Analysis: The MACD histogram, which represents the difference between the fast and slow lines, can help traders identify divergences between price and momentum. Divergence occurs when the price and the MACD indicator move in opposite directions, potentially signaling a reversal or trend continuation. This aspect of the MACD strategy can be particularly valuable for traders looking for potential trend reversals.
- Versatility: The MACD indicator is versatile and can be applied to various markets and timeframes. While it has shown effectiveness in stock indices, traders can also use it in other markets, such as forex, commodities, and cryptocurrencies. Additionally, traders can adjust the MACD parameters to suit their preferred timeframes, allowing for customization and adaptability to different trading styles.
- Supplementary Tools: The MACD indicator can be used in combination with other technical indicators or trading tools to enhance its effectiveness. For example, traders often combine the MACD with trendlines, support and resistance levels, or other oscillators to strengthen their trading signals and increase the probability of successful trades.
- Backtesting and Optimization: The MACD trading strategy is amenable to backtesting and optimization, allowing traders to evaluate its historical performance and fine-tune the indicator’s parameters for optimal results. By conducting thorough testing on different markets and timeframes, traders can gain confidence in the strategy and make informed decisions based on empirical data.

It’s important to note that while the MACD trading strategy offers numerous benefits, it is not a foolproof method for guaranteed profitability. Traders should exercise caution, combine it with other forms of analysis, and employ risk management techniques to mitigate potential losses.

## Step-by-Step Guide to Implementing MACD Trading Strategy

If you’re interested in implementing the MACD trading strategy, here is a step-by-step guide to help you get started:

- Understand the MACD Indicator: Familiarize yourself with the MACD indicator and its components. The MACD consists of two lines, the fast line (MACD line) and the slow line (signal line), as well as the MACD histogram, which shows the difference between the two lines.
- Calculate the MACD Line: Calculate the fast line by subtracting the 26-day exponential moving average (EMA) from the 12-day EMA. This represents the short-term and long-term moving averages.
- Calculate the Signal Line: Calculate the slow line by taking the 9-day EMA of the fast line. The signal line is often used as a reversal signal in trading.
- Understand MACD Oscillations: Visualize the MACD line, signal line, and histogram on a chart. The MACD oscillates above and below zero, indicating momentum, reversal, and trend.
- Determine the Best MACD Settings: Experiment with different parameter values for the MACD indicator to find settings that work best for your trading strategy. Consider the market you are trading and the time frame you are analyzing.
- Develop Entry and Exit Rules: Define your entry and exit rules based on MACD crossovers. A common strategy is to buy when the fast line crosses above the slow line and sell when the slow line crosses above the fast line.
- Test and Optimize the Strategy: Backtest your MACD trading strategy using historical data to evaluate its performance. Optimize the strategy by adjusting the MACD parameter values to maximize profitability and minimize risk.
- Consider Additional Filters: Explore the possibility of adding additional filters or indicators to enhance the MACD trading strategy. For example, you could incorporate a long-term trend filter, such as a 200-day moving average, to improve the success rate.
- Monitor and Refine: Continuously monitor the performance of your MACD trading strategy in real-time. Make adjustments and refinements as needed based on market conditions and the results of your analysis.
- Combine with Other Indicators: Consider combining the MACD indicator with other technical indicators, such as the Relative Strength Index (RSI), to create a more comprehensive trading strategy. Experiment with different combinations to find what works best for your trading style.

Remember, trading strategies are not one-size-fits-all, and it’s important to adapt and customize them based on your risk tolerance, trading goals, and the specific market you are trading. Always practice proper risk management and keep learning and evolving as a trader.

## Common Mistakes to Avoid When Using MACD for Trading

The MACD indicator can be a valuable tool for traders, but it’s important to be aware of common mistakes that can hinder its effectiveness. Here are some key pitfalls to avoid when using MACD for trading:

- Relying Solely on MACD Crossovers: While MACD crossovers between the fast line and the signal line can be used as trading signals, relying solely on these crossovers may result in false signals. It’s essential to consider other factors and indicators to confirm the validity of a trade.
- Ignoring Market Context: The MACD indicator’s performance can vary across different markets and timeframes. It’s crucial to consider the specific characteristics of the market you’re trading, such as volatility, liquidity, and trading hours. Adapt the MACD strategy to suit the market conditions for better results.
- Neglecting Price Action: The MACD is derived from moving averages, and it’s important not to overlook price action. Analyzing price patterns, support and resistance levels, and candlestick formations in conjunction with the MACD can provide a more comprehensive view of market dynamics.
- Over-Optimizing MACD Parameters: While it can be tempting to optimize the MACD parameters to achieve the best possible results, excessive parameter tweaking can lead to curve-fitting and overfitting the indicator to past data. Be cautious when adjusting the default parameters and focus on robustness rather than short-term performance.
- Failing to Use Stop Loss Orders: Risk management is crucial in trading, and using stop loss orders is essential to protect your capital. The MACD indicator alone does not provide information about potential stop loss levels. Incorporate appropriate risk management techniques to limit losses and preserve capital.
- Disregarding Divergences: MACD divergences occur when the price and the MACD indicator move in opposite directions. These divergences can provide valuable insights into potential trend reversals. Ignoring divergences may result in missed trading opportunities, so be sure to monitor them alongside other technical analysis tools.
- Neglecting Fundamental Analysis: While the MACD is a technical indicator, incorporating fundamental analysis can enhance your trading decisions. Pay attention to relevant news, economic events, and company-specific factors that can influence price movements. Combining technical and fundamental analysis can provide a more comprehensive trading strategy.

Remember, no trading strategy, including those involving the MACD indicator, is foolproof. It’s crucial to continuously monitor and adapt your approach based on market conditions and feedback from your trading results. Practice risk management, employ proper trade analysis, and avoid common mistakes to increase your chances of success when using the MACD indicator for trading.

## Advanced Techniques to Enhance Your MACD Trading Strategy

While the MACD indicator is a powerful tool on its own, there are advanced techniques that can further enhance your MACD trading strategy. By incorporating these techniques, you can potentially improve your trading results and increase your profitability. Here are some advanced techniques to consider:

- Divergence Analysis: In addition to the standard MACD signals, you can look for divergences between the MACD indicator and price movements. Divergence occurs when the MACD and price move in opposite directions. Bullish divergence is identified when the price forms lower lows while the MACD forms higher lows. Conversely, bearish divergence occurs when the price creates higher highs while the MACD forms lower highs. Divergence analysis can provide valuable insights into potential trend reversals or trend continuation.
- Multiple Time Frame Analysis: Instead of relying solely on one time frame, you can incorporate multiple time frames into your MACD analysis. For example, if you primarily trade on the daily chart, you can use the MACD on higher time frames like the weekly or monthly to get a broader perspective of the overall trend. This can help you make more informed trading decisions by aligning your trades with the dominant trend across different time frames.
- Trend Filtering: To increase the effectiveness of your MACD strategy, consider adding a trend filter. This can be done by incorporating a longer-term moving average, such as the 200-day moving average, to identify the direction of the primary trend. By only taking MACD signals that align with the trend filter, you can potentially improve the quality of your trades and avoid counter-trend signals during periods of consolidation or market noise.
- Confirmation Indicators: While the MACD can be a reliable indicator on its own, you can enhance its signals by using additional confirmation indicators. For instance, you can combine the MACD with other oscillators like the Relative Strength Index (RSI) or the Stochastic Oscillator to validate potential trade setups. When the MACD generates a signal in the direction of the trend, and the confirmation indicators also confirm the signal, it can increase your confidence in taking the trade.
- Money Management: Implementing proper money management techniques is crucial for any trading strategy, including MACD-based strategies. Determine your risk tolerance and use appropriate position sizing techniques to protect your capital. Consider setting stop-loss orders based on key support or resistance levels to manage your risk effectively. Additionally, you can use trailing stops to protect profits and allow for potential trend continuation.

Remember, it’s important to thoroughly backtest and forward test any modifications or advanced techniques you incorporate into your MACD trading strategy. Each market and timeframe may require adjustments and fine-tuning to optimize your results. Continuously monitor and evaluate the performance of your strategy, making necessary adjustments as market conditions change.

By utilizing these advanced techniques, you can take your MACD trading strategy to the next level and potentially increase your profitability in the markets. Always remember to exercise proper risk management and trade responsibly.

## Free trading strategies

We have covered many other indicators and strategies in previous articles. For a full list, please see this link:

## Conclusion about MACD and its trading strategies

As with all other indicators, the MACD is a lagging indicator. The moving average crossover most likely has limited use as a stand-alone trading signal, but the **MACD histogram trading strategy** shows some real promise, albeit not the best swing trading indicator. However, the MACD-histogram is a mean reversion indicator, and there are probably other and better indicators for that, like for example, the RSI indicator.

I tested out the code from 1999 to 2020, seems the MACD strategy does not work at all before 2000. the drawdown is 50%. I guess the market regime changed.

Hi Erik,

Thanks for the testing.

Oddmund

Hey,

I’m curious as to why you use sellPrice= Close ; and buyPrice= Close; as they are not really realistic imo (unless you have a trick for that?).

If you use a more realistic next day buy and sell prices of AvgPrice = (O+H+L+C)/4; your results will look a lot different (and unfortunately a lot worse).

Cheers,

Hi Ben,

Your question is relevant. You have three options to trade a signal: on the close, after the close (after hours), or next day.

I prefer to enter on the close. It’s not really on the close, but I enter ten seconds before the exchange closes. The results are better by entering on the same bar than the next bar (for example of the open).

You’re right, it will be a lot worse by using next day. This is the sad reality. I’m interested in doing what works and thus I enter just before the close:) This is the power of automation: the computer does it for you.

Regards,

O.G.