Back to Community
Trailing Twelve Months (TTM) with As Of Date

Hi,

I'm new to Quantopian. Here's my first code contribution: an easy to use TTM CustomFactor. For good performance, it has a single expression Python list comprehension. Results are accurate for all sample cases I have tested so far.

class TrailingTwelveMonths(CustomFactor):  
    window_length=400  
    window_safe = True  
    mask=symbols  
    outputs="""  
        factor  
        asof_date  
        """.split()  
    def compute(self, today, assets, out, values, dates):  
        out.factor[:] = [  
            (v[d + np.timedelta64(52, 'W') > d[-1]])[  
                np.unique(  
                    d[d + np.timedelta64(52, 'W') > d[-1]],  
                    return_index=True  
                )[1]  
            ].sum()  
            for v, d in zip(values.T, dates.T)  
        ]  
        out.asof_date[:] = dates[-1]  
def make_pipeline():  
    (  
        total_revenue_ttm,  
        total_revenue_ttm_asof_date  
    ) = TrailingTwelveMonths(  
        inputs=[  
            Fundamentals.total_revenue,  
            Fundamentals.total_revenue_asof_date,  
        ]  
    )  
    return Pipeline(  
        columns={  
            'total_revenue_ttm': total_revenue_ttm,  
            'total_revenue_ttm_asof_date': total_revenue_ttm_asof_date  
        },  
        screen=symbols  
    )  
df = run_pipeline(make_pipeline(), '2017-11-03', '2017-11-03')  
df['total_revenue_ttm_asof_date'] = df['total_revenue_ttm_asof_date'].astype('datetime64[ns]')  
df  
Loading notebook preview...
Notebook previews are currently unavailable.
1 response

Thank you for your contribution! I'm new to Quantopian too, and this example helped me understand better how to work with Fundamental Data. I've been trying to compute the Pietroski F-Score and studying your workbook gave me some good ideas for how to get data for start-of-year, previous year, and current date, comparing across assets with varying reporting dates.