Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to manage a list of many securities

Hello everyone,
I'm getting my head around quantopian and I had an efficiency question. I've seen beginner code that creates an object for each security using context.a = sid(100000) or context.a = symbol(a). However, this gets very tedious when trying to work with a large number of securities. How would I go about having a list of say, 100 predetermined securities then call those later on?
I originally tried making something like this:

context.security_list = []  
    symbolslist = ['abt', 'adbe', 'tmo','biib']  
    for mysymbol in symbolslist:  
        context.security_list.append(symbol(mysymbol))

...
order(context.security_list[1],  .9)  

This did not pan out, however. haha
Thanks for your advice.

1 response

The symbols method (https://www.quantopian.com/help#api-symbols) can take more than one security ticker and return a list of associated security objects. Something like this:

my_security_list = symbols(['TRU', 'GKOS', 'ALRM', 'BLD',  'CC', 'ENR', 'TDOC',])

Note the brackets around the ticker symbols. Those are required.

I actually like storing everything in a pandas dataframe so take that list and create a dataframe from it. Then maybe add some data to associate to each security (eg 'weight')

import pandas as pd  
my_weights = [.1, .1, .2, .1, .1, .1, .1, .1, .1]  
my_securities_df = pd.DataFrame(index=my_security_list, data=my_weights, columns=['weight'])

To place orders for each security simply loop over the dataframe index

for stock in my_securities_df.index:  
    weight = my_securities_df.at[stock, 'weight']  
    order_target_percent(stock, weight)

Or, better yet, use the order_optimal_portfolio method to order all at once (no loops).

    algo.order_optimal_portfolio(objective=opt.TargetWeights(my_securities_df.weight), constraints=[])

See attached notebook. Hope that helps.