EMA crossover and the MACD line: formula, 12/26 rule and example

On this page

Key takeaways

  • An exponential moving average gives the latest price the most weight and lets older prices fade gradually, so it turns sooner than a simple average of the same length.
  • The rule holds the asset while the fast average is above the slow one. With twelve-day and twenty-six-day averages, that is the same decision as the MACD line, the gap between them, being above zero.
  • Faster averages mean earlier exits, earlier re-entries and more false signals, so a twelve-day and twenty-six-day pair trades far more often than the fifty-day and two-hundred-day golden cross.
  • The popular MACD signal-line rule, which compares the MACD line with its own nine-day average, is a different and faster rule; MarketHeist can approximate it but not reproduce it exactly.
  • Like every moving-average rule it trades protection in long declines for late entries and whipsaws; whether that trade paid off depends on the asset and the years tested.

Definition

An exponential moving average (EMA) weights recent closing prices more heavily than older ones, and an EMA crossover rule holds an asset while a shorter EMA is above a longer one. With 12-day and 26-day averages it is Gerald Appel's MACD line read against zero: the difference between the two EMAs is positive exactly when the rule is invested.

Also known as: exponential moving average crossover, EMA cross, MACD, MACD line, MACD zero line, moving average convergence divergence, 12/26 EMA, exponential moving average.

How it works

A simple moving average treats the last n prices equally and forgets everything older at once. An exponential moving average weights every past price, with weights that shrink by a constant factor each day back: the newest price gets the most, yesterday's a little less, and so on, without a cut-off. The weight on the newest price is two divided by the length plus one, so a 12-day EMA puts two thirteenths of its weight on today. Because recent prices count more, an EMA turns sooner than a simple average of the same length.

Gerald Appel built the MACD, moving average convergence divergence, from two EMAs in the late 1970s. The MACD line is the 12-day EMA minus the 26-day EMA: positive when the fast average is above the slow one, negative below. A nine-day EMA of the MACD line is the signal line, and the gap between the two is the histogram. Holding an asset while the MACD line is above zero is exactly an EMA crossover rule with 12 and 26 days.

An exponential average is like a memory that fades: yesterday is vivid, last month is hazy, and nothing is ever entirely forgotten.

MarketHeist expresses the crossover as a ratio, the fast EMA divided by the slow one, and holds the asset while the ratio is above one; for positive prices that is the same decision as the MACD line above zero. The more popular signal-line crossover, the MACD line against its nine-day EMA, needs an average of the difference, which the backtester does not build. Its crossover rule can compare the ratio with its own nine-day simple average, which is close in spirit but not identical: a simple instead of an exponential average, of a ratio instead of a difference.

Speed is the trade-off. A 12/26 crossover reacts within days of a turn, so it exits early in a decline but also on every brief dip, and each false exit sells lower and buys back higher. Slower pairs, such as 50/200, whipsaw less and react later. The lengths 12 and 26 are Appel's published settings, conventions rather than values fitted to any market.

Formula

Exponential moving average as MarketHeist computes it
En(t)=∑i=0t(1−α)t−iPi∑i=0t(1−α)t−i,α=2n+1
Pᵢ
adjusted closing price on day i, counted from the first day of data (i = 0)
n
the EMA's span in days (12 or 26 here)
α
weight on the newest price
E_n(t)
the n-day exponential moving average on day t

This is the normalised form (pandas adjust = True). Far from the start of the data it equals the familiar recursion Eₜ = α Pₜ + (1 − α) Eₜ₋₁; it differs only in the first weeks of a series, which the backtest's history long precedes.

MACD, its signal line, and the crossover rule
MACDt=E12(t)−E26(t),Signalt=EMA9(MACD),st=E12(t)E26(t),pt=1⇔st>1⇔MACDt>0
MACDₜ
the MACD line: 12-day EMA minus 26-day EMA
Signalₜ
the signal line: a 9-day EMA of the MACD line (not used by the engine)
sₜ
MarketHeist's signal: the ratio of the two EMAs
pₜ
the position decided at day t's close: 1 = invested, 0 = cash

The MACD histogram is MACD minus the signal line. MarketHeist's closest version of the signal-line rule compares sₜ with its own 9-day simple average.

Worked example

SPY's daily bars from Oct 2006 to Sep 2026, about 20 years: hold SPY while its 12-day EMA is above its 26-day EMA, the MACD line above zero, otherwise cash. Standard one-bar delay, no trading costs, no interest on cash.

The rule was invested on 70.8% of days and completed 83 round trips, 4.2 a year. It grew 6.8% a year against 11.1% for holding SPY, a gap that compounds: $10,000 became $36,905 instead of $82,292.

In exchange, its worst decline from a peak was -27.3%, against -55.2% for SPY, much shallower, because the fast averages turned down within weeks of each major top. Its volatility was 11.2% against 19.4%.

Simple averages of 12 and 26 days gave 90 round trips and 5.8% a year. The approximation of the MACD signal-line rule, long while the ratio of the two EMAs is above its own 9-day simple average, traded far more: 218 round trips, 10.9 a year. 50.9% of its trades ended with a gain, and it grew 4.4% a year.

The 12/26 EMA robustness page runs the zero-line rule on SPY, QQQ, TLT, GLD and EFA over each fund's history, with trading costs and interest on cash, and checks whether nearby lengths behave alike.

Data through Sep 2026. Reproduce id 2d7a0b71f0ccb327 (this guide, its lab setup and the data month).

Interactive lab

SPY's price with the 12-day and 26-day EMAs, the MACD line in the indicator panel with its zero line, days invested shaded, and the results table for the zero-line rule, simple averages and the signal-line approximation against buy-and-hold. Change the lengths, the rule, the cost, the delay or the fund.

SPY price with the days the base rule held itS&P 500, adjusted daily close, Oct 2006 to Sep 2026, log scale. Shaded: the 84 stretches the base rule held the fund (71% of 5030 days). Also drawn: 12-day exponential average, 26-day exponential average.$50$100$200$50020062011201620212026SPY adjusted close12-day exponential average26-day exponential averageHeld by the base rule
SPY on a log scale. Shaded: the days the base rule held the fund. Oct 2006 to Sep 2026.
Short / long EMA ratio with the base rule's lineShort / long EMA ratio on SPY, Oct 2006 to Sep 2026. The rule compares it with the fixed line 1.0.920.940.960.9811.02200620112016202120261Short / long EMA ratio
Short / long EMA ratio and the line the base rule compares it with. Oct 2006 to Sep 2026.
Growth of $10,000: the setups against buy and holdS&P 500, Oct 2006 to Sep 2026, log scale. $10,000 grows to $36,905 (base), $30,780 (Simple averages, 12/26), $23,430 (Signal-line approximation: ratio above its 9-day average), $82,292 (buy and hold).$10k$20k$50k20062011201620212026Base ruleSimple averages, 12/26Signal-line approximation: ratio above …Buy and hold
Growth of $10,000 on a log scale, same days for every line. Oct 2006 to Sep 2026.
MeasureBaseSimple averages, 12/26Signal-line approximation: ratio above its 9-day averageBuy and hold
CAGR6.8%5.8%4.4%11.1%
Volatility (annualized)11.2%11.5%11.1%19.4%
Maximum drawdown-27.3%-19.0%-40.6%-55.2%
Sharpe ratio0.640.550.440.64
Sortino ratio0.890.750.60n/a
Growth of $10,000$36,905$30,780$23,430$82,292
Time in the market70.8%66.5%48.9%100.0%
Round trips8390218n/a
Round trips per year4.24.510.9n/a
Win rate43.4%45.6%50.9%n/a
Average win6.7%5.7%2.6%n/a
Average loss-2.1%-2.2%-1.8%n/a
Payoff ratio3.282.561.44n/a
Average days held42.837.111.2n/a
Expectancy per trade1.8%1.4%0.4%n/a
Profit factor, per day1.151.131.131.13
Profit factor, per trade2.512.151.51n/a
Indicator, last day1.0021.0011.002n/a
Indicator, 10th / 50th / 90th percentile0.989 / 1.005 / 1.0140.983 / 1.006 / 1.0190.989 / 1.005 / 1.014n/a
Days the rule alone is long70.8%66.5%48.8%n/a

S&P 500, Oct 2006 to Sep 2026, 5030 trading days. Every setup is measured over the same days, with the indicator warmed up on earlier ones; cash earns 0. Base: EMA Crossover (short window 12, long window 26); long while the Short / long EMA ratio is above 1; execution delay 1; cost 0 bps one way. Simple averages, 12/26: MA Crossover (short window 12, long window 26, ma type SMA); long while the Short / long average ratio is above 1; execution delay 1; cost 0 bps one way. Signal-line approximation: ratio above its 9-day average: EMA Crossover (short window 12, long window 26); long while the Short / long EMA ratio is above its own 9-day average; execution delay 1; cost 0 bps one way.

Buy and hold, same daysValue
Largest one-day gain14.5% on 13 Oct 2008
Largest one-day loss-10.9% on 16 Mar 2020
CAGR without the 10 largest gains6.6%
CAGR without the 30 largest gains1.8%
CAGR without the 10 largest losses16.0%
CAGR without the 30 largest losses22.1%

The days replaced by 0 are the largest daily gains (or losses) of the window.

How MarketHeist computes it

Every choice an implementation has to make, as the code makes it today. The page is checked against the code each time it is built.

ChoiceHow it is computedIn the code
DataDaily bars (open, high, low, close, volume) of the fund as the MarketHeist data service serves them to the backtester: prices adjusted for splits and dividends, so a dividend counts as reinvested. They come from a snapshot taken each month and cut at the data month of this page, and are not rounded. The fund's own history, not an extension: a fund younger than the window is measured over the years it has.
WindowThe worked example and the lab measure the last 20 years of trading days, Oct 2006 to Sep 2026 (5030 days), ending at the data month of this page. Every setup, and buy and hold, is measured over exactly these days; an indicator is warmed up on the days before them, so changing a setting never moves the window, and a setting that needs more history than exists before the window is refused rather than measured over fewer days.
BacktestThe backtester's own engine, in the order it runs it: the indicator, the position rule (or entry and exit triggers) and the optional regime filter produce a position for every day of the fund's whole history; the position is then shifted forward by the execution delay and applied to each day's return over the window. Cash earns 0, there is no leverage, and a one-way cost in basis points is charged on the size of every change of position. Round trips are the closed entries of the trade log (a trade still open on the last day is not counted); the win rate is the share of them with a gain; the payoff ratio is the average win over the size of the average loss; expectancy is the average return per trade; the per-trade profit factor is the sum of the winning trades' returns over the size of the sum of the losing ones, while the per-day profit factor sums days.
Years and volatilityA year is 252 trading days, the engine's convention: trades per year is round trips over days divided by 252, the CAGR is the growth multiple to the power 252 over the days, and volatility is the sample standard deviation of the daily returns times the square root of 252.
Indicator statisticsThe indicator's main output over the window: its last value, its 10th, 50th and 90th percentile (linear interpolation between ranks), and the share of days the rule alone says long, before the delay and any regime filter. Every output of the indicator is also summarized by its median and the share of days below 0.
Buy and holdThe fund held every day of the window with dividends reinvested. The largest one-day gain and loss are the highest and lowest daily returns; the CAGR without the 10 or 30 largest gains (or losses) replaces those days' returns with 0 and recompounds.
Exponential averagepandas ewm(span = n).mean() with adjust = True: α = 2 ÷ (n + 1), weights (1 − α)ᵏ normalised over all data so far, no simple-average seed, defined from the first bar. The backtest's window starts long after the first bar, so the start-up weighting does not reach it.emapackages/shared/engine/utils.ts
SignalShort EMA ÷ long EMA of the adjusted close. A short span of 1 uses the raw price, which turns the rule into price against its long EMA.computepackages/shared/engine/indicators/ema_crossover.ts
RuleDefault threshold 1, direction above: invested while the ratio is strictly above 1, the MACD line strictly above zero. Default spans 12 and 26; the short span ranges from 1 to 200 and the long from 4 to 400.SPECpackages/shared/engine/indicators/ema_crossover.ts
Signal-line ruleNot available exactly. The crossover position rule compares the signal with its own simple moving average, so a crossover with a 9-bar window tests the EMA ratio against its 9-day simple average, an approximation of MACD against its 9-day EMA.generatePositionpackages/shared/engine/positions.ts
Engine functionsThe functions the portfolio app and the MarketHeist MCP tools run, called here on the same monthly returns.computePositionpackages/shared/engine/run_basic.tsgeneratePositionpackages/shared/engine/positions.tsapplyRegimeFilterpackages/shared/engine/regime_filter.tsgenerateTriggeredPositionpackages/shared/engine/triggered_position.tsrunBacktestpackages/shared/engine/backtest.tsgetIndicatorpackages/shared/engine/indicators/registry.ts

EMA crossover (12/26, the MACD line) compared with its neighbours

EMA crossover, simple-average crossover and the MACD rules
RuleInvested whileSpeedIn MarketHeist
EMA crossover 12/26 (MACD zero line)12-day EMA above 26-day EMAFastExactly: ema_crossover, threshold 1
SMA crossover 12/2612-day simple average above 26-dayFast, turns a little laterExactly: ma_crossover with SMA
MACD signal-line crossoverMACD line above its 9-day EMAVery fastApproximately: EMA ratio above its 9-day simple average
MACD histogram risingHistogram above its previous valueVery fastNot available
Golden cross (50/200 SMA)50-day above 200-day simple averageSlowExactly: ma_crossover 50/200

Limitations

  • Fast rules whipsaw. In sideways markets a 12/26 crossover can switch many times in a few months, and each false exit sells lower and buys back higher.
  • The example charges no trading costs. At several round trips a year, costs and taxes on realised gains matter more for this rule than for slow trend rules.
  • Cash earns nothing in the example; in years of high interest rates the months out of the market cost less than shown.
  • The signal-line version here is an approximation, not the textbook MACD signal-line rule, and its results can differ from a platform that computes the real signal line.
  • One fund and one window. Moving-average rules behave very differently on bonds, gold and stock markets with different trend patterns, which the robustness page compares.

Frequently asked questions

What is the MACD?
Moving average convergence divergence, an indicator Gerald Appel developed: the 12-day EMA minus the 26-day EMA (the MACD line), a 9-day EMA of that line (the signal line), and the gap between them (the histogram). It tracks whether short-term momentum is above or below longer-term momentum.
Is an EMA crossover the same as MACD?
The 12/26 EMA crossover is the same decision as the MACD line being above zero. Most MACD trading rules, though, use the signal-line crossover, the MACD line against its own 9-day EMA, which trades more often and is a different rule.
Why 12 and 26 days?
They are Appel's published settings, kept by convention ever since. Nothing makes them special for any market, which is why MarketHeist's robustness page tests the neighbouring lengths as well.
Does an EMA crossover react faster than a simple moving-average crossover?
For the same lengths, yes: the exponential average weights recent prices more, so it turns sooner, gets out and back in a little earlier, and trades a little more.
Can MarketHeist backtest the MACD signal-line crossover?
Not exactly. The backtester can compare the ratio of the two EMAs with its own simple moving average, which approximates the signal line, and it can test the MACD zero line exactly with the EMA crossover indicator.

References

  1. Appel, G. (2005) Technical Analysis: Power Tools for Active Investors. FT Prentice Hall. MACD, its signal line and histogram, by the indicator's author.
  2. Brock, W., Lakonishok, J. and LeBaron, B. (1992) Simple Technical Trading Rules and the Stochastic Properties of Stock Returns. Journal of Finance 47(5). Moving-average crossover rules on a century of index data.
  3. Murphy, J. J. (1999) Technical Analysis of the Financial Markets. New York Institute of Finance. Exponential averages and the MACD.

Try it on your own holdings

Open the 12/26 EMA crossover in the backtester →

Or ask an assistant connected to the MarketHeist MCP server (https://marketheist.io/mcp), which computes the same figures:

Using MarketHeist.io, backtest the 12/26 EMA crossover (the MACD line above zero) on SPY daily bars with execution delay 1 and compare CAGR, max drawdown and number of trades with buy-and-hold; then run the same EMA ratio against its own 9-day average (crossover rule) to approximate the MACD signal-line rule.

Ask an AI assistant

The prompt opens in a new tab, already filled in. An assistant without the MarketHeist connector answers from its own knowledge, not from the figures on this page.

Historical simulation, not advice. Computed by the MarketHeist portfolio engine from monthly total returns, data through Sep 2026. Markdown version of this page: ema-crossover.md.