Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Working with the S&P500 as my universe

Hey guys,

I'm trying to set my universe as the S&P500. What's the best way to do this? Currently I'm doing something like this:

def before_trading_start(context, data):  
    today = get_datetime().date()  

    sp_500 = get_fundamentals(  
                        query(fundamentals.valuation.market_cap,  
                             fundamentals.company_reference.primary_exchange_id)  
                        .filter(fundamentals.valuation.market_cap > 4e9)  
                        .filter(fundamentals.company_reference.country_id == "USA")  
                        .filter(or_(fundamentals.company_reference.primary_exchange_id == "NAS",  
                                    fundamentals.company_reference.primary_exchange_id == "NYS"))  
                        .order_by(fundamentals.valuation.market_cap.desc())  
                        .limit(500),  
                        today)  
    sids = sp_500.columns.values  
    context.stocks = [s.sid for s in sids]  

However this only returns about 100 something stocks (varies with each day / month). To my understanding, this is because of the fixed value for the market_cap at 4e9. That value changes with the time so I can't have a fixed value. That being said, what's the best way to get the S&P500 stocks over time?

Thanks for the help,
Thomas

2 responses

First off, generally use the pipeline approach to get data and not the 'get_fundamentals' method. Pipeline is faster and better supported with a number of built in methods and filters. If you haven't already, look at the tutorial https://www.quantopian.com/tutorials/pipeline

So, once you go down the path of using a pipeline, then simply use the Q500US filter. That roughly approximates the S&P500. See this post for info on how it works https://www.quantopian.com/posts/the-q500us-and-q1500us

To get started, this post may help to implement the filter (and pipeline) https://www.quantopian.com/posts/how-to-use-q500us

Thanks Dan! I'll check it all out