Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Tracking positions within single handle_data call

In my handle_data call, I loop through all the stocks in context.stocks, executing the trade logic on each. As a result, multiple positions can be opened during a single handle_data call. This leads to a static (and inaccurate) count of my positions. I know context.portfolio.positions isn't updated until the next bar, so I've also tried the following (with no success):

len(get_open_orders())+len(context.portfolio.positions)  

Is there a way to track the number of positions as it changes within a single handle_data call? Any help would be much appreciated!

3 responses

Hello Param,

I took a quick stab at this, but didn't make it to an answer. Here's some code that can be built upon to work on a solution.

It seems that there are a number of things at play here. You want to know the number of securities in which you currently hold positions. But then you also want to project, after handle_data has executed, how many positions will be held. So, you need to look at all open orders and assuming that they go through, what will be the net result. Is this correct?

I'm guessing that you want to set a cap/target on the number of positions held at any given time, correct?

Grant

Thanks Grant - I think this is a first step in the right direction. I actually already successfully use this code to limit my total positions:

len(get_open_orders())+len(context.portfolio.positions)  

What I am actually hoping to do is scale my position sizes (target percent of portfolio) using this function: .25^((total_positions/10)+1). So, the first position would be 25%, the second 21.9%, the third 18.9% and so on. The goal is to allocate a larger percent of the portfolio during periods where I am holding few stocks. Right now, the function allocates the same percentage to each position within a single handle_data call, because total_positions is not getting updated.

Hi Param,

I'm not sure that I follow. The order_target_percent method will do the reallocation for you. And if you always want to be 100% in the market, just normalize the allocation vector to 1 (or a lesser value to keep some reserve cash). Assuming you don't have any open orders, everything should work out, right?

Grant