Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trying to obtain the amount of stocks owned for a list of securities without a for loop

context.securit_list = pd.DataFrame indexed by [sid(4922), sid(679), sid(24)...]

Why can't I perform the statement below ? and is there a way of obtaining the amount of stocks held for every security owned without using a for loop ?

log.info(context.portfolio.positions[context.security_list.index.tolist()]amount)

2 responses

Something like this should work

import pandas as pd

# Get a list of the position objects  
positions = context.portfolio.positions

# Make a pandas series out of the list  
positions_series = pd.Series(positions)

# With a series (rather than a list) one can use the map method  
position_amounts = positions_series.map(lambda stock: stock.amount)

# Above gives a pandas series of amounts indexed so log.info will print the amounts of each stock  
log.info(position_amounts)  

This can be done in a couple of lines

position_amounts = pd.Series(context.portfolio.positions).map(lambda stock: stock.amount)  
log.info(position_amounts)

Or even one line

log.info(pd.Series(context.portfolio.positions).map(lambda stock: stock.amount))

I'm partial to the two line version since it seems more 'self documenting'. The first version highlights the individual steps.

There's probably other ways but this works (and doesn't use for loops).

A few reasons why what you suggested won't work

log.info(context.portfolio.positions[context.security_list.index.tolist()]amount)

'context.portfolio.positions' is a python dict object. It doesn't understand being passed a list of keys. Also even if it did (ie was able to create a subset of the dictionary based upon a list of keys) then it wouldn't understand what you meant by 'amount' or '.amount'. It would expect that was a method or property of the dictionary. However. 'amount' is really a property of the objects stored in the dictionary. It would need some way to know it should apply 'amount' to each value. In a way, that is exactly what map does. Applies a function to each value.

I have integrated it into my algorithm. It was exactly what I was looking for.

Thanks Dan!