Buy two stocks at target weights, hold the shares, compute each day’s weights in a long pandas panel, and compare buy and hold with a portfolio rebalanced every day.
After this lesson, you can compute the weights of a portfolio whose shares you hold, and compare its return with a portfolio rebalanced every day.
Why do the weights change?
A stock’s weight is its value divided by the portfolio’s value, and both change with the prices. When AAA rises 20% and BBB stays flat, AAA’s weight grows from 0.500 to 0.545 without any trade.
Here \(n_i\) is the number of shares of stock \(i\), \(P_{i,t}\) its price on day \(t\), and the sum runs over the stocks in the portfolio.
The example is a long panel, as in the lesson on long and wide panels, of two made-up stocks over three trading days. I invest 1,000 dollars at the first close, half in AAA at 10 dollars a share and half in BBB at 20 dollars a share, so I buy 50 and 25 shares.
position_value computes each row’s value in dollars. .transform("first") puts each stock’s first price on all its rows, .map(target) puts each stock’s target weight on its rows, and dividing the target dollars by the first price gives the shares. .transform("sum") puts each day’s portfolio value on that day’s rows, so dividing gives the weights.
The following box builds the panel and computes the values and weights.
On 4 March, BBB rises 25% while AAA stays flat, so the weights become 0.490 and 0.510. A stock gains weight whenever its return beats the portfolio’s return.
What changes if I rebalance every day?
A portfolio rebalanced every day trades back to the targets at each close, so every day’s return uses the weights 0.5 and 0.5. Buy and hold earns 22.5% over the two days, and daily rebalancing earns 23.75%.
As in the lesson on percentage changes, .pct_change() gives each stock’s daily return. Multiplying by the targets and adding within each date gives the rebalanced portfolio’s daily return, and (1 + daily).prod() - 1 compounds it. Buy and hold’s return is the last portfolio value divided by the 1,000 dollars invested, minus 1.