Skip to content
Home » Scripts » MACD Signal Trading

MACD Signal Trading

The Moving Average Convergence Divergence (MACD) is a popular technical analysis indicator used to identify trends and potential trading opportunities. It is constructed by calculating the difference between two exponential moving averages (EMAs) of varying periods, typically a 12-day EMA and a 26-day EMA. The MACD is then plotted along with a signal line, which is typically a 9-day EMA of the MACD.

Different uses for the MACD Indicator

The MACD indicator can be used to identify potential trading signals in various ways:

  1. Crossovers: A buy signal is generated when the MACD line crosses above the signal line, indicating a potential upward trend. Conversely, a sell signal is generated when the MACD line crosses below the signal line, suggesting a potential downward trend.
  2. Divergence: When the price of an asset diverges from the MACD, it can indicate a potential trend reversal. For instance, if the price reaches a new high but the MACD fails to reach a new high, it can signal a bearish divergence. On the other hand, if the price reaches a new low while the MACD doesn’t, it can indicate a bullish divergence.
  3. Centerline Crossovers: Buy signals can be generated when the MACD crosses above the zero line, indicating positive momentum. Sell signals can be generated when the MACD crosses below the zero line, suggesting negative momentum.

The Code

This code demonstrates a simple MACD crossover strategy, where it buys when the MACD line is above the signal line and sells when the MACD line is below the signal line. The algorithm uses the “SPY” symbol and daily data resolution. The MACD parameters are set with a 12-day EMA, a 26-day EMA, and a 9-day EMA for the signal line.

Click on the code to copy it to your clipboard.
Click here for detailed instructions on how to use the scripts in QuantConnect.

Python
from AlgorithmImports import *

class MACDCrossoverAlgorithm(QCAlgorithm):

    def Initialize(self):
        self.SetStartDate(2018, 1, 1)
        self.SetEndDate(2021, 1, 1)
        self.SetCash(100000)
        
        self.symbol = self.AddEquity("SPY", Resolution.Daily).Symbol

        # Initialize MACD with 12-day EMA, 26-day EMA, and 9-day EMA for the signal line
        self.macd = self.MACD(self.symbol, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily, Field.SevenBar)

        # Warm up the indicators
        self.SetWarmUp(self.macd.WarmUpPeriod)

    def OnData(self, data):
        if self.IsWarmingUp:
            return

        # Check if we have a MACD crossover signal
        if self.macd.Current.Value > self.macd.Signal.Current.Value:
            # Buy signal: go long if not already invested
            if not self.Portfolio[self.symbol].Invested:
                self.SetHoldings(self.symbol, 1.0)
        elif self.macd.Current.Value < self.macd.Signal.Current.Value:
            # Sell signal: liquidate if invested
            if self.Portfolio[self.symbol].Invested:
                self.Liquidate(self.symbol)
C#
using System;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace QuantConnect.Algorithm.CSharp
{
    public class MACDCrossoverAlgorithm : QCAlgorithm
    {
        private Symbol _symbol;
        private MovingAverageConvergenceDivergence _macd;

        public override void Initialize()
        {
            SetStartDate(2018, 1, 1);
            SetEndDate(2021, 1, 1);
            SetCash(100000);

            _symbol = AddEquity("SPY", Resolution.Daily).Symbol;

            // Initialize MACD with 12-day EMA, 26-day EMA, and 9-day EMA for the signal line
            _macd = MACD(_symbol, 12, 26, 9, MovingAverageType.Exponential, Resolution.Daily, Field.SevenBar);

            // Warm up the indicators
            SetWarmUp(_macd.WarmUpPeriod);
        }

        public override void OnData(Slice data)
        {
            if (IsWarmingUp)
            {
                return;
            }

            // Check if we have a MACD crossover signal
            if (_macd > _macd.Signal.Current.Value)
            {
                // Buy signal: go long if not already invested
                if (!Portfolio[_symbol].Invested)
                {
                    SetHoldings(_symbol, 1.0);
                }
            }
            else if (_macd < _macd.Signal.Current.Value)
            {
                // Sell signal: liquidate if invested
                if (Portfolio[_symbol].Invested)
                {
                    Liquidate(_symbol);
                }
            }
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *