# def initialize(context):
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import ExponentialWeightedMovingAverage, EWMA
from quantopian.pipeline.factors.morningstar import MarketCap
from quantopian.research import run_pipeline
# def make_pipeline(context): context is optional and used only if make_pipeline will be used on an external variable
def make_pipeline():
mktcap = MarketCap()
mktcap_500 = mktcap.top(500)
#Calculates EMA for security
EMA20 = EWMA.from_span(inputs=[USEquityPricing.close], window_length=20, span=20, mask=mktcap_500)
EMA50 = EWMA.from_span(inputs=[USEquityPricing.close], window_length=50, span=50, mask=mktcap_500)
EMA200 = EWMA.from_span(inputs=[USEquityPricing.close], window_length=200, span=200, mask=mktcap_500)
#Checks if EMA is in uptrend
EMA2050_upcheck = (EMA20 > EMA50)
EMA50200_upcheck = (EMA50 > EMA200)
#Checks if EMA is in downtrend, could also use = ~ inversion filter
EMA2050_downcheck = (EMA20 < EMA50)
EMA50200_downcheck = (EMA50 < EMA200)
EMA_uptrend = (EMA2050_upcheck & EMA50200_upcheck)
#Create table and assign variables as columns
pipe_columns ={
'EMA20': EMA20,
'EMA50': EMA50,
'EMA200': EMA200,
'EMA2050_upcheck': EMA2050_upcheck,
'EMA50200_upcheck': EMA50200_upcheck,
'EMA2050_downcheck': EMA2050_downcheck,
'EMA50200_downcheck': EMA50200_downcheck,
'mktcap': mktcap
}
#outputs table with columns (can omit to remove columns), and screens to only show securities where EMA_uptrend is TRUE
return Pipeline(pipe_columns, screen = EMA_uptrend)
# def before_trading_start(context, data):
# def compute_weights(context):
# def rebalance(context,data):
# def record_vars(context, data):
my_pipe = make_pipeline()
#mktCap = MarketCap()
#my_pipe.add(mktCap, 'mktCap')
result = run_pipeline(my_pipe, '2012-05-17', '2012-05-17')
result.head()
from quantopian.pipeline.factors.morningstar import MarketCap
mktcap = MarketCap()
print mktcap