from time import time
from quantopian.pipeline import Pipeline
from quantopian.research import run_pipeline
from quantopian.pipeline import CustomFactor
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.fundamentals import IsPrimaryShare
from quantopian.pipeline.classifiers.fundamentals import Sector
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.data import Fundamentals, morningstar as mstar
import pandas as pd
import numpy as np
class Previous(CustomFactor):
# Returns value of input x trading days ago where x is the window_length
# Both the inputs and window_length must be specified as there are no defaults
def compute(self, today, assets, out, inputs):
out[:] = inputs[0]
class PreviousAsOf(CustomFactor):
# Returns value of input x trading days ago where x is the window_length
# Both the inputs and window_length must be specified as there are no defaults
dtype = np.dtype('datetime64[ns]')
def compute(self, today, assets, out, inputs):
out[:] = inputs[0]
class LastFourQuarters(CustomFactor):
# Get the last 4 reported values of the given asof_date + field.
outputs = ['q1', 'q2', 'q3', 'q4']
window_length = 195 + 65
def compute(self, today, assets, out, asof_date, values):
for column_ix in range(asof_date.shape[1]):
_, unique_indices = np.unique(asof_date[:, column_ix], return_index=True)
quarterly_values = values[unique_indices, column_ix]
if len(quarterly_values) < 4:
quarterly_values = np.hstack([
np.repeat([np.nan], 4 - len(quarterly_values)),
quarterly_values,
])
quarterly_values = quarterly_values[-4:]
out[column_ix] = quarterly_values
class LastFourQuartersAsOfDates(CustomFactor):
# Get the last 4 unique values of a given asof_date.
outputs = ['q1_asof', 'q2_asof', 'q3_asof', 'q4_asof']
window_length = 195 + 65
dtype = np.dtype('datetime64[ns]')
def compute(self, today, assets, out, asof_date):
for column_ix in range(asof_date.shape[1]):
unique_dates, _ = np.unique(asof_date[:, column_ix], return_index=True)
if len(unique_dates) < 4:
unique_dates = np.hstack([
np.repeat([np.datetime64('NaT')], 4 - len(unique_dates)),
unique_dates,
])
unique_dates = unique_dates[-4:]
out[column_ix] = unique_dates
class FormType(CustomFactor):
# Get the Formtype of a given asof_date.
outputs = ['q1_form', 'q2_form', 'q3_form', 'q4_form']
window_length = 195 + 65
def compute(self, today, assets, out, asof_date, form_type):
for column_ix in range(asof_date.shape[1]):
_, unique_indices = np.unique(asof_date[:, column_ix], return_index=True)
form_types = form_type[unique_indices, column_ix]
types_to_num = {'6-K': 1., '10-Q/A': 2., 'Quarterly': 3. , '10-Q': 10. , 'Quarterly': 4. }
result = np.zeros(form_types.shape)
i = 0
for key in form_types:
val = types_to_num.get(key, -1.)
result[i] = val
i = i + 1
if len(result) < 4:
result = np.hstack([
np.repeat([0], 4 - len(result)),
result,
])
result = result[-4:]
out[column_ix] = result