Solution (source code)

= Solution

At time $n-1$, the <self-financing portfolio> can be valued using the holdings about to be carried over the next period:
$$
V_{n-1}=\phi_nS_{n-1}+\psi_nB_{n-1}.
$$
Subtracting this from $V_n=\phi_nS_n+\psi_nB_n$ gives the gains identity
$$
\boxed{V_n-V_{n-1}=\phi_n(S_n-S_{n-1})+\psi_n(B_n-B_{n-1}).}
$$
Conversely, suppose the gains identity and the valuation $V_n=\phi_nS_n+\psi_nB_n$ hold. Rearranging the identity gives $V_{n-1}=\phi_nS_{n-1}+\psi_nB_{n-1}$. Comparing with the valuation using $(\phi_{n-1},\psi_{n-1})$ shows that rebalancing at $n-1$ costs nothing. Applying this at each rebalancing time recovers the <self-financing> condition.