We collect cookies to improve your browsing experience. By using our site, you agree to ourPrivacy Policy andTerms of Service.

How Pro Traders Use MACD
Bubble Analytics Research14-Jun-2026

How Pro Traders Use MACD

Summary:

Ticker:TSLA
Timeframe:Daily
Backtest Window:10yrs
Time Invested:82.7%
# Trades:155
Win Rate:50.3%
Total Return:22533.26%
Max Drawdown:-48.7%
Sharpe Ratio:0.77
Profit Factor:2.54

This week’s article sees us having a look at the MACD indicator, making a small modification to the histogram calculation in an attempt to accurately time getting long during short term pullbacks within an existing uptrend; and time the sale of those long positions when momentum turns negative and a bearish breakdown is confirmed.

To start things rolling we have picked the Nasdaq 100 index (QQQ), with 10 years worth of daily OHLC bars downloaded from Yahoo Finance into a dataframe named df, and the backtest itself is run using the backtesting.py library. We will show you how to calculate the indicator, apply it to price, generate trading signals, then run a full backtest and output the results.

As usual, the completed codebook along with our backtesting template can be downloaded via our GitHub profile, but for more detailed coding instruction you can refer to the video on our YouTube channel which shows you how to construct it from start to finish. Please note that the article strategy is for infotainment purposes only and should not be construed as financial advice.

Calculating MACD

The standard MACD calculation uses a 12-period and 26-period exponential moving average of the Close price (fast & slow), subtracting the slow moving average from the fast moving average to form the MACD line. The SIGNAL line is the 9-period exponential average of the MACD line, and the histogram tracks the difference between the two (MACD - SIGNAL).

The code is as follows:

def MACD(data, n1, n2, n3):
fast = data['Close'].ewm(span=n1).mean()
slow = data['Close'].ewm(span=n2).mean()
macd = fast - slow
sig = macd.ewm(span=n3).mean()
histo = macd - sig
return macd, sig, histo
df['MACD'], df['SIG'], df['HISTO'] = MACD(df, 12, 26, 9)

Conventional wisdom says that traders should buy when the MACD line crosses above the SIGNAL line, and sell when it crosses back below, so we tested that strategy going long at the open following a buy signal, then closing that long position and flipping short when a sell signal came.

To generate buy and sell signals within our code book, we ran a loop over our dataset looking for yesterday's MACD line to be below yesterday's SIGNAL line, and today's MACD line to be back above (buy signal), and yesterday's MACD line to be above yesterday's SIGNAL line, and today's MACD line to be below (sell signal). Code as follows:

def signal(data):
signal = [0] * len(data)
for i in range(2,len(data)):
if (data['MACD'].iloc[i-1] < data['SIG'].iloc[i-1]) &\
(data['MACD'].iloc[i] > data['SIG'].iloc[i]):
signal[i] = 1
elif (data['MACD'].iloc[i-1] > data['SIG'].iloc[i-1]) &\
(data['MACD'].iloc[i] < data['SIG'].iloc[i]):
signal[i] = 2
else:
signal[i] = 0
data["signal"] = signal
signal(df)

With our buy and sell signals now contained within our dataset, we generated a price chart for QQQ with the MACD indicator below, and buy signals rendered as white triangles, with sell signals marked by yellow crosses. Chart as follows:

Section 14

We then ran a backtest on QQQ (daily timeframe) over 10 years, utilising no profit targets or stop losses for buy or sell signals, with the strategy simply flipping between long and short with each corresponding signal. The results were horrific, generating a -54% overall return. Full strategy stats are as follows:

Stats 16

So with our new found understanding that trading using bullish and bearish crossovers of the MACD / SIGNAL lines does not yield outsized returns, we turn to look at the histogram part of the indicator. This is often overlooked when in fact it is the most important feature of MACD, tracking the spread between the MACD and SIGNAL lines and giving traders an early warning system that the trend may be about to change.

To utilise the histogram to its fullest we must first amend the MACD calculation, using simple moving averages in place of exponential moving averages, and then smoothing the histogram values further to reduce the risk of false signals. The new MACD Indicator calculation code is as follows:

def MACD(data, n1, n2, n3):
fast = data['Close'].rolling(n1).mean()
slow = data['Close'].rolling(n2).mean()
macd = fast - slow
sig = macd.rolling(n3).mean()
histo1 = macd - sig
histo = histo1.rolling(3).mean()
return macd, sig, histo
df['MACD'], df['SIG'], df['HISTO'] = MACD(df, 12, 26, 9)

So with our customised indicator calculation in place, we then amended our signal calculation, with the sell signal generation method remaining the same as before, but our buy signals coming when the histogram turns up while below zero. In effect we buy when the spread between the MACD and SIGNAL lines starts to narrow, rather than waiting for the bullish cross. Code as follows:

def signal(data):
signal = [0] * len(data)
for i in range(2,len(data)):
if (data['HISTO'].iloc[i-1] < data['HISTO'].iloc[i-2]) &\
(data['HISTO'].iloc[i] > data['HISTO'].iloc[i-1]) &\
(data['HISTO'].iloc[i] < 0):
signal[i] = 1
elif (data['MACD'].iloc[i-1] > data['SIG'].iloc[i-1]) &\
(data['MACD'].iloc[i] < data['SIG'].iloc[i]):
signal[i] = 2
else:
signal[i] = 0
data["signal"] = signal
signal(df)

With our new indicator calculation and signal generation logic in place, we re-rendered our chart to show the difference in the indicator and where the new signals came. This methodology has you buying at the low rather than 5-6 bars later and marks a major improvement. Chart as follows:

Section 23

We then ran another backtest, again on QQQ (daily timeframe) over 10 years, this time utilising a profit target on the long side of 12% and closing out long trades if a sell signal came before that target was hit, but never flipping short. Used as a long only strategy the results improved no end, generating a 367% overall return with a 67% win rate. Full strategy stats are as follows:

Stats 25

How to Exploit This Methodology

As we point out in the code along video, a flat market kills your return as you get multiple signals with no follow through. To use the strategy to its fullest then, what we need to find is a high beta stock that trends strongly in both directions, as that way we get to make bank on the big upside swings, and potentially make money on the downside too.

On this occasion we plumped for the king of volatile stocks over the last 10 years - TESLA. While the gains have been meteoric, the pullbacks have been eye-watering at times, and this is exactly what we need to trade in both directions.

To account for the additional volatility Tesla brings, we have smoothed the histogram values further, and so our last iteration of the indicator employs a 9-period simple moving average rather than the 3-period average we used for QQQ. The calculation is below:

def MACD(data, n1, n2, n3):
fast = data['Close'].rolling(n1).mean()
slow = data['Close'].rolling(n2).mean()
macd = fast - slow
sig = macd.rolling(n3).mean()
histo1 = macd - sig
histo = histo1.rolling(n3).mean()
return macd, sig, histo
df['MACD'], df['SIG'], df['HISTO'] = MACD(df, 12, 26, 9)

We then ran our last backtest, going long when the histogram turns up from below zero, and taking profits when we had a bearish cross of the SIGNAL line. Rather than sitting out of the market following a sell signal, we flipped short with a 6% stop loss and a 10% profit target.

Over 155 trades the strategy returned a staggering 22,533%, but with the extra volatility we experienced a drawdown of -48%. Still.. worth it for the gains we think. Stats are as follows:

Stats 33

To emphasise the bonkers, outsized gains, a profit and loss graph is included below showing that an investment of $100K would now be worth $22.5M:

Section 35

As always, further parameter optimisation, regime filtering, or volatility targeting may improve performance. This article strategy is presented for educational purposes only and should not be considered financial advice. For a detailed run through of the codebook, please watch the video below.

Looking for algorithmic trading signals? Bubble Analytics provides real-time trade notifications generated by systematically tested strategies, complete with detailed performance statistics, trade histories and risk metrics. Explore our live trading signals and start your free 30-day trial today. ->

Share this article:

Explore our services

Recent Articles

Browse all articles