from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.research import run_pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import Q3000US, StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage
from alphalens.utils import get_clean_factor_and_forward_returns
from alphalens.tears import create_full_tear_sheet
import talib
base_universe = Q3000US()
class Factor_N_Days_Ago(CustomFactor):
def compute(self, today, assets, out, input_factor):
out[:] = input_factor[0]
class sma(CustomFactor):
window_safe = True
sma50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50 )
sma200 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=200 )
inputs = [sma50,sma200]
window_length = 1
outputs = ["sma50","sma200"]
def compute(self, today, assets, out, sma50, sma200):
out.sma50[:] = sma50
out.sma200[:] = sma200
def make_pipeline():
sma50 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=50 )
sma200 = SimpleMovingAverage(inputs = [USEquityPricing.close], window_length=200 )
sma50_1, sma200_1 = sma()
sma200_lagged = Factor_N_Days_Ago([sma200_1], window_length=2)
sma50_lagged = Factor_N_Days_Ago([sma50_1], window_length=2)
crossover_condition= (sma200 < sma50) & (sma200_lagged > sma50_lagged )
return Pipeline(
columns={
'crossover_condition': crossover_condition,
},
screen= base_universe
)
result = run_pipeline(make_pipeline(), '2019-5-1', '2020-4-22')
asset_list = result.index.levels[1].unique()
pricing = get_pricing(asset_list,start_date="2019-4-5", end_date="2020-5-5", fields= "close_price" )
merged_data = get_clean_factor_and_forward_returns(result, pricing, quantiles= None, bins= [-1, .5, 2])
create_full_tear_sheet(merged_data)