Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Fundamentals: Updating Universe

Hi Quantopian,

I have a dictionary of stocks and corresponding values that goes as follows stored in context.stock_values:

{'BA': 24, 'AAPL': 11, 'NAV': -2, 'AGU': 7, 'XLNX': 0, 'WY': 8, 'TAP': -4}

This dictionary is derived from interpreting fundamentals data. Unfortunately I cannot pull price data on all of these values because (from what I can tell) some of these stocks are not in my stock universe. Is there some way that I can update the universe with a dictionary like this or with the individual stock tickers?

Please let me know if this doesn't make sense.

Thanks!

4 responses

The update_universe() method is probably what you're looking for: https://www.quantopian.com/help/#api-update-universe

Note, you need to pass update_universe() a list of sids, not tickers. See the fundamentals algo example for a template: https://www.quantopian.com/help/#sample-fundamentals

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.

If you pass their ticker symbols as string constants to symbol or symbols, they will be placed in your initial universe. Typically, you would write in initialize:

    context.stocks=symbols('BA', 'AAPL', 'NAV', 'AGU', 'XLNX', 'WY', 'TAP')  

The assignment is not required, but useful. There is no way to find out later what your universe is if you don't save this information yourself. See https://www.quantopian.com/posts/search?q=get_universe .

You should include them in any subsequent calls to update_universe, otherwise they will be removed.

I appreciate the help guys, unfortunately I am still running into issues. I decided to use the fundamentals.valuation.sid in my query of fundamentals data, then feed that list of SID's into the update_universe method. Now, when I try to query the price of a stock in that list I have created, I get hit with this error:

TypeError: 'zipline.assets._assets.Equity' object has no attribute '__getitem__'
USER ALGORITHM:72, in handle_data
log.info(stock[data].price)

Here is a sample of my code. Thanks for all the help in advance!

import pandas as pd  
import numpy as np

def initialize(context):  
    # Dictionary of stocks  
    context.stocks = []  
    context.fun_stocks = []  
    # Count of days before rebalancing  
    context.days = 0  
    set_benchmark(sid(8554))  
    # Sector mappings  
    context.sector_mappings = {  
       101.0: "Basic Materials",  
       102.0: "Consumer Cyclical",  
       103.0: "Financial Services",  
       104.0: "Real Estate",  
       205.0: "Consumer Defensive",  
       206.0: "Healthcare",  
       207.0: "Utilites",  
       308.0: "Communication Services",  
       309.0: "Energy",  
       310.0: "Industrials",  
       311.0: "Technology"  
    }  
    context.sectors = context.sector_mappings.keys()

def before_trading_start(context, data):  
    num_stocks = 100  
    fundamental_df = get_fundamentals(  
        query(  
            fundamentals.valuation.sid, #get stock ID  
            fundamentals.company_reference.primary_symbol,  
            fundamentals.valuation_ratios.pe_ratio,     # Price to Earnings ratio  
            fundamentals.asset_classification.morningstar_sector_code  
        )  
        .filter(fundamentals.valuation_ratios.pe_ratio != None)  
        .filter(fundamentals.asset_classification.morningstar_sector_code != None)  
        .filter(fundamentals.asset_classification.morningstar_sector_code != 309.0)    # filter out utilities  
        .filter(fundamentals.asset_classification.morningstar_sector_code != 103.0)    # filter out finance  
        .filter(fundamentals.asset_classification.morningstar_sector_code != 206.0)    # filter out healthcare  
        .filter(fundamentals.valuation.market_cap >= 50000000)  
        .filter(fundamentals.valuation.shares_outstanding != None)

        .order_by(fundamentals.valuation.market_cap.desc())  
        .limit(num_stocks)  
    )  
    sectors = [101.0, 102.0, 104.0, 205.0, 207.0, 308.0, 310.0, 311.0]  
    context.fun_stocks = [stock for stock in fundamental_df if fundamental_df[stock]['morningstar_sector_code'] in sectors]  
    for stock in context.fun_stocks:  
        stock = fundamental_df[stock]['sid']  
        context.stocks.append(stock) #iterate through list of SIDs and append them to context.stocks  
    update_universe(context.stocks)

def handle_data(context, data):  
    for stock in context.stocks:  #loop through context.stocks and log their price  
        log.info(stock[data].price)

The last line should have data[stock].price. But that is only a number, indistinguishable from others. You'd better write something like

        log.info("{}: {} ${}".format(get_datetime('US/Eastern').time(), stock.symbol, data[stock].price))