So there are many ways of doing this, and some logical differences. Depends on what you mean by 5% out of whack.
- Rebalancing when the difference is 5% relative to the total. eg rebalance a 70% weight when it is 75%.
Problem with this method is that it make sense for a 70% weighting, but say you have a 10% weighting... it would only trigger if it was at 15%, which is actually 50% more than what you want.
- Rebalance individual positions when the difference is 5% relative to that position. eg a 70% holding is at 73.5% ( 3.5% being 5% of of the 70% weighting)
One of the issues I have with this is in scenarios where you a small number of positions sometimes you might rebalance one and not the others. eg in your case if your 70-30 weighting moves to 68-32 the smaller will trigger and not the larger (2% is more than 5% of 30%, but 2% is less than 5% of 70%) so you would end up with 68% and 30% with 2% in cash after rebalance.
- Rebalance as in 2, but rebalance the whole book if one is triggered. This is the method I have used in the attached backtest.
A few other changes:
1. Using schedule function instead of your complicated logic around doing every day
2. Using half days = False in schedule function (you had some logic around short days that was complicated, but it didn't look like it does anything).