Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Subsetting Shorts from Positions

Hello! I am trying to subset context.portfolio.positions to only include longs or shorts in the Algorithm IDE. My current code, which doesn't do any subsetting, is

current_holdings = context.portfolio.positions  
long_rule = 'top_quality_momentum & (trend_up or index in @current_holdings)'  
short_rule = 'bottom_quality_momentum & (not trend_up or index in @current_holdings)'  
stocks_to_hold = df.query(long_rule).index  
stocks_to_short = df.query(short_rule).index  

Is it possible to only view short or long positions from context.portfolio.positions?

Thanks!

1 response

I found one solution by checking out the Zipline source code.

current_holdings = context.portfolio.positions  
long_assets = [asset for asset, position in current_holdings.items() if position.amount > 0]  
short_assets = [asset for asset, position in current_holdings.items() if asset not in long_assets]  
long_rule = 'top_quality_momentum & (trend_up or index in @long_assets)'  
short_rule = 'bottom_quality_momentum & (not trend_up or index in @short_assets)'  
stocks_to_hold = df.query(long_rule).index  
stocks_to_short = df.query(short_rule).index