from quantopian.algorithm import attach_pipeline,pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume,SimpleMovingAverage
from quantopian.pipeline.filters.morningstar import Q1500US
from quantopian.pipeline.data import morningstar
def initialize(context):
schedule_function(rebalance,date_rules.week_start(),time_rules.market_open(hours=1))
my_pipe = make_pipeline()
attach_pipeline(my_pipe,'my_pipeline')
def rebalance(context,data):
for security in context.portfolio.positions:
if security not in context.longs and security not in context.shorts and data.can_trade(security):
order_target_percent(security,0.0)
for security in context.longs:
if data.can_trade(security):
order_target_percent(security,context.long_weights)
for security in context.shorts:
if data.can_trade(security):
order_target_percent(security,context.short_weights)
def my_compute_weights(context):
if len(context.longs)==0:
long_weights=0
else:
long_weights=0.5/ len(context.longs)
if len(context.shorts)==0:
short_weights=0
else:
short_weights= -0.5/ len(context.shorts)
return ( long_weights,short_weights)
def before_trading_starts(context,data):
context.output= pipeline_output('my_pipeline')
#longs
context.longs=context.output[context.output['longs']].index.tolist()
#short
context.shorts= context.output[context.output['shorts']].index.tolist()
context.long_weights,context.short_weights= my_compute_weights(context)
def make_pipeline():
#Universe Q1500US()
base_universe= Q1500US()
#Energy sector
sector= morningstar.asset_classification.morningstar_sector_code.latest
energy_sector=sector.eq(309)
#combine the mask
base_energy= base_universe & energy_sector
# dollar volume 30 days
dollar_volume= AverageDollarVolume(window_length=30)
# grab top 5% of stocks
high_dollar_volume= dollar_volume.percentile_between(95,100)
#combine filters
top_five_base_energy= base_energy & high_dollar_volume
# 10day mean close
mean_10= SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=10, mask=top_five_base_energy)
# 30 Day Mean close
mean_30 = SimpleMovingAverage(inputs=[USEquityPricing.close],window_length=30, mask=top_five_base_energy)
#Percent difference
percent_diff=(mean_10-mean_30)/mean_30
#List of shorts
shorts= percent_diff < 0
#List of longs
longs= percent_diff > 0
#Final mask/filter for anything in shorts and longs
securities_to_trade= (shorts| longs)
#retrun pipleine
return Pipeline(columns={'longs':longs,'shorts':shorts,'perc_diff':percent_diff},screen=securities_to_trade)