'MACD stock indicator function using ewm() from pandas library

Here is the test code for my macd function, however, the values I am getting are incorrect. I don't know if it is because my span is in days and my data is in 2 minute increments, or if it is a seperate issue. Any help would be much appreciated :)

import yfinance as yf
import pandas as pd
import pandas_ta as ta
import numpy as np
import datetime as dt
import time


dataTSLA = yf.download(tickers='TSLA', period='1mo', interval='2m', auto_adjust=True)


def indicatorMACD(data):
    exp1 = data['Close'].ewm(span=12, adjust=False).mean()
    exp2 = data['Close'].ewm(span=26, adjust=False).mean()
    macd = exp1 - exp2
    signalLine = macd.ewm(span=9, adjust=False).mean()
    return [macd, signalLine]

print(indicatorMACD(dataTSLA))

Getting an output of around 0.66 for macd and 0.23 for signal when it should be -0.23 and -0.64 respectively.



Solution 1:[1]

Use min_periods instead adjust code:

    import pandas as pd
    import pandas_datareader as pdr
    import matplotlib.pyplot as plt

df = pdr.DataReader('BTC-USD' , data_source='yahoo' , start='2020-01-01')
df

Function definition:

def MACD(DF,a,b,c):
    df=DF.copy()
    df['MA FAST'] = df['Close'].ewm(span=a , min_periods = a).mean()
    df['MA SLOW'] = df['Close'].ewm(span=b , min_periods = b).mean()
    df['MACD'] = df['MA FAST'] - df['MA SLOW']
    df['Signal'] = df['MACD'].ewm(span= c , min_periods = c).mean()  
    df.dropna(inplace=True)
    return df

Function call:

data = MACD(df , 12,26,9)
data

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mehdad