Back to Community
PLEASE HELP MY - LIMIT PIPELINE RESULTS

please, can anyone tell me how to limit my results from my pipeline to 200 each? any help is appreciated, below is my code for the program on which i want to impose a limit

Clone Algorithm
3
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
"""
Trading Strategy using Fundamental Data
1. Look at stocks in the QTradableStocksUS.
2. Go long in the top 50 stocks by pe_ratio.
3. Go short in the bottom 50 stocks by pe_ratio.
4. Rebalance once a month at market open.
"""

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data import Fundamentals
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.factors import BusinessDaysSincePreviousEvent


def initialize(context):
    # Rebalance monthly on the first day of the month at market open
    schedule_function(rebalance,
                      date_rule=date_rules.month_start(days_offset=1),
                      time_rule=time_rules.market_open())

    attach_pipeline(make_pipeline(), 'fundamentals_pipeline')

def make_pipeline():

    growth_grade = Fundamentals.growth_grade.latest
    
   
    universe = QTradableStocksUS()
    Aplus_grade = growth_grade.startswith('A')
    Anormal_grade = growth_grade.startswith('A')
    F_grade = growth_grade.startswith('F')
   

    graded  = (F_grade | Aplus_grade | Anormal_grade )
    A_grade = (Anormal_grade | Aplus_grade)
    tradable = universe & graded
    
    pipe = Pipeline(
              columns={
                'Growth Grade': growth_grade,
                'long': A_grade,
                'short': F_grade 
              }, screen= tradable
          )

    return pipe

    
"""
Runs our fundamentals pipeline before the marke opens every day.
"""
def before_trading_start(context, data): 

    context.pipe_output = pipeline_output('fundamentals_pipeline')

    # The high p/e stocks that we want to long.
    context.longs = context.pipe_output[context.pipe_output['long']].index

    # The low p/e stocks that we want to short.
    context.shorts = context.pipe_output[context.pipe_output['short']].index
    
    record(leverage = context.account.leverage)
    
    longs = shorts = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount > 0:
            longs += 1
        if position.amount < 0:
            shorts += 1
    record(long_count=longs, short_count=shorts)

    
    

def rebalance(context, data):
    
    my_positions = context.portfolio.positions
    
    # If we have at least one long and at least one short from our pipeline. Note that
    # we should only expect to have 0 of both if we start our first backtest mid-month
    # since our pipeline is scheduled to run at the start of the month.
    if (len(context.longs) > 0) and (len(context.shorts) > 0):

        # Equally weight all of our long positions and all of our short positions.
        long_weight = .75/len(context.longs)
        short_weight = -.25/len(context.shorts)
        
        # Get our target names for our long and short baskets. We can display these
        # later.
        target_long_symbols = [s.symbol for s in context.longs]
        target_short_symbols = [s.symbol for s in context.shorts]

        log.info("Opening long positions each worth %.2f of our portfolio in: %s" \
                 % (long_weight, ','.join(target_long_symbols)))
        
        log.info("Opening long positions each worth %.2f of our portfolio in: %s" \
                 % (short_weight, ','.join(target_short_symbols)))
        
        # Open long positions in our high p/e stocks.
        for security in context.longs:
            if data.can_trade(security):
                if security not in my_positions:
                    order_target_percent(security, long_weight)
            else:
                log.info("Didn't open long position in %s" % security)

        # Open short positions in our low p/e stocks.
        for security in context.shorts:
            if data.can_trade(security):
                if security not in my_positions:
                    order_target_percent(security, short_weight)
            else:
                log.info("Didn't open short position in %s" % security)
                  

    closed_positions = []
    
    # Close our previous positions that are no longer in our pipeline.
    for security in my_positions:
        if security not in context.longs and security not in context.shorts \
        and data.can_trade(security):
            order_target_percent(security, 0)
            closed_positions.append(security)
    
    log.info("Closing our positions in %s." % ','.join([s.symbol for s in closed_positions]))
There was a runtime error.
1 response

Hi Nathan,

I've attached a version of your algorithm where pipe_output only keeps 100 "long" stocks and 100 "short" stocks. However, the version I wrote simply keeps the first 100 (by name) of each type; you'll probably want to find a less arbitrary way to decide which 200 stocks to trade!

Note: I wrote it this way because the growth_grade field is categorical, so there are >100 A-rated stocks and >100 F- rated stocks, with no way to decide which stocks in the same category are "better" than others. In a case where your data is continuous instead of categorical, you might want to check out the .top() filter to limit your pipeline to a certain number of stocks -- take a look at the usage of .top() in the Creating Custom Factors and Fundamental Data Algorithm examples here. Hope this helps!

Clone Algorithm
0
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
"""
Trading Strategy using Fundamental Data
1. Look at stocks in the QTradableStocksUS.
2. Go long in the top 50 stocks by pe_ratio.
3. Go short in the bottom 50 stocks by pe_ratio.
4. Rebalance once a month at market open.
"""

from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data import Fundamentals
from quantopian.pipeline.filters import QTradableStocksUS
from quantopian.pipeline.factors import BusinessDaysSincePreviousEvent


import pandas as pd


def initialize(context):
    # Rebalance monthly on the first day of the month at market open
    schedule_function(rebalance,
                      date_rule=date_rules.month_start(days_offset=1),
                      time_rule=time_rules.market_open())

    attach_pipeline(make_pipeline(), 'fundamentals_pipeline')

def make_pipeline():

    growth_grade = Fundamentals.growth_grade.latest
    
   
    universe = QTradableStocksUS()
    Aplus_grade = growth_grade.startswith('A')
    Anormal_grade = growth_grade.startswith('A') # This seems to be the same thing as Aplus_grade?
    F_grade = growth_grade.startswith('F')
   

    graded  = (F_grade | Aplus_grade | Anormal_grade )
    A_grade = (Anormal_grade | Aplus_grade)
    tradable = universe & graded
    
    pipe = Pipeline(
              columns={
                'Growth Grade': growth_grade,
                'long': A_grade,
                'short': F_grade 
              }, screen= tradable
          )

    return pipe

    
"""
Runs our fundamentals pipeline before the marke opens every day.
"""
def before_trading_start(context, data): 

    context.raw_pipe_output = pipeline_output('fundamentals_pipeline')
    context.long_pipe_output = context.raw_pipe_output[context.raw_pipe_output['long']].head(100)
    context.short_pipe_output = context.raw_pipe_output[context.raw_pipe_output['short']].head(100)
    context.pipe_output = context.long_pipe_output.append(context.short_pipe_output)
    
    print context.pipe_output

    # The high p/e stocks that we want to long.
    context.longs = context.pipe_output[context.pipe_output['long']].index

    # The low p/e stocks that we want to short.
    context.shorts = context.pipe_output[context.pipe_output['short']].index
    
    record(leverage = context.account.leverage)
    
    longs = shorts = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount > 0:
            longs += 1
        if position.amount < 0:
            shorts += 1
    record(long_count=longs, short_count=shorts)

    
    

def rebalance(context, data):
    
    my_positions = context.portfolio.positions
    
    # If we have at least one long and at least one short from our pipeline. Note that
    # we should only expect to have 0 of both if we start our first backtest mid-month
    # since our pipeline is scheduled to run at the start of the month.
    if (len(context.longs) > 0) and (len(context.shorts) > 0):

        # Equally weight all of our long positions and all of our short positions.
        long_weight = .75/len(context.longs)
        short_weight = -.25/len(context.shorts)
        
        # Get our target names for our long and short baskets. We can display these
        # later.
        target_long_symbols = [s.symbol for s in context.longs]
        target_short_symbols = [s.symbol for s in context.shorts]

        log.info("Opening long positions each worth %.2f of our portfolio in: %s" \
                 % (long_weight, ','.join(target_long_symbols)))
        
        log.info("Opening long positions each worth %.2f of our portfolio in: %s" \
                 % (short_weight, ','.join(target_short_symbols)))
        
        # Open long positions in our high p/e stocks.
        for security in context.longs:
            if data.can_trade(security):
                if security not in my_positions:
                    order_target_percent(security, long_weight)
            else:
                log.info("Didn't open long position in %s" % security)

        # Open short positions in our low p/e stocks.
        for security in context.shorts:
            if data.can_trade(security):
                if security not in my_positions:
                    order_target_percent(security, short_weight)
            else:
                log.info("Didn't open short position in %s" % security)
                  

    closed_positions = []
    
    # Close our previous positions that are no longer in our pipeline.
    for security in my_positions:
        if security not in context.longs and security not in context.shorts \
        and data.can_trade(security):
            order_target_percent(security, 0)
            closed_positions.append(security)
    
    log.info("Closing our positions in %s." % ','.join([s.symbol for s in closed_positions]))
There was a runtime error.
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.