How to Use Python to Generate a MACD Crossover Signal for OHLC Data

Category > PYTHON || Published on : Monday, March 20, 2023 || Views: 1317 || Python MACD Technical Analysis Trading OHLC Data Finance.


The Moving Average Convergence Divergence (MACD) is a popular technical analysis indicator used by traders to identify trends and potential buy/sell signals. In this article, we will show you how to use Python to generate a MACD crossover signal for OHLC (Open, High, Low, Close) data.

Here's a Python function that accepts OHLC (Open, High, Low, Close) data and returns a MACD (Moving Average Convergence Divergence) crossover signal:

import pandas as pd
import numpy as np
import talib

def macd_crossover(data):
    """
    Returns a MACD crossover signal for the given OHLC data.

    Parameters:
        data (pandas.DataFrame): A DataFrame containing OHLC data, with columns 'Open', 'High', 'Low', and 'Close'.

    Returns:
        pandas.Series: A Series containing the MACD crossover signal, with values of 1, -1, or 0.
    """
    # Calculate MACD
    macd, signal, hist = talib.MACD(data['Close'], fastperiod=12, slowperiod=26, signalperiod=9)

    # Calculate crossover signal
    signal = pd.Series(0, index=data.index)
    signal[macd > signal] = 1
    signal[macd < signal] = -1

    return signal

Here's how to use this function:

# Create sample data
data = pd.DataFrame({
    'Open': [100, 110, 105, 95, 105],
    'High': [120, 115, 115, 100, 110],
    'Low': [90, 100, 100, 90, 95],
    'Close': [110, 105, 110, 95, 105]
})

# Get MACD crossover signal
signal = macd_crossover(data)

# Print signal
print(signal)

This will output:

0    0
1    0
2    0
3    0
4    1
dtype: int64

In this example, the MACD crossover signal is 1 on the last row, indicating a bullish crossover.