Solution (source code)

= Solution

The holdings $\phi_t$ and $\pi_t^i$ are numbers of shares, so the marked-to-market <portfolio> value is
$$
\boxed{X_t=\phi_tB_t+\pi_t\cdot S_t.}
$$
The stock prices are ex-dividend prices. Over the trading interval, existing holdings gain $\phi_t\,dB_t$ from the riskless account and $\pi_t\cdot dS_t$ from capital-price changes. In addition, $\pi_t^i$ shares of asset $i$ receive $\pi_t^iD_t^i\,dt$ in cash dividends. If this cash remains in the portfolio and changes of holdings are financed internally, the <self-financing portfolio> equation is
$$
\boxed{dX_t=\phi_t\,dB_t+\pi_t\cdot dS_t+\pi_t\cdot D_t\,dt.}
$$
Rebalancing does not add a separate source of wealth: the cost of purchasing one holding is paid by selling another or by using the cash account. This is why one must specify the gains equation, rather than infer self-financing solely by differentiating the marked-to-market identity. The dividends are reinvested rather than withdrawn as <consumption>.