Posts

Automated Trading with the MACD in Python

avatar of @chasmic-cosm
25
@chasmic-cosm
·
·
0 views
·
2 min read

Theory

The MACD consists of several exponential moving averages. It is a momentum indicator, basing trading signals on the rate of change of price for an asset.

A naïve strategy can be developed for the MACD by using the following assumptions:

  1. If the MACD is above the signal line, the price is moving upwards.
  2. If the MACD is below the signal line, the price is moving downwards.

These assumptions can be written in terms of the MACD histogram as follows:

  1. If the MACD histogram is positive, the price is moving upwards.
  2. If the MACD histogram is negative, the price is moving downwards.

This means that the zero crossings of the histogram are important since they denote changes in the direction of momentum. Since the goal is to buy when upward momentum starts and sell when downward momentum starts, a buy signal should be emitted when the histogram crosses from negative to positive, and a sell signal should be emitted when the histogram crosses from positive to negative.

Implementation

We need a function that decides when to buy and when to sell. This function is fed the market history and decides what to do based on the most recent state of the MACD.

import numpy as np 
 
def macd_strategy(ohlcv): 
    """ 
    Calculate the macd of a stock, decide whether to buy, sell, or hold based on signal behaviour 
    Inputs: 
        ohlcv:  numpy array -   A 5 x N matrix with rows corresponding to 
                                o, h, l, c, v respectively 
    Outputs: 
        status: string      -   "BUY", "SELL", or "HOLD" 
    """ 
    typical = ta.typical_price(ohlcv) 
    macd, macd_sig, macd_hist = ta.macd(typical) 
    macd_hist = macd_hist[::-1] # reversed MACD histogram 
     
    if macd_hist[0] > 0 and macd_hist[1] <= 0: 
        return "BUY" 
    elif macd_hist[0] < 0 and macd_hist[1] >= 0: 
        return "SELL" 
    else: 
        return "HOLD" 

Results

This is a very simplistic strategy for trading with the MACD. While it occasionally produces reliable signals, it is clear from the figure below that the MACD also produces a lot of false trade signals and should therefore not be used on its own.

Some of these spurious trading signals can be filtered out by combining the MACD with another indicator. Alternatively we could add some additional constraints to the macd_strategy method, for example only sending a signal if the MACD is positive.

Posted Using LeoFinance