Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Set top N large cap universe (e.g. S&P 500)

I wanted to restrict my universe to a certain index such as S&P 500.

I thought "Dollar-Volume Universe" is not what I was looking for, so I modified one of example codes in the Help page. I was wondering if my code is correct.
If historical S&P 500 component list at a certain point in the past can be easily found, I can verify whether this code is working well or not. However, I found it is pretty hard to find such component data.. so I have no way of checking the output is correct or not at this point.

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):

    pipe = Pipeline()  
    attach_pipeline(pipe, 'example')

    # Construct the custom factor  
    mkt_cap = MarketCap()

    pipe.add(mkt_cap, 'mkt_cap')  
    pipe.add(mkt_cap.rank(ascending=False), 'mkt_cap_rank')

    # Use screen to narrow the universe  
    pipe.set_screen(mkt_cap.top(100))

def before_trading_start(context, data):  
    context.output = pipeline_output('example')

    context.large_cap = context.output.sort(['mkt_cap'], ascending=False)#.iloc[:10]

    update_universe(context.large_cap.index)

def handle_data(context, data):

    log.info("\n" + str(context.large_cap.head()))  
    log.info("\n" + str(context.large_cap.tail()))  
1 response

James,
This pipeline is giving you the top 100 stocks by market cap. The selection criteria for the S&P 500 are a bit more complex, and at the end, the decision to add or remove a company from the S&P500 is made by a committee. This makes it difficult to write code to replicate the S&P500.

The Russell 1000 and 3000 are rules based, and this algorithm here tries to replicate the Russell 3000, but as Simon pointed out, there are still challenges.

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.