The MACD seems intimidating at first — three elements, two numbers, a histogram — but the core idea is simple: it measures whether the trend is accelerating or decelerating by comparing two moving averages. After this guide, you'll understand each part and have the code to automate the classic strategy.
01What is the MACD
MACD stands for Moving Average Convergence Divergence, created by Gerald Appel in the late 1970s. It's simultaneously a trend and momentum indicator. It has three components:
- MACD Line: the difference between the 12-period exponential moving average (EMA) and the 26-period. When the fast is above the slow, it's positive (bullish momentum).
- Signal Line: a 9-period EMA of the MACD line itself. Serves as a trigger.
- Histograma: a diferença between a linha MACD e a linha de sinal. Mostra a força do movimento visualmente.
The numbers 12, 26, 9: are Appel's default. 12 = fast average, 26 = slow average, 9 = signal line. You can adjust, but these values are so widespread that many traders react to them — there's value in using what the entire market watches.
02Os sinais do MACD
1. Line crossover (the classic)
The most used signal: when the MACD line crosses the signal line upward → buy. When it crosses downward → sell. The foundation of the automatable strategy.
2. Zero line crossover
When the MACD line crosses zero upward, the fast average passed the slow — confirmation of uptrend. Downward, downtrend. Slower, but more reliable than the line crossover.
3. Histograma
The histogram grows when momentum accelerates and shrinks when it decelerates. Decreasing histogram (even if still positive) warns that the rally is losing strength — anticipates the crossover.
4. Divergences
Como no RSI, divergência between preço e MACD é poderosa: preço faz topo mais alto, MACD faz topo mais baixo → enfraquecimento, possível reversal.
The MACD weakness: it's based on averages, so it lags. In ranging markets, it generates many false crossovers ("whipsaws"). Like RSI, MACD shines in trends and struggles in consolidation. Don't trade MACD crossovers in ranging markets without a filter.
03Coding the MACD
//@version=5 strategy("MACD Cruzamento", overlay=false) rapida = input.int(12, "EMA Rápida") lenta = input.int(26, "EMA Lenta") sinal = input.int(9, "Linha de Sinal") [macdLine, signalLine, hist] = ta.macd(close, rapida, lenta, sinal) plot(macdLine, "MACD", color=color.blue) plot(signalLine, "Sinal", color=color.orange) plot(hist, "Histograma", style=plot.style_histogram, color=hist >= 0 ? color.green : color.red) // strategy: line crossover if ta.crossover(macdLine, signalLine) strategy.entry("Compra", strategy.long) if ta.crossunder(macdLine, signalLine) strategy.close("Compra")
import pandas as pd def calcular_macd(precos, rapida=12, lenta=26, sinal=9): ema_rapida = precos.ewm(span=rapida, adjust=False).mean() ema_lenta = precos.ewm(span=lenta, adjust=False).mean() macd_line = ema_rapida - ema_lenta signal_line = macd_line.ewm(span=sinal, adjust=False).mean() histograma = macd_line - signal_line return macd_line, signal_line, histograma macd, sinal_l, hist = calcular_macd(df["close"]) # detecta cruzamento de alta no último candle cruzou_cima = (macd.iloc[-2] < sinal_l.iloc[-2]) and \ (macd.iloc[-1] > sinal_l.iloc[-1]) if cruzou_cima: print("MACD cruzou for cima — sinal de compra")
Atalho: in Python, pandas-ta has MACD ready: df.ta.macd(fast=12, slow=26, signal=9). The manual calculation above is for you to understand the mechanics.
Combine MACD com outros indicadores
Veja como o RSI complementa o MACD for filtrar sinais falsos.
04Melhorando a estratégia
Pure MACD crossover generates many false signals. Filters that greatly improve:
- Filtro de trend: só compre se o preço está above da média de 200, e MACD cruzou for cima.
- Filtro de linha zero: só valide o cruzamento se acontecer above de zero (já em trend de alta).
- Confirmação com RSI: cruzamento de MACD + RSI above de 50 = sinal mais forte.
Princípio: nenhum indicador isolado é suficiente. O MACD ganha very when confirma (ou é confirmado por) trend and momentum de outras fontes. Combinação reduz falso positivo.
05Preguntas frecuentes
What is the MACD?
É um indicador de momentum e trend que mostra a relação between duas médias móveis exponenciais (12 e 26), com uma linha de sinal (9) e um histograma. Mede se a trend acelera ou desacelera.
What are the default parameters?
12, 26, 9: fast average 12, slow 26, signal 9. Set by Gerald Appel and widely used — there's value in using what the entire market watches.
Como gerar sinal de compra?
O clássico é when a linha MACD cruza a linha de sinal for cima (compra) ou for baixo (venda). O cruzamento da linha zero e o histograma complementam. Always filtre com trend to avoid falsos.
MACD or RSI?
It's not "either/or" — they complement each other. MACD focuses more on trend/momentum of averages; RSI on overbought/oversold. Many strategies use both: MACD for direction, RSI for timing/filter.
Does MACD work for day trading?
Yes, but adjust periods for short timeframes and beware of inherent lag. In very fast day trading (scalping), MACD lag can be a problem — combine with more agile indicators.