Hi,
I've been researching how to use the pipeline API, but all the documentation I've found seems somewhat incomplete. I'm trying to write a very simple algorithm that does the following.
- Creates a pipeline object
- Uses SMAs like in the example to narrow down the stocks
- Sort the stocks by ranking
- Purchase 1 share each of the top 5 stocks
- Uses SMAs like in the example to narrow down the stocks
For now I'm just trying to get a basic understanding of Pipeline, later I'd like to add factors like RSI and EMA, but I'll figure that out when I come to it.
I'm having trouble with the order function, I can't seem to figure out how to convert the pipeline results to symbol objects to be able to order. Any help would be greatly appreciated!
Thanks,
Bryce
Here's what I'm working with:
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 SimpleMovingAverage
from quantopian.pipeline.factors import RSI
from quantopian.pipeline.data import morningstar
def initialize(context):
pipe = Pipeline()
pipe = attach_pipeline(pipe, 'my_pipeline')
sma_short = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30)
sma_long = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=100)
# Combined factors to create new factors
sma_val = sma_short/sma_long
# Create and apply a screen to remove penny stocks
remove_penny_stocks = sma_short > 1.0
pipe.set_screen(remove_penny_stocks)
pipe.add(sma_short, 'sma_short')
pipe.add(sma_long, 'sma_long')
pipe.add(sma_val, 'sma_val')
# Rank a factor using a mask to ignore the values we're
# filtering out by passing mask=remove_penny_stocks to rank.
pipe.add(sma_val.rank(mask=remove_penny_stocks), 'sma_rank')
def before_trading_start(context):
context.output = pipeline_output('my_pipeline')
# Set the list of securities to short
context.short_list = context.output.sort(['sma_rank'], ascending=True).iloc[:200]
# Set the list of securities to long
context.long_list = context.output.sort(['sma_rank'], ascending=True).iloc[-200:]
# Update your universe with the SIDs of long and short securities
update_universe(context.long_list.index.union(context.short_list.index))
def handle_data(context, data):
for item in context.short_list[5:]:
stk = symbol(item)
order_target(stk,1)