Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to use multiple filters with pipe.set_screen ?

Hello everyone.

I want to create a universe where I can buy stocks with simple moving average SMA50 >SMA100 >SMA200, and short stocks with

simple moving average SMA50<SMA100 <SMA200, but I'm stuck with this error: IndexError: index 0 is out of bounds for axis 0 with size 0

Any help would be appreciated.

Thank you in advance.

5 responses
import pandas  
import numpy as np  
import talib

from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline import CustomFactor  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.data import morningstar  
from quantopian.pipeline.factors import SimpleMovingAverage

class AvgDailyDollarVolume(CustomFactor):  
    inputs = [USEquityPricing.close, USEquityPricing.volume]  
    window_length = 30  
    def compute(self, today, assets, out, close_price, volume):  
        dollar_volume = close_price * volume  
        avg_dollar_volume = np.mean(dollar_volume, axis=0)  
        out[:] = avg_dollar_volume  
#class Income_statement(CustomFactor):  
    # Pre-declare inputs and window_length  
    #inputs = [morningstar.income_statement]  
    #window_length = 1  
    # Compute market cap value  
    #def compute(self, today, assets, out, income):  
        #out[:] = income  
class MarketCap(CustomFactor):  
    # Pre-declare inputs and window_length  
    inputs = [USEquityPricing.close, morningstar.valuation.shares_outstanding]  
    window_length = 1  
    # Compute market cap value  
    def compute(self, today, assets, out, close, shares):  
        out[:] = close[-1] * shares[-1]  
def initialize(context):  
    #context.size = float(context.portfolio.cash / 20)  & (sma_long ) & (sma_short)  
    context.shorting = True  
    context.shorts = []  
    context.max_positions = 26  
    pipe = Pipeline()  
    attach_pipeline(pipe, 'mypipe')  
    sma_200 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=200)  
    sma_100 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=100)  
    sma_50 = SimpleMovingAverage(inputs=[USEquityPricing.close], window_length=50)  
    sma_long =  ( (sma_100 > sma_200) & (sma_50 > sma_100))  
    sma_short = ( (sma_100 < sma_200) & (sma_50 < sma_100))  
    #pipe.add(sma_200, 'sma_200')  
    #pipe.add(sma_115, 'sma_115')    # and sma_long and sma_short  & (sma_long) & (sma_short )  
    #pipe.add(sma_35, 'sma_35')       # (sma_35 > sma_115) &  &  (sma_35 < sma_115))  
    pipe.add(sma_short, 'sma_short')  
    pipe.add(sma_long, 'sma_long')  
    mkt_cap = MarketCap()  
    pipe.add(mkt_cap, 'mkt_cap')  
    #income = Income_statement()  
    #pipe.add(income, 'income')  
    dollar_volume = AvgDailyDollarVolume()  
    pipe.add(dollar_volume, 'dollar_volume')  
    dv_filter = (dollar_volume > 10*10**6) & (dollar_volume < 30 * 10**6)  
    mkt_cap_fltr= (mkt_cap > 10*10**8) & (mkt_cap < 20*10**8)  
    pipe.set_screen (sma_long & sma_short & dv_filter & mkt_cap_fltr)  

    schedule_function(logic,date_rules.every_day(),time_rules.market_close())  
    #schedule_function(logic,date_rules.every_day(),time_rules.market_close(minutes=380))

def before_trading_start(context, data):

    context.output = pipeline_output('mypipe')  
    #log.info(len(context.output))  
    context.sma_long = context.output.sort(['sma_long'], ascending=True).iloc[:100]  
    log.info(len(context.sma_long))  
    log.info("\n" + str(context.sma_long.head(10)))  
    context.sma_short = context.output.sort(['sma_short'], ascending=True).iloc[:100]  
    log.info(len(context.sma_short))  
    log.info("\n" + str(context.sma_short.head(10)))  

    update_universe(context.sma_long.index.union(context.sma_short.index))  

def logic(context, data):  
    pass  
def handle_data(context, data):  
    pass  

That error typically means that your pipeline is empty on the first day of trading - you've written a set of criteria that nothing made it through. I started visualizing your pipeline, but I ran out of time - hopefully it's useful to you.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thank you Dan for your reply.

If I use only 1 filter in pipe.set_screen, "**sma_long**" or "**sma_short**" it works fine. The problem is when I use both of them.

I'm new to coding so just bear with me.

Thanks!

There is a problem in your logic. I'll put the problematic bits together:

sma_long =  ( (sma_100 > sma_200) & (sma_50 > sma_100))  
sma_short = ( (sma_100 < sma_200) & (sma_50 < sma_100))  
pipe.set_screen (sma_long & sma_short)  

If you substitute sma_long and sma_short in the screen,

pipe.set_screen((sma_100 > sma_200) & (sma_50 > sma_100) & (sma_100 < sma_200) & (sma_50 < sma_100))  

Nothing will ever satisfy this screen.

Sunil

Thank you Sunil.

I want to create a universe where I can buy stocks with simple moving average SMA50 >SMA100 >SMA200, and short stocks with

simple moving average SMA50<SMA100 <SMA200. Is there a way to do this using the Pipeline API ?

Thanks.