Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
how to select only the very first one

Hi Fellows,

I am trying to select only one stock from a list with .top() function.

When I choose to put 2, the code below runs smoothly.

            longs = sma_rank.top(2, mask=remove_penny_stocks)

However, when I choose to select 1 stock, the code will have an error.

           longs = sma_rank.top(1, mask=remove_penny_stocks)

Can someone help me on this? Any ideas will be greatly appreciated.

3 responses

Interesting. True. The '.top' method doesn't seem to like a 1 for the N parameter. Maybe Quantopian support could provide some insight.

from quantopian.pipeline  import Pipeline  
from quantopian.algorithm import attach_pipeline, pipeline_output  
import quantopian.pipeline.factors as Factors  
import quantopian.pipeline.filters as Filters

TOP = 2

def initialize(context):  
    schedule_function(print_top_market_cap, date_rules.month_start(), time_rules.market_open(minutes = 65))  
    attach_pipeline(pipeline(context), 'pipeline') 

def pipeline(context):  
    mkt_cap   = Factors.MarketCap(mask = Filters.QTradableStocksUS())  
    my_screen = mkt_cap.top(TOP)  
    pipe      = Pipeline(columns = {'mkt_cap': mkt_cap}, screen = my_screen)  
    return pipe

def print_top_market_cap(context, data):  
    top_market_cap = pipeline_output('pipeline')  
    print top_market_cap  

" if TOP = 1 --> AttributeError: 'Sentinel' object has no attribute 'dependencies' "

How to select the only one?

Here is the documentation from Quantopian for top:

''''''''top(N, mask=sentinel('NotSpecified'), groupby=sentinel('NotSpecified')) Construct a Filter matching the top N asset values of self each day.
If groupby is supplied, returns a Filter matching the top N asset values for each group.
Parameters:
N (int) – Number of assets passing the returned filter each day.
mask (zipline.pipeline.Filter, optional) – A Filter representing assets to consider when computing ranks. If mask is supplied, top values are computed ignoring any asset/date pairs for which mask produces a value of False.
groupby (zipline.pipeline.Classifier, optional) – A classifier defining partitions over which to perform ranking.
Returns:
filter (zipline.pipeline.filters.Filter)
''''''

It does not indicate N cannot be 1.