I was looking for a MACD pipeline factor in the forum. I couldn't find one. I just wrote one and posting here as it might help someone. Please feel free to reply if you find any bug.
# Custom factor for MACD
class MACD(CustomFactor):
inputs = [USEquityPricing.close]
outputs = {'macd', 'signal','hist'}
window_length = 60
# The initial value for EMA is taken as trialing SMA
def ema(self, data, window):
import numpy as np
c = 2.0 / (window + 1)
ema = np.mean(data[-(2*window)+1:-window+1], axis=0)
for value in data[-window+1:]:
ema = (c * value) + ((1 - c) * ema)
return ema
def compute(self, today, assets, out, close):
fema = self.ema(close, 12)
sema = self.ema(close, 26)
macd_line = fema - sema
#Find trailing macd line
macd = []
macd.insert(0, self.ema(close,12) - self.ema(close,26))
for i in range(1,15, 1):
macd.insert(0, self.ema(close[:-i],12) - self.ema(close[:-i],26))
signal = self.ema(macd,9)
out.macd[:] = macd_line
out.signal[:] = signal
out.hist[:] = macd_line - signal