Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Build a CustomFactor EMA and MACD?

There is built-in factor SMA.

Has someone idea to build a CustomFactor EMA and MACD?

4 responses

a little late response but for someone who searches later - two different variations below:

class MACD(CustomFactor):

inputs=[USEquityPricing.close]  
window_length = 40

def compute(self, today, assets, out, close):  
    ema12 = pd.stats.moments.ewma(close, span=12)  
    ema26 = pd.stats.moments.ewma(close, span=26)  
    signal = pd.stats.moments.ewma(ema12[-10:] - ema26[-10:], span=9)  
    out[:] = (ema12[-1] - ema26[-1]) - signal[-1]

class MACD(CustomFactor):
inputs = [USEquityPricing.close]
window_length = 40

def compute(self, today, assets, out, close):

    sig_lines = []

    for col in close.T:  
            # get signal line only  
        try:  
            macd, signal, hist = talib.MACD(col, fastperiod=12, slowperiod=26, signalperiod=9)  
            sig_lines.append(macd[-1] - signal[-1])  
            # if error calculating, return NaN  
        except:  
            sig_lines.append(np.nan)  

    out[:] = sig_lines  

oh and ewma

ewma12 = ewma.from_span([USEquityPricing.close], window_length=12, span=6)

Hi Hasan,

Thanks much for your answer. In your first post you've posted two alternatives of MACD-Factor. I've tried them but find the values are "quite" different. Have you also tried them?

Thomas

And to the EWMA, is the EWMA the same as EMA?

Cheers