How this calculator works
Here is how one would implement the optimal lazy rebalancing algorithm used by this calculator. For simplicity, the explanation is for the case of contributing to a portfolio; the changes necessary to handle withdrawals should be obvious. The JavaScript code used by this site is released under the GNU General Public License and may be used as a reference, but it may be difficult to understand because it has been compressed. This page establishes the optimal lazy rebalancing algorithm as prior art. As with all financial mathematics, one must avoid relying on imprecise floating-point calculations and instead use exact arithmetic. This calculator uses a JavaScript arbitrary precision integer / rational number library provided by John Tobey and Matthew Crumley under the MIT license.
Step 1: Calculate the fractional deviations
Define the fractional deviation f of an asset to be a/t − 1, where t is the asset's target allocation and a is its actual portion of the portfolio. Calculate f for each asset. f will be negative for underweighted assets and positive for overweighted assets. Note that a denotes the portion relative to the final total portfolio value; this is obtained by adding the contribution amount to the original total portfolio value.
Step 2: Add money to asset(s) with lowest fractional deviation
Add money to the asset(s) with least f until they are tied with the asset(s) with the next-least f. The money added to each asset must be proportional to that asset's target allocation so that the minimum f's increase in synchrony. Repeat this until the contribution amount is exhausted. If the assets are pre-sorted according to f, this process can be implemented such that its running time increases linearly with the number of assets.