W

WquGuru·QuantLearn

MomentumBeginner

MACD Oscillator

Moving average convergence divergence signals

MACD vs Awesome Oscillator Performance

Comparative analysis between MACD and Awesome Oscillator strategies, demonstrating trade execution differences and performance metrics.

MACD Trading Positions

MACD Trading Positions

MACD long and short position signals based on exponential moving average crossovers, showing typical signal delays.

MACD Oscillator Values

MACD Oscillator Values

MACD oscillator histogram showing the difference between fast and slow EMAs, with bar chart visualization.

Comparative Performance

Comparative Performance

Portfolio performance comparison showing MACD vs Awesome Oscillator asset values over time, highlighting different risk-return profiles.

Momentum Trading Theory

MACD compares short-term and long-term moving averages to identify momentum shifts and trend changes.

The classic implementation uses exponential weighted moving averages (EWMA) for smoother response to price changes.

The oscillator shows the difference between fast and slow moving averages, creating convergence and divergence patterns.

When short MA > long MA, positions are long (momentum is bullish); when short MA < long MA, positions are cleared.

The strategy originated in the 1970s and remains one of the most widely used technical indicators.

MACD works on the principle that short-term momentum has more impact than long-term trends during trend changes.

Mathematical Foundation

1
Exponential Moving Average

EMAt=αPricet+(1α)EMAt1EMA_t = \alpha \cdot Price_t + (1-\alpha) \cdot EMA_{t-1}

Exponential smoothing where α = 2/(N+1) and N is the period length. More recent prices have higher weights.

2
Fast EMA Smoothing Factor

αfast=2Nfast+1=25+1=13\alpha_{fast} = \frac{2}{N_{fast} + 1} = \frac{2}{5 + 1} = \frac{1}{3}

Smoothing factor for 5-period fast EMA, giving recent prices higher weight for responsiveness.

3
Slow EMA Smoothing Factor

αslow=2Nslow+1=234+1=235\alpha_{slow} = \frac{2}{N_{slow} + 1} = \frac{2}{34 + 1} = \frac{2}{35}

Smoothing factor for 34-period slow EMA, providing smoother long-term trend measurement.

4
MACD Line Calculation

MACDt=EMAfast,tEMAslow,tMACD_t = EMA_{fast,t} - EMA_{slow,t}

The core MACD oscillator representing momentum difference between fast and slow exponential moving averages.

5
Position Signal Generation

Positiont={1if EMAfast,tEMAslow,t0if EMAfast,t<EMAslow,tPosition_t = \begin{cases} 1 & \text{if } EMA_{fast,t} \geq EMA_{slow,t} \\ 0 & \text{if } EMA_{fast,t} < EMA_{slow,t} \end{cases}

Binary position signal: 1 for long positions when fast EMA is above slow EMA, 0 otherwise.

6
Trading Signal Generation

Signalt=PositiontPositiont1Signal_t = Position_t - Position_{t-1}

Trading signals from position changes: +1 for buy signal, -1 for sell signal, 0 for no change.

7
Portfolio Value Calculation

Portfoliot=Holdingst+Casht=PositiontPricetShares+(Capital0i=1tSignaliPriceiShares)Portfolio_t = Holdings_t + Cash_t = Position_t \cdot Price_t \cdot Shares + (Capital_0 - \sum_{i=1}^{t} Signal_i \cdot Price_i \cdot Shares)

Total portfolio value combining current holdings and remaining cash after cumulative trades.

MACD Implementation Algorithm

The MACD oscillator uses exponential weighted moving averages for smooth trend detection and simple crossover logic for signal generation.

Exponential Moving Average Calculation

python
def ewmacd(signals, ma1, ma2):
    signals['macd ma1'] = signals['Close'].ewm(span=ma1).mean()    
    signals['macd ma2'] = signals['Close'].ewm(span=ma2).mean()   
    return signals

Uses exponential weighted moving averages (EWMA) instead of simple moving averages for smoother and more responsive trend detection.

Signal Generation Logic

python
def signal_generation(df, method, ma1, ma2):
    signals = method(df, ma1, ma2)
    signals['macd positions'] = 0
    signals['macd positions'][ma1:] = np.where(
        signals['macd ma1'][ma1:] >= signals['macd ma2'][ma1:], 1, 0)
    signals['macd signals'] = signals['macd positions'].diff()
    signals['macd oscillator'] = signals['macd ma1'] - signals['macd ma2']
    return signals

Generates binary signals when fast MA crosses above/below slow MA. Uses diff() to create entry/exit signals from position changes.

Portfolio Management

python
# Portfolio allocation and performance tracking
capital0 = 5000
positions = 100

portfolio['macd holding'] = signals['macd positions'] * portfolio['Close'] * positions
portfolio['macd cash'] = capital0 - (signals['macd signals'] * portfolio['Close'] * positions).cumsum()
portfolio['macd asset'] = portfolio['macd holding'] + portfolio['macd cash']
portfolio['macd return'] = portfolio['macd asset'].pct_change()

Tracks portfolio value by combining holdings (positions × price × shares) with remaining cash after trades.

Implementation Steps

  1. 1Choose appropriate periods for fast and slow moving averages (classic: 12 and 26, modern: 10 and 21)
  2. 2Calculate exponential weighted moving average for fast period (shorter lookback)
  3. 3Calculate exponential weighted moving average for slow period (longer lookback)
  4. 4Generate MACD oscillator = Fast EMA - Slow EMA
  5. 5Create binary positions: 1 when fast MA ≥ slow MA, 0 otherwise
  6. 6Generate trading signals using diff() of positions (1 = buy, -1 = sell)
  7. 7Apply position sizing and portfolio management rules
  8. 8Monitor for late entry signals characteristic of lagging indicators

Key Metrics

MACD oscillator value and direction (positive = bullish, negative = bearish)
Moving average crossover frequency and timing
Signal delay compared to actual price trend changes
Win rate and average profit per trade
Maximum drawdown during false signal periods
Sharpe ratio compared to buy-and-hold strategy

Risk Considerations

Lagging indicator nature - signals typically come after significant price moves have occurred
False signals and whipsaws in sideways or choppy market conditions
Performs poorly during range-bound markets with no clear trend direction
Entry signals are often delayed, resulting in missed profit opportunities
Exponential smoothing can create "downward EMA spirals" during rapid trend reversals
Works best in trending markets but struggles to identify trend beginnings early

Practice Implementation

Prerequisites

Mathematical Background

  • • Linear regression and OLS estimation
  • • Time series analysis (stationarity, unit roots)
  • • Hypothesis testing and p-values
  • • Basic econometrics (error correction models)

Technical Skills

  • • Python programming (pandas, numpy)
  • • Statistical libraries (statsmodels)
  • • Data visualization (matplotlib)
  • • Financial data handling (yfinance)

Complete Implementation

Access the full Python implementation from the original quantitative trading repository:

bash
# Complete pair trading implementation
git clone https://github.com/je-suis-tm/quant-trading.git
cd quant-trading
python "Pair trading backtest.py"
# Modify tickers and parameters for your own analysis

Learning Checkpoints

1

Understand Cointegration

Can you explain why two assets might be cointegrated and what breaks this relationship?

2

Interpret Statistical Tests

Practice reading ADF test results and understanding when to accept/reject cointegration.

3

Signal Generation

Implement Z-score calculations and understand threshold selection (±1σ vs ±2σ).

4

Risk Management

Understand position sizing, monitoring regime changes, and exit strategies.

Recommended Learning Path

Immediate Actions

  • Download and run the Python script
  • Test with different asset pairs
  • Experiment with threshold parameters

Advanced Studies

  • Learn Johansen cointegration test
  • Study Vector Error Correction Models
  • Explore multiple asset pair trading

Important Disclaimer

This strategy involves significant risk. Historical cointegration relationships can break permanently. Always use proper risk management, position sizing, and never risk more than you can afford to lose. Paper trade extensively before using real capital.

Quick Navigation