Notebook
In [1]:
from quantopian.research import run_pipeline
from quantopian.pipeline import Pipeline
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.factors import Returns, SimpleBeta, SimpleMovingAverage
import quantopian.optimize as opt
from quantopian.pipeline.filters import QTradableStocksUS, StaticAssets
from quantopian.pipeline.classifiers.morningstar import Sector
import pandas as pd

WINDOW_LENGTH_REGRESS = 253 # days, length of window for returns forecast model
N_STOCKS = 250 # equal long & short, total positions: 2*NSTOCKS

def normalize(x):
    r = x - x.mean()
    return r/r.abs().sum()
In [2]:
QTU = QTradableStocksUS()
sectors = [101,102,103,104,205,206,207,308,309,310,311]
returns = Returns(window_length=2, mask=(QTU|StaticAssets(symbols(['SPY']))))
beta = SimpleBeta(target=symbols(8554),regression_length=WINDOW_LENGTH_REGRESS,allowed_missing_percentage=1.0)
return_SPY = SimpleMovingAverage(inputs=[returns[symbols('SPY')]],window_length=20)
returns_average = SimpleMovingAverage(inputs=[returns],window_length=20)
pipeline_columns = {}
for s in sectors:
    alpha = SimpleMovingAverage(inputs=[returns],window_length=WINDOW_LENGTH_REGRESS,mask=QTU&Sector().eq(s))-beta*SimpleMovingAverage(inputs=[returns[symbols(8554)]],window_length=WINDOW_LENGTH_REGRESS)
    returns_forecast = beta*return_SPY + alpha
    pipeline_columns['sector_'+str(s)] = (returns_forecast-returns_average).zscore()
In [3]:
pipe = Pipeline(columns = pipeline_columns, screen = QTU)
results = run_pipeline(pipe, '2016-04-01', '2017-12-19')

Pipeline Execution Time: 53.33 Seconds
In [4]:
results.head(4)
Out[4]:
sector_101 sector_102 sector_103 sector_104 sector_205 sector_206 sector_207 sector_308 sector_309 sector_310 sector_311
2016-04-01 00:00:00+00:00 Equity(2 [ARNC]) 0.915835 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
Equity(24 [AAPL]) NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN -0.527322
Equity(31 [ABAX]) NaN NaN NaN NaN NaN -0.956252 NaN NaN NaN NaN NaN
Equity(39 [DDC]) 0.289189 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
In [5]:
alpha = results.sum(axis=1).dropna()
In [6]:
alpha.head(4)
Out[6]:
2016-04-01 00:00:00+00:00  Equity(2 [ARNC])     0.915835
                           Equity(24 [AAPL])   -0.527322
                           Equity(31 [ABAX])   -0.956252
                           Equity(39 [DDC])     0.289189
dtype: float64
In [7]:
alpha = normalize(pd.Series().append(alpha.nlargest(N_STOCKS)).append(alpha.nsmallest(N_STOCKS)))
In [8]:
alpha.head(4)
Out[8]:
(2017-07-31 00:00:00+00:00, Equity(15697 [OCN]))     0.003943
(2016-04-05 00:00:00+00:00, Equity(13306 [SUNE]))    0.003486
(2016-05-24 00:00:00+00:00, Equity(16999 [SRPT]))    0.003049
(2017-04-28 00:00:00+00:00, Equity(15697 [OCN]))     0.002974
dtype: float64