Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Confusion between data/context [New to Quantopian]

Hello, I am relatively new here to Quantopian and have a pretty basic question. I'm trying to setup a ranking system by getting fundamental data on 10 stocks with highest market cap [context.fundamentals_High] and 10 stocks with the lowest market cap [context.fundamentals_low]

However, when the handle_data(context,data) method is called, it appears that data only has the stocks from context.fundamentals_High, and not the stocks from context.fundamentals_Low. What is the best way to go about updating the universe with both sets of stocks? For example if I wanted to go long on the stocks with high market cap and short the stocks with low market cap, how can I distinguish between the two sets inside the data parameter?

Thanks for any help!
(P.S. Quantopian is amazing!)

# Put any initialization logic here.  The context object will be passed to  
# the other methods in your algorithm.  
import datetime  
def initialize(context):

    pass  
    context.limit = 10

def before_trading_start(context):  
    context.today = datetime.datetime.now().strftime('%Y-%m-%d')  
    context.fundamentals_Low = get_fundamentals(  
        query(  
            # put your query in here by typing "fundamentals."  
            fundamentals.valuation.market_cap,  
            fundamentals.operation_ratios.roe,  
            fundamentals.cash_flow_statement.free_cash_flow)  
        .filter(fundamentals.cash_flow_statement.free_cash_flow > 0)  
        .order_by(fundamentals.valuation.market_cap.asc())  
        .limit(context.limit),  
        context.today)

    context.fundamentals_High = get_fundamentals(  
        query(  
            # put your query in here by typing "fundamentals."  
            fundamentals.valuation.market_cap,  
            fundamentals.operation_ratios.roe,  
            fundamentals.cash_flow_statement.free_cash_flow)  
        .filter(fundamentals.cash_flow_statement.free_cash_flow > 0)  
        .order_by(fundamentals.valuation.market_cap.desc())  
        .limit(context.limit),  
        context.today)  
    update_universe(context.fundamentals_Low.columns.values)  
    update_universe(context.fundamentals_High.columns.values)

# Will be called on every trade event for the securities you specify.  
def handle_data(context, data):

    for stock in data:  
        print "stock is:", context.fundamentals_Low[stock]  
        print "new STOCK:"
2 responses

Justin,

You should be able to use context.fundamentals_Low.columns.values & context.fundamentals_High.columns.values which will persist in context and are accessible from handle_data().

Grant

Have a look at the link below in the def before_trading_start, this might give you some other ideas.
https://www.quantopian.com/posts/long-short-sector-neutral-strategy-based-on-fundamentals