scubamut
6/13/2019 - 8:53 AM

ZIPLINE PIPELINE ALGORITHM

# https://www.quantopian.com/help#Pipeline

from zipline import run_algorithm
from zipline.pipeline import Pipeline
from zipline.api import attach_pipeline, pipeline_output
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.factors import  SimpleMovingAverage, AverageDollarVolume

from datetime import datetime, timezone, timedelta
import pytz

def initialize(context):

    # Construct a simple moving average factor
    sma = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=10)

    # Construct a 30-day average dollar volume factor 
    dollar_volume = AverageDollarVolume(window_length=30)

    # Define high dollar-volume filter to be the top 10% of stocks by dollar volume.
    high_dollar_volume = dollar_volume.percentile_between(90, 100)

    # Set a screen on the pipelines to filter out securities.
    pipe_screen = ((sma > 1.0) & high_dollar_volume)

    # Create a columns dictionary
    pipe_columns = {'dollar_volume':dollar_volume, 'sma':sma}

    # Create, register and name a pipeline in initialize.
    pipe = Pipeline(columns=pipe_columns,screen=pipe_screen)
    attach_pipeline(pipe, 'example')

def before_trading_start(context, data):
    # Pipeline_output returns the constructed dataframe.
    output = pipeline_output('example')

    # Select and update your universe.
    context.my_securities = output.sort_values('sma', ascending=False).iloc[:50]
    print (len(context.my_securities))

    context.security_list = context.my_securities.index

    print("\n" + str(context.my_securities))
 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   
capital_base = 10000
start = datetime(2015, 1, 1, 0, 0, 0, 0, pytz.utc)
end = datetime(2016, 1, 1, 0, 0, 0, 0, pytz.utc)
 
    
result = run_algorithm(start = start, end = end, initialize=initialize,\
                capital_base=capital_base,\
                before_trading_start = before_trading_start, 
                bundle = 'etfs_bundle')