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