from quantopian.pipeline import Pipeline
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline import CustomFactor
from quantopian.pipeline.filters import StaticAssets
import numpy as np
import alphalens
#import anything else as need be
#Momentum Custom Factor
class Momentum(CustomFactor):
def compute(self, today, asset_ids, out, values):
out[:] = values[-1] / values[0]
def make_pipeline():
portfolio = (StaticAssets(symbols([
'SPY',
'VEU',
'TLT',
])))
#put alpha to test here
moment = Momentum(inputs = [USEquityPricing.close], mask=portfolio, window_length = 252)
#specify any filters here into universe. Make sure alphas have .notnull() in universe.
universe = (moment.notnull())
#Use print statements to make sure the BETTER one is ranked HIGHER. Eg Rank 150 is BETTER than rank 149.
#first do it without ranking them, so you can ensure raw numbers make sense.
testingFactor = moment.rank(method='average',
ascending=True,
mask = universe)
#Seperate into the desired quantiles, top X%, whatever you want here.
longs = testingFactor.top(1)
#if long and short strategy, specify which sections you would long/short. Returns a pipeline object.
pipe = Pipeline(columns = {'testingFactor':testingFactor,
'Momentum': moment,
'long': longs},
screen = universe)
return pipe
#Makes a dataframe with the given universe, ranked by the testing factor.
results = run_pipeline(make_pipeline(), start_date = '2008-04-01', end_date = '2009-01-01')
#print the results to make sure it fuckin worked. Print once without rankings to verify.
results
#Gets each unique stock ticker and puts it in assets
assets = results.index.levels[1].unique()
#gets pricing data. Needs a month before and after. Dunno why.
pricing = get_pricing(assets, start_date='2008-03-01', end_date='2009-02-01', fields='open_price')
#Look up documentation to see how to customize this. This all organizes info so alphalens can get to work.
factor_data = alphalens.utils.get_clean_factor_and_forward_returns(factor = results['testingFactor'],
prices = pricing,
quantiles =3,
periods = (30,60))
# Runs alphalens
alphalens.tears.create_full_tear_sheet(factor_data)