Final Exam Algorithm Pipeline Basic starts here
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 CustomFactor, SimpleMovingAverage, AverageDollarVolume
from quantopian.pipeline.data import morningstar
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.classifiers.morningstar import Sector
import numpy as np
import pandas as pd
def initialize(context):
"""
Called once at the start of the program. Any one-time
startup logic goes here.
"""
# Define context variables that can be accessed in other methods of
# the algorithm.
context.long_leverage = 0.5
context.short_leverage = -0.5
#context.returns_lookback = 5
# Rebalance on the first trading day of each week at 11AM.
schedule_function(rebalance,
date_rules.week_start(days_offset=0),
time_rules.market_open(hours=1, minutes=30))
# Record tracking variables at the end of each day.
schedule_function(record_vars,
date_rules.every_day(),
time_rules.market_close(minutes=1))
# Create and attach an empty Pipeline.
pipe = Pipeline()
pipe = attach_pipeline(pipe, name='my_pipeline')
Page 5
MSc Finance/IWM/RMFE 2017/2018: Introduction to Algorithmic Trading BS0353
Author: AK
©Imperial College London 2017/2018
sma_10 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10)
sma_30 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=30)
sma_10_30 = sma_10/sma_30
low_sma = sma_10_30.percentile_between(0,10)
high_sma = sma_10_30.percentile_between(90,100)
# Construct a Filter.
prices_under_5 = (sma_10 < 5)
# Register outputs.
#pipe.add(sma_10, 'sma_10')
#pipe.add(sma_30, 'sma_30')
pipe.add(low_sma, 'low_sma')
pipe.add(high_sma, 'high_sma')
#pipe.add(securities_to_trade, 'securities_to_trade')
# Remove rows for which the Filter returns False.
pipe.set_screen(prices_under_5)
def before_trading_start(context, data):
# Access results using the name passed to attach_pipeline
.
context.output = pipeline_output('my_pipeline')
#print context.output.head(5)
# Store pipeline results for use by the rest of the algorithm.
#context.pipeline_results = context.output
# Sets the list of securities we want to long as the securities with a 'True'
# value in the high_sma column.
context.long_secs = context.output[context.output['high_sma']]
# Sets the list of securities we want to short as the securities with a 'True'
# value in the low_sma column.
context.short_secs = context.output[context.output['low_sma']]
# A list of the securities that we want to order today.
context.security_list = context.long_secs.index.union(context.short_secs.index).tolist()
# A set of the same securities, sets have faster lookup.
context.security_set = set(context.security_list)