I'm new and learning about how the portfolio is rebalanced. I have taken a code sample from one of the tutorials and placed it below.
def my_rebalance(context, data):
lng_secs = context.output[context.output['longs']].index
lng_wghts = 0.5/len(lng_secs)
shrt_secs = context.output[context.output['shorts']].index
shrt_wghts = -0.5/len(shrt_secs)
for security in lng_secs:
if data.can_trade(security):
order_target_percent(security, lng_wghts)
for security in shrt_secs:
if data.can_trade(security):
order_target_percent(security, shrt_wghts)
for security in context.portfolio.positions:
if data.can_trade(security) and security not in lng_secs and security not in shrt_secs:
order_target_percent(security, 0)
Based on the above, I have two questions:
- In the last part of the code, we see that securities that are not in the new portfolio are removed. Should this not come before we purchase new securities i.e. should we not liquidate our old positions first and then purchase our new ones? In the above case, this is done afterwards. To me, it makes sense to liquidate first so that we have the cash to purchase new securities. Or is the order not relevant i.e. does Quantopian fix this automatically?
- In the above, we only liquidate our positions if the security can trade. What if it can't? how does our new portfolio weights get affected? By example, let's say we have two securities A & B in our portfolio with a 50/50 split. Then let's say our new strategy tells us that we need to rebalance to a 50/50 split of B & C. What happens when A can't trade? Does C stay at zero i.e. no rebalancing takes place?
Thanks ahead.