QuantLearn
Trading Strategies
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 long and short position signals based on exponential moving average crossovers, showing typical signal delays.

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

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
1Exponential Moving Average
Exponential smoothing where α = 2/(N+1) and N is the period length. More recent prices have higher weights.
2Fast EMA Smoothing Factor
Smoothing factor for 5-period fast EMA, giving recent prices higher weight for responsiveness.
3Slow EMA Smoothing Factor
Smoothing factor for 34-period slow EMA, providing smoother long-term trend measurement.
4MACD Line Calculation
The core MACD oscillator representing momentum difference between fast and slow exponential moving averages.
5Position Signal Generation
Binary position signal: 1 for long positions when fast EMA is above slow EMA, 0 otherwise.
6Trading Signal Generation
Trading signals from position changes: +1 for buy signal, -1 for sell signal, 0 for no change.
7Portfolio Value Calculation
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
def ewmacd(signals, ma1, ma2):
signals['macd ma1'] = signals['Close'].ewm(span=ma1).mean()
signals['macd ma2'] = signals['Close'].ewm(span=ma2).mean()
return signalsUses exponential weighted moving averages (EWMA) instead of simple moving averages for smoother and more responsive trend detection.
Signal Generation Logic
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 signalsGenerates binary signals when fast MA crosses above/below slow MA. Uses diff() to create entry/exit signals from position changes.
Portfolio Management
# 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
- 1Choose appropriate periods for fast and slow moving averages (classic: 12 and 26, modern: 10 and 21)
- 2Calculate exponential weighted moving average for fast period (shorter lookback)
- 3Calculate exponential weighted moving average for slow period (longer lookback)
- 4Generate MACD oscillator = Fast EMA - Slow EMA
- 5Create binary positions: 1 when fast MA ≥ slow MA, 0 otherwise
- 6Generate trading signals using diff() of positions (1 = buy, -1 = sell)
- 7Apply position sizing and portfolio management rules
- 8Monitor for late entry signals characteristic of lagging indicators
Key Metrics
Risk Considerations
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:
# 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 analysisLearning Checkpoints
Understand Cointegration
Can you explain why two assets might be cointegrated and what breaks this relationship?
Interpret Statistical Tests
Practice reading ADF test results and understanding when to accept/reject cointegration.
Signal Generation
Implement Z-score calculations and understand threshold selection (±1σ vs ±2σ).
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.