Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Advanced Custom Factor - Trailing 12M As Of Date

Hi,

The goal is to create a CustomFactor that returns the last 4 quarters of Earnings Surprise data.
I started with Doug Baldwin's TTM, that creates a sum of the last 12 months of revenue data.

I changed the CustomFactor to try and return a list of matching values, rather than a sum:

universe = StaticAssets(symbols(['AAPL','IBM']))  
#universe = StaticAssets(symbols(['AAPL']))  
#universe = QTradableStocksUS()  
class Last4QAsOf(CustomFactor):  
    window_length=400  
    window_safe = True  
    #mask=universe  
    outputs = ['fq0', 'fq1', 'fq2', 'fq3', 'asof_date']  
    def compute(self, today, assets, out, values, dates):  
        tmpArray = ([  
            ((v[(d + np.timedelta64(52, 'W')) > d[-1]])[  
                np.unique(  
                    d[d + np.timedelta64(52, 'W') > d[-1]],  
                    return_index=True  
                )[1]  
            ])  
            for v, d in zip(values.T, dates.T)  
        ])  
        if len(tmpArray[0]) < 4:  
            tmpArray[0]=[-99,-99,-99,-99]  
        (out.fq3[:],out.fq2[:],out.fq1[:],out.fq0[:]) = tmpArray[0]  
        out.asof_date[:] = dates[-1].astype('datetime64[ns]')  
def make_pipeline():  
    (  
        fq0s,  
        fq1s,  
        fq2s,  
        fq3s,  
        asof_date  
    ) = Last4QAsOf(  
        inputs=[  
            EarningsSurprises.eps_pct_diff_surp,  
            EarningsSurprises.asof_date,  
        ]  
    )  
    return Pipeline(  
        columns={  
            'eps0': EarningsSurprises.eps_act.latest,  
            'price': USEquityPricing.close.latest,  
            'fwd_pe' : Fundamentals.forward_pe_ratio.latest,  
            'q0': fq0s,  
            'q1': fq1s,  
            'q2': fq2s,  
            'q3': fq3s,  
            'asof': asof_date  
        },  
        screen=universe)  
po = run_pipeline(make_pipeline(), '2017-1-01', '2017-11-03')  

If I use a single symbol universe (the commented out AAPL line) - it works.
But if I have use an array StaticAssets(symbols(['AAPL','IBM'])) , it fails - with both stocks having the same data.
And if I use the universe ( QTradableStocksUS()), it crashes.
There is some issue with the CustomFactor -- but can't for the life of me, figure it out. H-E-L-P!