Systemicalpha

Moving Average Convergence Divergence

systemic:core-macdIndicatorsfunction1 cr

Inputs

NameTypeDescription
Short Window / Short EMAintegerThe period length for the **fast EMA** in the MACD calculation.
Long Window / Long EMAintegerThe period length for the **slow EMA** in the MACD calculation.
Signal Window / Signal LineintegerThe period length for the **Signal Line EMA**—an EMA applied to the MACD Line itself.
PricefloatarrayThe time series of price values used as input for the MACD calculation.

Outputs

NameTypeDescription
MACDfloatarrayThe **MACD Line**—the core momentum indicator representing the difference between fast and slow exponential moving averages.

The MACD (Moving Average Convergence Divergence) is one of the most widely recognized momentum indicators in technical analysis. Created by Gerald Appel in the late 1970s, it remains a cornerstone of trading systems because it elegantly combines trend-following and momentum analysis into a single measure.

What this module outputs: The MACD Line—the difference between a fast and slow EMA. To build a complete MACD system with Signal Line and Histogram, combine this module with additional EMA and subtraction modules.

MACD Line=EMAfast−EMAslow\text{MACD Line} = \text{EMA}_{\text{fast}} - \text{EMA}_{\text{slow}}

The Intuition Behind MACD

When a fast moving average is above a slow moving average, short-term prices are higher than the longer-term average—bullish momentum. When it's below, short-term prices are lagging—bearish momentum.

MACD quantifies this relationship by measuring the distance between the two averages.

flowchart LR
    subgraph Price["Price Action"]
        P["Closing Prices"]
    end
    
    subgraph EMAs["Exponential Moving Averages"]
        F["Fast EMA (12)"]
        S["Slow EMA (26)"]
    end
    
    subgraph Output["MACD Line"]
        M["Fast − Slow"]
    end
    
    P --> F
    P --> S
    F --> M
    S --> M

Interpreting MACD Values

MACD ValueMeaning
Positive (+)Fast EMA > Slow EMA → Bullish momentum
Negative (−)Fast EMA < Slow EMA → Bearish momentum
RisingMomentum is strengthening
FallingMomentum is weakening
Crossing ZeroTrend direction may be reversing

The Zero Line

The zero line is the equilibrium point where fast and slow EMAs are equal. Crosses above or below zero often signal significant trend changes:

flowchart TD
    subgraph Above["MACD > 0"]
        A1["Fast EMA above Slow EMA"]
        A2["Uptrend momentum"]
    end
    
    subgraph Cross["MACD = 0"]
        C1["EMAs are equal"]
        C2["Potential trend change"]
    end
    
    subgraph Below["MACD < 0"]
        B1["Fast EMA below Slow EMA"]
        B2["Downtrend momentum"]
    end
    
    Above --> Cross --> Below

Real-World Example: SPY EMAs

Using recent SPY (S&P 500 ETF) data (December 2024):

DateEMA-12
2024-12-29$683.92
2024-12-26$683.21
2024-12-24$681.92
2024-12-23$680.38
2024-12-22$679.00

When the 12-period EMA is rising while staying above the 26-period EMA, the MACD Line is positive and increasing—confirming bullish momentum.


Configuration Parameters

ParameterDefaultDescription
Short Window12Fast EMA period
Long Window26Slow EMA period
Signal Window9Smoothing for the Signal Line (used downstream)

Why 12-26-9?

These defaults were established by Gerald Appel for daily stock charts:

  • 12 days ≈ Two trading weeks (short-term trend)
  • 26 days ≈ One trading month (medium-term trend)
  • 9 days ≈ Signal Line smoothing

Alternative Configurations

Market ConditionShortLongRationale
High Volatility817More responsive to rapid changes
Low Volatility1939Filters out noise
Crypto/Forex (24/7)1226Standard works well
Weekly Charts1226Same proportions, larger timeframe

Building a Complete MACD System

This module outputs only the MACD Line. To build a full MACD trading system, combine it with other modules:

flowchart TD
    subgraph Step1["1. MACD Module"]
        M["MACD Line = EMA₁₂ − EMA₂₆"]
    end
    
    subgraph Step2["2. Add EMA Module"]
        E["Signal Line = EMA₉ of MACD"]
    end
    
    subgraph Step3["3. Add SUB Module"]
        H["Histogram = MACD − Signal"]
    end
    
    subgraph Signals["Trading Signals"]
        S1["Crossovers"]
        S2["Zero-line crosses"]
        S3["Divergence"]
    end
    
    Step1 --> Step2 --> Step3 --> Signals

Complete MACD Components

ComponentFormulaWhat It Shows
MACD LineEMA₁₂ − EMA₂₆Momentum direction
Signal LineEMA₉ of MACDSmoothed momentum
HistogramMACD − SignalMomentum acceleration

Trading Strategies

Strategy 1: Zero-Line Crossover

The simplest and most reliable MACD signal—trade when MACD crosses zero.

SignalConditionInterpretation
BullishMACD crosses above 0Short-term trend now above long-term
BearishMACD crosses below 0Short-term trend now below long-term

Strength: These signals are less frequent but more reliable than Signal Line crossovers.

Strategy 2: MACD Direction

Monitor whether MACD is rising or falling, regardless of its absolute value.

MACD BehaviorInterpretation
Rising from deeply negativeBearish momentum slowing, potential reversal
Falling from positiveBullish momentum weakening
Accelerating upwardStrong bullish pressure

Strategy 3: Divergence Detection

Compare MACD direction to price direction—divergence often precedes reversals.

TypePrice ActionMACD ActionMeaning
Bullish DivergenceLower lowsHigher lowsSelling exhaustion
Bearish DivergenceHigher highsLower highsBuying exhaustion

MACD vs. Other Indicators

IndicatorMeasuresMACD Advantage
RSIOverbought/OversoldMACD shows trend direction
StochasticPrice position in rangeMACD works in trends, not just ranges
ADXTrend strength onlyMACD shows direction + momentum
Simple MA CrossoverTrend onlyMACD is smoother (uses EMAs)

Strengths

AspectBenefit
Dual natureCaptures both trend and momentum
Visual clarityEasy to interpret rising/falling patterns
VersatilityWorks across timeframes and asset classes
Well-establishedDecades of trader experience and research

Limitations

AspectChallenge
LaggingBased on moving averages—inherently delayed
False signalsWhipsaws common in ranging/choppy markets
Not boundedUnlike RSI, no overbought/oversold levels
Requires confirmationBest used with other indicators

Combining MACD with Other Modules

CombinationPurpose
MACD + EMACreate Signal Line for crossover signals
MACD + RSIConfirm: MACD bullish + RSI not overbought = stronger signal
MACD + ATRUse ATR for position sizing based on volatility
MACD + VolumeVolume spike + MACD cross = higher confidence
MACD + Bollinger BandsVolatility squeeze + MACD cross = breakout signal

Historical Context

Gerald Appel introduced MACD in his 1979 book "The Moving Average Convergence Divergence Trading Method". Originally designed for stocks, it has proven remarkably adaptable across asset classes—forex, crypto, commodities, and indices all respond well to MACD analysis.

The indicator's longevity (over 45 years) speaks to its fundamental soundness: it captures the universal market dynamic of short-term momentum relative to longer-term trends.


Data Alignment in Systemic

The MACD module accepts a single price series input. Since all window parameters (Short, Long, Signal) are constants, alignment primarily concerns the price_data input.

Single-Input Behavior

The price_data input typically comes directly from an asset data source. If connected to a module that outputs a processed series:

  • Systemic ensures the data reaches MACD as a continuous numeric sequence
  • No multi-input alignment is required since only one price series is used

Parameter Constants

All three window parameters (Short, Long, Signal) must be constants:

  • They cannot be connected to time-varying module outputs
  • This ensures consistent EMA calculations across the entire series

Data Length Requirements

MACD requires sufficient data to compute the longest EMA:

Minimum data points=max⁡(Short Window,Long Window,Signal Window)\text{Minimum data points} = \max(\text{Short Window}, \text{Long Window}, \text{Signal Window})

With default settings (12, 26, 9), you need at least 26 data points.


Missing Data

Both EMAs run over observed bars only and are reindexed back to the full input grid:

  • Closed-market gaps (e.g. weekends) stay gaps, and bridge. A missing input slot produces None in the output — never a carried-forward (stale) MACD value, never a zero-line sentinel. The EMA decay across a gap treats the next observed bar (e.g. Monday) as adjacent to the last observed bar (Friday), not as many calendar days removed — the correct bar-adjacent decay.
  • Warm-up is None, never 0.0. The first long_window − 1 observed bars are honestly undetermined — retired the prior fabricated 0.0 warm-up, which traders could misread as a zero-line crossover signal.
  • Live mode. MACD returns exactly one value for a live request: the most recent slot's MACD, or None if that slot itself is a closed-market gap or still inside the observed-bar warm-up.

Indicator Profile

The following chart compares MACD's utility across stocks and cryptocurrency markets:

quadrantChart
    title MACD Indicator Profile
    x-axis Low Popularity --> High Popularity
    y-axis Low Reliability --> High Reliability
    quadrant-1 High potential  
    quadrant-2 Established leaders
    quadrant-3 Niche tools
    quadrant-4 Popular but risky
    MACD - Stocks: [0.90, 0.75]
    MACD - Crypto: [0.85, 0.65]

Dimension Ratings

DimensionStocksCryptoNotes
Popularity9.0/108.5/10One of the most widely used indicators globally. Standard on every trading platform.
Reliability7.5/106.5/10Reliable in trending markets. Crypto's higher volatility increases false signals.
Complexity4.0/104.0/10Conceptually simple (EMA difference). Most traders can interpret it quickly.
Versatility8.5/108.0/10Works across all timeframes and asset classes. Default settings widely applicable.
Recent Interest7.5/107.0/10Steady classic indicator. Continues to appear in research and trading education.

Further Reading

Rendering diagrams...
© 2026 WanoLabs. All rights reservedAlpha build v0.1.5