# Researching the MACD Indicator in Python

### The last indicator to research before trying to create a strategy. Spoiler, one of our visualizations shows us one of the trade entry criteria we are going to use in the near future.

The third and final indicator before we dive into strategy research. This indicator isn't new (none of them have been), but we are going to calculate it differently than you would normally see. This post isn't as math heavy as some of the others, but the notebook is. The PDF is available for download at the bottom of the post for paid subscribers.

This post is going to be structured a little different. The only parts of the post that aren't available to free subscribers will be the code at the end and the PDF. The rest of the post will be available for all. That means if you have some coding skills (Python, C#, or whatever), and you can translate concepts/math into code, you can reproduce the same indicators.

**Updates**:

I clearly wasn’t able to get into the strategy research this week. The visualizations on this post, along with the observations on the previous indicators, should give you a couple of ideas about what we are going to look for in our strategy research. Next week I will tackle the strategy research and see if we can’t get our first tested strategy published.

I want to thank all of the HGT readers for being patient with me as I try and get a routine and tempo going for research and publications. Currently, my son is 14 months old and beginning to need more attention and structure than before. This means that through the days, I tend to only be able to get an hour or so at a time to get work done. This type of interuption is terrible for deep focus work, so I am working on a way to work around this. I sense night time research in my future.

Anyway, you aren’t here to read about the difficulties of being a stay at home parent. You’re here because you want to up your trading game and you have an interest in automated trade strategies and quant research.

Let’s get into it.

Disclaimer: the following post is an organized representation of my research and project notes. It doesn’t represent any type of advice, financial or otherwise. Its purpose is to be informative and educational. Backtest results are based on historical data, not real-time data. There is no guarantee that these hypothetical results will continue in the future. Day trading is extremely risky, and I do not suggest running any of these strategies live.

## The Moving Average Convergence/Divergence (MACD) Indicator

The implementation of the Moving Average Convergence Divergence (MACD) provided here is an 'enhanced' version that incorporates normalization using the Average True Range (ATR) and the normal cumulative distribution function (CDF). This adaptation aims to improve the traditional MACD by adjusting for varying volatility levels across trading instruments and market conditions.

Traditionally, the MACD is calculated using two exponential moving averages (EMAs)—a fast and a slow EMA—where the MACD value is the difference between these two averages.

A signal line is then generated as an EMA of the MACD, providing a basis for trading signals.

However, this conventional approach does not account for changes in price volatility, which can significantly affect the sensitivity and interpretability of the MACD values. [1]

In this version, the MACD is normalized by incorporating the ATR, a measure used to gauge market volatility. By scaling the difference between the EMAs and the ATR, the MACD values are adjusted for the volatility of the asset. This normalization helps maintain consistency across instruments with differing price scales or volatility signatures, making the indicator more universally applicable and easier to interpret. The scaling factor ensures that MACD values reflect relative price movements more accurately rather than being disproportionately affected by the absolute price levels. [1]

Furthermore, using the normal CDF in the normalization process transforms the MACD values to fit within a standard range, typically around -50 to +50. This transformation standardizes the output, providing a clear, bounded scale that enhances comparability across different assets and timeframes. The result is a MACD that not only signals trend changes and momentum but also adjusts its sensitivity dynamically based on the underlying volatility of the market. [1]

The adjusted equation looks something like this:

This function returns the raw MACD value, the smoothed MACD (trigger line), and the difference between the two. The smoothed value uses exponential smoothing on the MACD to provide a clearer view of the trend. It is often used as a trigger line for traders looking to make an entry into a trade. The difference value can be helpful to anticipate these crossover events, so it is being calculated and returned for future use.

Notes on the specific CDF function being used for this indicator can be found here:

Cumulative Distribution Function

## MACD Plots and Observations

The following visualizations and plots are the preliminary results of this indicator we create in this post. The MACD values are plotted against the logarithmic returns of **SPY** for the past ten years. Data was retrieved from the `yfinance`

library for testing purposes. All code for this research is available for paid subscribers in the PDF that is attached or on the GitHub.

### MACD Plots

In the following plots we are inspecting our indicator for apparent stationarity.

#### Impression

All three plots appear stationary. There is a clear difference between the raw MACD line and the smoothed one, as one would expect.

### Log Returns

We are looking for stationarity here.

#### Impressions

Returns appear mostly stationary. There is a clear aberrancy in 2020 that might show a break in the mean in future testing.

### MACD vs. Returns

In these plots, we are inspecting our MACD values for any obvious patterns associated with the returns of our instrument.

#### Impressions

Every chart, except for the last one, looks relatively symmetrical as far as returns are concerned. With three different return values on this indicator, there are many combinations for comparison. The final scatter plot shows the returns associated with bars (days in this case) directly following a crossover/under event. In this plot, we can clearly see a correlation between returns and a crossover event. This should be investigated further.

### Key Observations

All three return values of the MACD appear stationary in the 10-year window observed in this paper. As expected, the raw MACD line is choppier than the smoothed line, but they appear to be similar otherwise.

All of the returns plots exhibit a large degree of symmetry across the MACD values. The most interesting of them is the final plot, which looks at only the returns with bars (days) after a crossover event. This would be a good place to start for a trade entry trigger.

Notable deviations in return patterns, such as the aberration observed in 2020, underscore the potential for external market shocks to disrupt the mean. Such instances warrant closer scrutiny in future tests to ascertain their implications on predictive strategies.

Volume interaction with the MACD is unremarkable.

This visual analysis of the MACD indicator gives us a starting point for further research. As it stands, the MACD indicator needs to be used with at least one more indicator to see if there is any change in the shape of returns. The most interesting chart remains the returns associated with crossover events. It would be ideal to see this on lower time frames as well to see if it holds up below the daily chart.

The rest of this post is for paid subscribers. Paid subscribers will have access to the private GitHub where all the Hunt Gather Code and strategies live. It is continuously being worked on and will expand as we explore the world of automated trade systems.

## Creating the MACD Indicator

The code below is my interpretation of the MACD indicator discussed by Timothy Masters in reference one below.