Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Ensuring portfolio is always maintaining 25% in each holding

Alright, so I am running into an issue where my algorithm is holding 4 stocks at any time and based on momentum/fundamental analysis they are rotated in and out. The way the algorithm is setup now when a stock is sold it then re-distributes the "cash" over the 4 stocks again - thus if there is 1 stock that doesn't sell it gets money applied to it and making it go over the 25% balance.

Is there a way to ensure my portfolio is always 25% for each stock?

4 responses

It may be easier if you attached a backtest of your algorithm to see the ordering logic. However, from what I gather, your logic doesn't take into consideration the exception cases that 1) a sell order doesn't sell at all or 2) a sell order partial fills and sells only a portion of shares.

How do you want to handle those? I assume you still want to sell and certainly don't want to buy any more of that stock, however what to do with the 'new' 4th stock. Do you want to distribute 25% to the current picks and take on leverage (potentially, if a stock doesn't sell at all, then you would have 25% allocated to 5 stocks so leverage would go to 1.25). Or, do you want to wait until the stock sells before distributing 25% to the current picks and therefore not take on leverage?

I can add the ordering logic. I have it looks for cash - so this ensures that there is enough cash to purchase shares:

        Curr_P = (data.current(s, 'price'))  
        shares = int((context.portfolio.cash / 4) / Curr_P)  
        order(s, shares, style=LimitOrder(Curr_P))

The sell logic is before this to ensure there is cash available. I don't use order portfolio percentage because it is harder to ensure there is enough cash to be able to purchase anything.

Does that make sense?

Again, it may be easier if you attached a backtest. However, one potential case is that portfolio cash can be negative. You will end up selling shares in the above logic (because of the negative sign).

Is 's' only the 4 stock(s) you want to hold or can it also contain other stocks (ie the ones you want to sell)?

I will work on posting the backtest. In my backtests I run the PvR routine and there is no negative cash every - I think that is due to ensuring the cash is divided by 4 and making it an integer then placing a limit on it.

Yes, 's' is only the 4 stocks I have chosen.

So the issue is that say 1 of the 4 stocks falls out of favor and is sold and lets say there is $1,000 placed on all 4 stocks. Now the algorithm shows there is $1,000 in cash so it then splits the 1,000 by 4 thus reducing the 25% holding on the new stock that is purchased and placing more on the other 3 stocks.

I don't think there is an issue with the selling and negative cash so much as my portfolio becomes extremely reliant on 1-2 stocks.