Back to Community
Add current positions to universe

Hi Everyone,

I want to do a very simple thing. After using the pipeline to get the Stocks of interest. I want to add current stocks in my positions in "before_trading_start" function like this:

update_universe(context.my_universe.index.ravel().tolist() + context.day_start_stocks)

I'm not able to do that. Simply how could I create an Equity object. I tried sid, symbol, symbols. Another thing, is there a way to get a list of stocks from my positions directly without looping on them?


3 responses

Here is a sample code for completeness:

context.output = pipeline_output('example')  
context.my_universe = context.output.sort(['blah_blah'], ascending=False).iloc[:300]  
context.day_start_total_position = context.account.total_positions_value  
context.day_start_stocks = [sid(pos.sid) for pos in context.portfolio.positions]"positions index : " + str(context.day_start_stocks) + "\n")"positions stocks type " + str(type(context.day_start_stocks)) + "\n")"My Universe stocks type " + str(context.my_universe.index.ravel().tolist()) + "\n")"My Universe stocks type " + str(type(context.my_universe.index.ravel().tolist())) + "\n")  
update_universe(context.my_universe.index.ravel().tolist() + context.day_start_stocks)  

I haven't tested the code, but here are a few ideas:

context.day_start_stocks = [sid(pos.sid) for pos in context.portfolio.positions]  
# can probably be changed to  
context.day_start_stocks = context.portfolio.positions.index

update_universe(context.my_universe.index.ravel().tolist() + context.day_start_stocks)  
# should probably be  
update_universe(context.my_universe.index | context.day_start_stocks)  

I just had to do this. context.portfolio.positions.keys() gives the stocks currently in positions, which you can directly use for update_universe.