Back to Community
Cash Algo Tests

Trading 90% of Cash:

Clone Algorithm
28
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor, AverageDollarVolume
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar, builtin
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage
import numpy as np
import pandas as pd


class UniverseFilter(CustomFactor):  

    window_length = 1  
    inputs = [morningstar.share_class_reference.is_primary_share,  
              morningstar.share_class_reference.is_depositary_receipt,  
              morningstar.asset_classification.morningstar_sector_code]  
    def compute(self, today, assets, out, is_primary_share, is_depositary_receipt, sector_code):  
        def accept_symbol(equity):  
            symbol = equity.symbol  
            if symbol.endswith("_PR") or symbol.endswith("_WI") or symbol.endswith("_WD") or                                             symbol.endswith("_VJ") or symbol.endswith("_H") or symbol.endswith("_V") or symbol.endswith("_A"):  
                return False  
            else:  
                return True  
 
        vsid = np.vectorize(sid)  
        equities = vsid(assets)   
        vaccept_symbol = np.vectorize(accept_symbol)  
        accept_symbol = vaccept_symbol(equities)  
        criteria = accept_symbol
        criteria = criteria
        out[:] = criteria.astype(float)  
        
 

class MessageVolume(CustomFactor):
                    
    inputs = [stocktwits.bearish_intensity]
    window_length = 25
    def compute(self, today, assets, out, msgs):
        out[:] = -np.nansum(msgs, axis=0)
        
   

                    
    
    
    
def make_pipeline():

    bullish = MessageVolume()
    universefilter = UniverseFilter() 
    initial_screen = filter_universe()
    combined_rank = (bullish.rank(mask=initial_screen) + universefilter.rank(mask=initial_screen))
    
    N = 3
    
    longs = combined_rank.top(N) 
    pipe_screen = (longs)

    pipe_columns = {'longs':longs,
        'combined_rank':combined_rank,
        'bullish':bullish,
        'universefilter':universefilter}
    
    pipe = Pipeline(columns = pipe_columns, screen = pipe_screen)
    return pipe



                    
    
    
    
def initialize(context):
    
    set_long_only()   
    set_commission(commission.PerShare(cost=0.00, min_trade_cost=0.0))
     
    attach_pipeline(make_pipeline(), 'ranking_example')

    context.dont_buys = security_lists.leveraged_etf_list
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.week_start(),
                      time_rule=time_rules.market_open(minutes=30),
                      half_days=True)

    schedule_function(func=clean_out,
                      date_rule=date_rules.week_end(),
                      time_rule=time_rules.market_open(minutes=90))


    
                       
        
        
        
        
def before_trading_start(context, data):

    output = pipeline_output('ranking_example')
    ranks = output['combined_rank']
    long_ranks = ranks[output['longs']]
    context.long_weights = (long_ranks / long_ranks.sum())

  

                    
    
    
    
#def handle_data(context, data):

    #record(leverage=context.account.leverage)
    #pass     
                    
   
 
    
    
    
    
def rebalance(context, data):
    
    n = 3
    context.security_set = set(context.long_weights.index)
    

    for stock in context.security_set:
        order_check=len(get_open_orders(stock)) 
        if ((stock in context.long_weights.index) & (order_check ==0)):
            order_value(stock, .9*(context.account.settled_cash / n))                 
                  

def clean_out(context, data):

    for stock in context.security_set:
        order_target_percent(stock, 0.0)                 
 

                    
            
        
        
        
        
def filter_universe():

    common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()
    have_data = morningstar.valuation.market_cap.latest.notnull()
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~morningstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet &
                       have_data & not_otc & not_wi & not_depository & primary_share)
    
    high_volume_tradable = (AverageDollarVolume(window_length=5,
    mask=tradable_filter).percentile_between(50, 100))    
    
    USEP = builtin.USEquityPricing
    
    above_5 = (SimpleMovingAverage(inputs=[USEP.close], window_length=3,                                  mask=high_volume_tradable).percentile_between(10,37))   
    
    screen = above_5

    return screen
                    
           
        
There was a runtime error.
4 responses

Trading 50% of Cash:

Clone Algorithm
28
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor, AverageDollarVolume
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar, builtin
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage
import numpy as np
import pandas as pd


class UniverseFilter(CustomFactor):  

    window_length = 1  
    inputs = [morningstar.share_class_reference.is_primary_share,  
              morningstar.share_class_reference.is_depositary_receipt,  
              morningstar.asset_classification.morningstar_sector_code]  
    def compute(self, today, assets, out, is_primary_share, is_depositary_receipt, sector_code):  
        def accept_symbol(equity):  
            symbol = equity.symbol  
            if symbol.endswith("_PR") or symbol.endswith("_WI") or symbol.endswith("_WD") or                                             symbol.endswith("_VJ") or symbol.endswith("_H") or symbol.endswith("_V") or symbol.endswith("_A"):  
                return False  
            else:  
                return True  
 
        vsid = np.vectorize(sid)  
        equities = vsid(assets)   
        vaccept_symbol = np.vectorize(accept_symbol)  
        accept_symbol = vaccept_symbol(equities)  
        criteria = accept_symbol
        criteria = criteria
        out[:] = criteria.astype(float)  
        
 

class MessageVolume(CustomFactor):
                    
    inputs = [stocktwits.bearish_intensity]
    window_length = 25
    def compute(self, today, assets, out, msgs):
        out[:] = -np.nansum(msgs, axis=0)
        
   

                    
    
    
    
def make_pipeline():

    bullish = MessageVolume()
    universefilter = UniverseFilter() 
    initial_screen = filter_universe()
    combined_rank = (bullish.rank(mask=initial_screen) + universefilter.rank(mask=initial_screen))
    
    N = 3
    
    longs = combined_rank.top(N) 
    pipe_screen = (longs)

    pipe_columns = {'longs':longs,
        'combined_rank':combined_rank,
        'bullish':bullish,
        'universefilter':universefilter}
    
    pipe = Pipeline(columns = pipe_columns, screen = pipe_screen)
    return pipe



                    
    
    
    
def initialize(context):
    
    set_long_only()   
    set_commission(commission.PerShare(cost=0.00, min_trade_cost=0.0))
     
    attach_pipeline(make_pipeline(), 'ranking_example')

    context.dont_buys = security_lists.leveraged_etf_list
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.week_start(),
                      time_rule=time_rules.market_open(minutes=30),
                      half_days=True)

    schedule_function(func=clean_out,
                      date_rule=date_rules.week_end(),
                      time_rule=time_rules.market_open(minutes=90))


    
                       
        
        
        
        
def before_trading_start(context, data):

    output = pipeline_output('ranking_example')
    ranks = output['combined_rank']
    long_ranks = ranks[output['longs']]
    context.long_weights = (long_ranks / long_ranks.sum())

  

                    
    
    
    
#def handle_data(context, data):

    #record(leverage=context.account.leverage)
    #pass     
                    
   
 
    
    
    
    
def rebalance(context, data):
    
    n = 3
    context.security_set = set(context.long_weights.index)
    

    for stock in context.security_set:
        order_check=len(get_open_orders(stock)) 
        if ((stock in context.long_weights.index) & (order_check ==0)):
            order_value(stock, .5*(context.account.settled_cash / n))                 
                  

def clean_out(context, data):

    for stock in context.security_set:
        order_target_percent(stock, 0.0)                 
 

                    
            
        
        
        
        
def filter_universe():

    common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()
    have_data = morningstar.valuation.market_cap.latest.notnull()
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~morningstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet &
                       have_data & not_otc & not_wi & not_depository & primary_share)
    
    high_volume_tradable = (AverageDollarVolume(window_length=5,
    mask=tradable_filter).percentile_between(50, 100))    
    
    USEP = builtin.USEquityPricing
    
    above_5 = (SimpleMovingAverage(inputs=[USEP.close], window_length=3,                                  mask=high_volume_tradable).percentile_between(10,37))   
    
    screen = above_5

    return screen
                    
           
        
There was a runtime error.

Trading 10% of Cash:

Clone Algorithm
28
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor, AverageDollarVolume
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar, builtin
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage
import numpy as np
import pandas as pd


class UniverseFilter(CustomFactor):  

    window_length = 1  
    inputs = [morningstar.share_class_reference.is_primary_share,  
              morningstar.share_class_reference.is_depositary_receipt,  
              morningstar.asset_classification.morningstar_sector_code]  
    def compute(self, today, assets, out, is_primary_share, is_depositary_receipt, sector_code):  
        def accept_symbol(equity):  
            symbol = equity.symbol  
            if symbol.endswith("_PR") or symbol.endswith("_WI") or symbol.endswith("_WD") or                                             symbol.endswith("_VJ") or symbol.endswith("_H") or symbol.endswith("_V") or symbol.endswith("_A"):  
                return False  
            else:  
                return True  
 
        vsid = np.vectorize(sid)  
        equities = vsid(assets)   
        vaccept_symbol = np.vectorize(accept_symbol)  
        accept_symbol = vaccept_symbol(equities)  
        criteria = accept_symbol
        criteria = criteria
        out[:] = criteria.astype(float)  
        
 

class MessageVolume(CustomFactor):
                    
    inputs = [stocktwits.bearish_intensity]
    window_length = 25
    def compute(self, today, assets, out, msgs):
        out[:] = -np.nansum(msgs, axis=0)
        
   

                    
    
    
    
def make_pipeline():

    bullish = MessageVolume()
    universefilter = UniverseFilter() 
    initial_screen = filter_universe()
    combined_rank = (bullish.rank(mask=initial_screen) + universefilter.rank(mask=initial_screen))
    
    N = 3
    
    longs = combined_rank.top(N) 
    pipe_screen = (longs)

    pipe_columns = {'longs':longs,
        'combined_rank':combined_rank,
        'bullish':bullish,
        'universefilter':universefilter}
    
    pipe = Pipeline(columns = pipe_columns, screen = pipe_screen)
    return pipe



                    
    
    
    
def initialize(context):
    
    set_long_only()   
    set_commission(commission.PerShare(cost=0.00, min_trade_cost=0.0))
     
    attach_pipeline(make_pipeline(), 'ranking_example')

    context.dont_buys = security_lists.leveraged_etf_list
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.week_start(),
                      time_rule=time_rules.market_open(minutes=30),
                      half_days=True)

    schedule_function(func=clean_out,
                      date_rule=date_rules.week_end(),
                      time_rule=time_rules.market_open(minutes=90))


    
                       
        
        
        
        
def before_trading_start(context, data):

    output = pipeline_output('ranking_example')
    ranks = output['combined_rank']
    long_ranks = ranks[output['longs']]
    context.long_weights = (long_ranks / long_ranks.sum())

  

                    
    
    
    
#def handle_data(context, data):

    #record(leverage=context.account.leverage)
    #pass     
                    
   
 
    
    
    
    
def rebalance(context, data):
    
    n = 3
    context.security_set = set(context.long_weights.index)
    

    for stock in context.security_set:
        order_check=len(get_open_orders(stock)) 
        if ((stock in context.long_weights.index) & (order_check ==0)):
            order_value(stock, .1*(context.account.settled_cash / n))                 
                  

def clean_out(context, data):

    for stock in context.security_set:
        order_target_percent(stock, 0.0)                 
 

                    
            
        
        
        
        
def filter_universe():

    common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()
    have_data = morningstar.valuation.market_cap.latest.notnull()
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~morningstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet &
                       have_data & not_otc & not_wi & not_depository & primary_share)
    
    high_volume_tradable = (AverageDollarVolume(window_length=5,
    mask=tradable_filter).percentile_between(50, 100))    
    
    USEP = builtin.USEquityPricing
    
    above_5 = (SimpleMovingAverage(inputs=[USEP.close], window_length=3,                                  mask=high_volume_tradable).percentile_between(10,37))   
    
    screen = above_5

    return screen
                    
           
        
There was a runtime error.

Trading 90% of Free Cash & Start Day1

Clone Algorithm
21
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor, AverageDollarVolume
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import morningstar, builtin
from quantopian.pipeline.filters.morningstar import IsPrimaryShare
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage
import numpy as np
import pandas as pd


class UniverseFilter(CustomFactor):  

    window_length = 1  
    inputs = [morningstar.share_class_reference.is_primary_share,  
              morningstar.share_class_reference.is_depositary_receipt,  
              morningstar.asset_classification.morningstar_sector_code]  
    def compute(self, today, assets, out, is_primary_share, is_depositary_receipt, sector_code):  
        def accept_symbol(equity):  
            symbol = equity.symbol  
            if symbol.endswith("_PR") or symbol.endswith("_WI") or symbol.endswith("_WD") or                                             symbol.endswith("_VJ") or symbol.endswith("_H") or symbol.endswith("_V") or symbol.endswith("_A"):  
                return False  
            else:  
                return True  
 
        vsid = np.vectorize(sid)  
        equities = vsid(assets)   
        vaccept_symbol = np.vectorize(accept_symbol)  
        accept_symbol = vaccept_symbol(equities)  
        criteria = accept_symbol
        criteria = criteria
        out[:] = criteria.astype(float)  
        
 

class MessageVolume(CustomFactor):
                    
    inputs = [stocktwits.bearish_intensity]
    window_length = 25
    def compute(self, today, assets, out, msgs):
        out[:] = -np.nansum(msgs, axis=0)
        
   

                    
    
    
    
def make_pipeline():

    bullish = MessageVolume()
    universefilter = UniverseFilter() 
    initial_screen = filter_universe()
    combined_rank = (bullish.rank(mask=initial_screen) + universefilter.rank(mask=initial_screen))
    
    N = 3
    
    longs = combined_rank.top(N) 
    pipe_screen = (longs)

    pipe_columns = {'longs':longs,
        'combined_rank':combined_rank,
        'bullish':bullish,
        'universefilter':universefilter}
    
    pipe = Pipeline(columns = pipe_columns, screen = pipe_screen)
    return pipe



                    
    
    
    
def initialize(context):
    
    set_long_only()   
    set_commission(commission.PerShare(cost=0.00, min_trade_cost=0.0))
     
    attach_pipeline(make_pipeline(), 'ranking_example')

    context.dont_buys = security_lists.leveraged_etf_list
    
    

    schedule_function(func=first_day,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(minutes=30),
                      half_days=True)
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.week_start(),
                      time_rule=time_rules.market_open(minutes=100),
                      half_days=True)
    
    schedule_function(func=clean_out,
                      date_rule=date_rules.week_end(),
                      time_rule=time_rules.market_open(minutes=90))


    
                       
        
        
        
        
def before_trading_start(context, data):

    output = pipeline_output('ranking_example')
    ranks = output['combined_rank']
    long_ranks = ranks[output['longs']]
    context.long_weights = (long_ranks / long_ranks.sum())
    return len(long_ranks)
  

                    
    
    
    
#def handle_data(context, data):

    #record(leverage=context.account.leverage)
    #pass     
                    
   

    
    
    
    
def rebalance(context, data):
    
    n = 3
    context.security_set = set(context.long_weights.index)
    

    for stock in context.security_set:
        order_check=len(get_open_orders(stock)) 
        if ((stock in context.long_weights.index) & (order_check ==0)):
            order_value(stock, .9*(context.account.settled_cash / n))                 
                  

def clean_out(context, data):
    
    try:
        for stock in context.security_set:
            order_target_percent(stock, 0.0)  
    except KeyError:
        pass
  

def first_day(context, data):
    
    try:
        if len(context.security_set) == 0:
            return 1           
    except KeyError:
        n = 3
        context.security_set = set(context.long_weights.index)
    

        for stock in context.security_set:
             order_check=len(get_open_orders(stock)) 
             if ((stock in context.long_weights.index) & (order_check ==0)):
                 order_value(stock, .9*(context.account.settled_cash / n))

                    
            
        
        
        
        
def filter_universe():

    common_stock = morningstar.share_class_reference.security_type.latest.eq('ST00000001')
    not_lp_name = ~morningstar.company_reference.standard_name.latest.matches('.* L[\\. ]?P\.?$')
    not_lp_balance_sheet = morningstar.balance_sheet.limited_partnership.latest.isnull()
    have_data = morningstar.valuation.market_cap.latest.notnull()
    not_otc = ~morningstar.share_class_reference.exchange_id.latest.startswith('OTC')
    not_wi = ~morningstar.share_class_reference.symbol.latest.endswith('.WI')
    not_depository = ~morningstar.share_class_reference.is_depositary_receipt.latest
    primary_share = IsPrimaryShare()
    tradable_filter = (common_stock & not_lp_name & not_lp_balance_sheet &
                       have_data & not_otc & not_wi & not_depository & primary_share)
    
    high_volume_tradable = (AverageDollarVolume(window_length=5,
    mask=tradable_filter).percentile_between(50, 100))    
    
    USEP = builtin.USEquityPricing
    
    above_5 = (SimpleMovingAverage(inputs=[USEP.close], window_length=3,                                  mask=high_volume_tradable).percentile_between(10,37))   
    
    screen = above_5

    return screen
                    
           
        
There was a runtime error.

50% free cash and etfs:

Clone Algorithm
21
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.data import builtin
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.filters import StaticAssets
from quantopian.pipeline.factors import SimpleMovingAverage
import numpy as np
import pandas as pd


class MessageVolume(CustomFactor):
                    
    inputs = [stocktwits.bull_minus_bear]
    window_length = 25
    def compute(self, today, assets, out, bull_minus_bear):
        out[:] = -np.nansum(bull_minus_bear, axis=0)
        
        
def make_pipeline():

    bullish = MessageVolume()
    initial_screen = filter_universe()
    combined_rank = (bullish.rank(mask=initial_screen)) 
    N = 5
    longs = combined_rank.bottom(N) 
    allstocks = combined_rank.bottom(129)
    pipe_screen = (allstocks) #longs
    pipe_columns = {'longs':longs,
                    'combined_rank':combined_rank,
                    'bullish':bullish}  
    pipe = Pipeline(columns = pipe_columns, screen = pipe_screen)
    return pipe
    
    
def initialize(context):
    
    set_long_only()   
    set_commission(commission.PerShare(cost=0.00, min_trade_cost=0.0))   
    context.tlo = sid(33946)
    context.spy = sid(8554)
    attach_pipeline(make_pipeline(), 'ranking_example')
    context.dont_buys = security_lists.leveraged_etf_list
    
    schedule_function(func=first_day,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(minutes=30),
                      half_days=True)
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(minutes=90),
                      half_days=True)
    
    schedule_function(func=clean_out,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open())
    
    schedule_function(func=daily_clean,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(minutes=30))
    
    
       
def before_trading_start(context, data):

    output = pipeline_output('ranking_example')  
    ranks = output['combined_rank']
    long_ranks = ranks[output['longs']]
    context.long_weights = (long_ranks / long_ranks.sum())
    context.ranks = ranks
    return len(long_ranks)
     
    
def rebalance(context, data):
    
    n = 5
    context.security_set = set(context.long_weights.index)  
    spy_200=data.history(context.spy, "price", 200, "1d")  
    spy_mavg=spy_200.mean()  
    spy_price=data.current(context.spy, "price")  
    
    if data.can_trade(context.tlo) and spy_price<spy_mavg:  
        order_value(context.tlo, .5*(context.account.settled_cash))
        return 
    
    for stock in context.security_set:
        order_check=len(get_open_orders(stock))
        if ((stock in context.long_weights.index) & (order_check ==0) & (data.can_trade(stock))):
            order_value(stock, .5*(context.account.settled_cash / n))                 
                  

def clean_out(context, data):
     
    try:
        for stock in context.security_set:
            if ((data.can_trade(stock))):
                order_target_percent(stock, 0.0)
        order_target_percent(context.tlo, 0.0)
    except KeyError:
        pass
    

def first_day(context, data): 
    
    try:
        if len(context.security_set) == 0:
            return 1
    except KeyError:
        n = 5
        context.security_set = set(context.long_weights.index)      
        spy_200=data.history(context.spy, "price", 200, "1d")  
        spy_mavg=spy_200.mean()  
        spy_price=data.current(context.spy, "price")  

        if data.can_trade(context.tlo) and spy_price<spy_mavg:   
            order_value(context.tlo, .5*(context.account.settled_cash))  
            return 

        for stock in context.security_set:
             order_check=len(get_open_orders(stock)) 
             if ((stock in context.long_weights.index) & (order_check ==0) & (data.can_trade(stock))):
                 order_value(stock, .5*(context.account.settled_cash / n))
                    
                    
def daily_clean(context, data):
    
    context.rank_set = set(context.ranks.index) 
    try:
        for stock in context.rank_set:
            if ((stock not in context.security_set) & (data.can_trade(stock))):
                order_target_percent(stock, 0.0)
    except KeyError:
        pass
           

def filter_universe():
   
    ETFs = StaticAssets(symbols('XLU','XLF','XLP','XLY','XLE','XLV','XLI','XLK','XLB','IBB','USO','URA','GDX','LIT','VNQ','SMH','VOO','VTI','TLT','IWM','VEA','GDXJ','VHT','VIG','SVXY','HACK','KOL','RSX','VGK','UVXY','JETS','VWO','ASHR','VGT','AMLP','BND','SIL','VB','VDE','VNM','MOO','VUG','INDA','GREK','IPO','ROBO','VFH','KWEB','SBIO','VYM','SOCL','SCHB','IBUY','VTV','SDIV','YYY','SLX','HDGE','SCHD','GOEX','VO','VBR','SCHF','FTEC','VIXY','JNK','SILJ','CNCR','COPX','ARGT','DIV','IBLN','VBK','RTH','SLVP','VDC','VOE','VCR','BBP','SCHA','VPU','XAR','VAW','SCHE','VT','SPYG','VEU','CNCR','COPX','ARGT','DIV','VBK','IBLN','RTH','SLVP','VDC','VOE','VCR','BBP','SCHA','VPU','XAR','VAW','SCHE','VT','SPYG','VEU','VOX','ORG','NGE','SGDM','BJK','BIV','PEK','VXUS','EDV','GVAL','ALFA','VOOG','VIXM','PPH','HYLD','BSV','FHLC','VIS','VNQI','KWT'))                             
    tradable_filter = (ETFs)
    USEP = builtin.USEquityPricing
    above_5 = (SimpleMovingAverage(inputs=[USEP.close], window_length=3,                                  mask=tradable_filter).percentile_between(5,80))   
    screen = above_5
    return tradable_filter             
           
        
There was a runtime error.