Functional Weave
Code in TypeScript

invest.rebalance Unreviewed

Whole-unit buy and sell trades that bring a portfolio back to target weights, skipping trades below a minimum size.

1.0.1 · published 2026-10-03 by charlie · Anterra

Pinned by 22 tests, run in TypeScript, Python and Rust.

Unreviewed. This capability’s implementations agree in every language and pass its published test vectors, which were worked out from the official sources cited. But no qualified tax adviser has yet checked those vectors, or confirmed that the capability covers the cases it claims. Treat it as a draft. Do not use it for real people, money or decisions without your own expert review. Once a qualified reviewer signs off, this notice is replaced with their name, qualification and the date. Each new version needs fresh sign-off.

Not professional advice. This capability calculates investment figures from published rules. It is a software component for developers, not financial advice. Rules change and every rate here has an effective date. Check that the dates cover your case. Verify results against the official sources listed in its README, and have a tax adviser review how you use it, before anyone relies on the output. Provided “as is” under its licence, without warranty.

What it does

The trades that move a portfolio back to its target weights when it can only trade whole units (shares, fund units) and does not want to pay dealing charges on tiny trades. Prices are taken as given; the plan assumes every trade fills at `unitPrice` and ignores dealing costs and taxes.

## How the plan is built

For example

  • rebalance(holdings ×2, £0.00, £0.00) → trades ×2, total value £100.00, bought £50.00, sold £50.00, cash after £0.00 sell half of one fund to buy another
  • rebalance(holdings ×1, £10.00, £0.00) → trades ×1, total value £10.00, bought £9.99, sold £0.00, cash after £0.01 invest cash in whole units, leaving the odd penny
  • rebalance(holdings ×2, £10.00, £0.00) → trades ×2, total value £10.00, bought £9.00, sold £0.00, cash after £1.00 two buys both round up to 2 units; the first is trimmed so the cash covers them

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

export function rebalance(holdings: readonly RebalanceHolding[], cash: Money, minimumTrade: Money): RebalancePlan
holdingsRebalanceHolding[]every position with its target; targets sum to at most 10000, the rest is the cash target
cashMoneyuninvested cash available to buy with, 0 or more
minimumTradeMoneya trade worth less than this is not placed; 0 places every trade
returnsRebalancePlan

The types it declares, generated into your project

/** A position held in whole units, and the weight it should have. */
export interface RebalanceHolding {
  /** unique */
  readonly id: string;
  /** whole units held now, 0 or more */
  readonly units: number;
  /** price of one unit, greater than zero */
  readonly unitPrice: Money;
  /** 0 to 10000 */
  readonly targetBasisPoints: number;
}

/** What to do with one holding, and where it ends up. */
export interface RebalanceTrade {
  readonly id: string;
  /** positive to buy, negative to sell, 0 for no trade */
  readonly units: number;
  /** units x unitPrice, signed the same way */
  readonly value: Money;
  readonly unitsAfter: number;
  readonly valueAfter: Money;
  /** valueAfter / total, half-up */
  readonly weightAfterBasisPoints: number;
}

/** Every holding's trade, in input order, and the cash left afterwards. */
export interface RebalancePlan {
  readonly trades: readonly RebalanceTrade[];
  /** holdings plus cash; trades do not change it */
  readonly totalValue: Money;
  /** total of the buys */
  readonly bought: Money;
  /** total of the sells, as a positive amount */
  readonly sold: Money;
  /** never negative: buys are funded from cash and sells */
  readonly cashAfter: Money;
}

Your code names it in one line, in the file that uses it

import { rebalance } from "#fune/invest.rebalance@^1";
impl/typescript.ts · 103 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { type Money, money } from "./money_amount.ts";  ← from money.amount ^1.0.0 · built alongside by fune
import { type RebalanceHolding, type RebalancePlan, type RebalanceTrade } from "./invest_rebalance_types.ts";

function isWhole(value: number): boolean {
  return Number.isInteger(value);
}

/**
 * Whole-unit trades back to target weights. Target units are the nearest
 * whole unit (a tie stays nearer the units held), trades below the minimum
 * are dropped, and buys are then trimmed one unit at a time, from the holding
 * that would end furthest above its target, until the cash covers them.
 */
export function rebalance(holdings: readonly RebalanceHolding[], cash: Money, minimumTrade: Money): RebalancePlan {
  if (holdings.length === 0) throw new RangeError("holdings must not be empty");
  const currency = cash.currency;
  if (minimumTrade.currency !== currency) throw new RangeError(`currency mismatch: ${currency} and ${minimumTrade.currency}`);
  if (!isWhole(cash.minor) || cash.minor < 0) throw new RangeError(`cash must be whole minor units, 0 or more; received ${cash.minor}`);
  if (!isWhole(minimumTrade.minor) || minimumTrade.minor < 0) {
    throw new RangeError(`minimumTrade must be whole minor units, 0 or more; received ${minimumTrade.minor}`);
  }
  const seen = new Set<string>();
  let total = BigInt(cash.minor);
  let targets = 0;
  for (const h of holdings) {
    if (seen.has(h.id)) throw new RangeError(`duplicate holding id "${h.id}"`);
    seen.add(h.id);
    if (h.unitPrice.currency !== currency) throw new RangeError(`currency mismatch: ${currency} and ${h.unitPrice.currency}`);
    if (!isWhole(h.units) || h.units < 0) throw new RangeError(`units must be a whole number, 0 or more; received ${h.units} for "${h.id}"`);
    if (!isWhole(h.unitPrice.minor) || h.unitPrice.minor <= 0) {
      throw new RangeError(`unitPrice must be whole minor units greater than zero; received ${h.unitPrice.minor} for "${h.id}"`);
    }
    if (!isWhole(h.targetBasisPoints) || h.targetBasisPoints < 0 || h.targetBasisPoints > 10000) {
      throw new RangeError(`targetBasisPoints must be a whole number from 0 to 10000; received ${h.targetBasisPoints} for "${h.id}"`);
    }
    targets += h.targetBasisPoints;
    total += BigInt(h.units) * BigInt(h.unitPrice.minor);
  }
  if (targets > 10000) throw new RangeError(`targets must sum to at most 10000 basis points, received ${targets}`);
  if (total === 0n) throw new RangeError("the portfolio total must be greater than zero");

  const minimum = BigInt(minimumTrade.minor);
  const trades: bigint[] = holdings.map((h) => {
    const price = BigInt(h.unitPrice.minor);
    const units = BigInt(h.units);
    const n = total * BigInt(h.targetBasisPoints);
    const d = 10000n * price;
    let target = n / d;
    const twice = 2n * (n - target * d);
    if (twice > d || (twice === d && units > target)) target += 1n;
    const trade = target - units;
    const size = trade < 0n ? -trade * price : trade * price;
    return size < minimum ? 0n : trade;
  });

  const spent = () => trades.reduce((sum, t, i) => sum + t * BigInt(holdings[i].unitPrice.minor), 0n);
  let cashAfter = BigInt(cash.minor) - spent();
  while (cashAfter < 0n) {
    let pick = -1;
    let worst = 0n;
    holdings.forEach((h, i) => {
      if (trades[i] <= 0n) return;
      const price = BigInt(h.unitPrice.minor);
      const excess = (BigInt(h.units) + trades[i]) * price * 10000n - total * BigInt(h.targetBasisPoints);
      if (pick < 0 || excess > worst) {
        pick = i;
        worst = excess;
      }
    });
    const price = BigInt(holdings[pick].unitPrice.minor);
    trades[pick] -= 1n;
    if (trades[pick] > 0n && trades[pick] * price < minimum) trades[pick] = 0n;
    cashAfter = BigInt(cash.minor) - spent();
  }

  let bought = 0n;
  let sold = 0n;
  const rows: RebalanceTrade[] = holdings.map((h, i) => {
    const price = BigInt(h.unitPrice.minor);
    const value = trades[i] * price;
    if (value > 0n) bought += value;
    else sold -= value;
    const unitsAfter = BigInt(h.units) + trades[i];
    const valueAfter = unitsAfter * price;
    let weight = (valueAfter * 10000n) / total;
    if (2n * (valueAfter * 10000n - weight * total) >= total) weight += 1n;
    return {
      id: h.id,
      units: Number(trades[i]),
      value: money(Number(value), currency),
      unitsAfter: Number(unitsAfter),
      valueAfter: money(Number(valueAfter), currency),
      weightAfterBasisPoints: Number(weight),
    };
  });
  return {
    trades: rows,
    totalValue: money(Number(total), currency),
    bought: money(Number(bought), currency),
    sold: money(Number(sold), currency),
    cashAfter: money(Number(cashAfter), currency),
  };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add invest.rebalance
Download for TypeScript invest.rebalance-1.0.1-typescript.fune · 33,812 bytes sha256 acc578df52fa942bc64fe568aa22ad68dd73661d4537149aeaac0daf655df3b6

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./invest.rebalance-1.0.1-typescript.fune, or fetch it from a terminal with fune pull invest.rebalance@1.0.1:typescript.

The whole function, every language, is one file too: invest.rebalance-1.0.1.fune, 47,018 bytes, sha256 9a985d1d4806b19bad49add26fea276f96be4bf3b9056c205b28a8eb679302f9. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before invest.rebalance

after — your function gets the result and the arguments, and returns the final result.

// fune: after invest.rebalance

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace money.amount in invest.rebalance

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show invest.rebalance --steps.

// fune: step invest.rebalance after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
sell half of one fund to buy another holdings ×2, £0.00, £0.00 → trades ×2, total value £100.00, bought £50.00, sold £50.00, cash after £0.00
invest cash in whole units, leaving the odd penny holdings ×1, £10.00, £0.00 → trades ×1, total value £10.00, bought £9.99, sold £0.00, cash after £0.01
two buys both round up to 2 units; the first is trimmed so the cash covers them holdings ×2, £10.00, £0.00 → trades ×2, total value £10.00, bought £9.00, sold £0.00, cash after £1.00
one-unit trades below the minimum are not placed holdings ×2, £0.00, £5.00 → trades ×2, total value £198.00, bought £0.00, sold £0.00, cash after £0.00
a trade exactly at the minimum is placed holdings ×2, £0.00, £5.00 → trades ×2, total value £10.00, bought £5.00, sold £5.00, cash after £0.00
the sell that funds a rounded-up buy is too small, so the buy is dropped too holdings ×3, £0.00, £9.50 → trades ×3, total value £100.00, bought £0.00, sold £0.00, cash after £0.00
without a minimum the sell goes ahead but the unfundable buy does not holdings ×3, £0.00, £0.00 → trades ×3, total value £100.00, bought £0.00, sold £9.00, cash after £9.00
targets summing to 8000 leave 20% in cash holdings ×1, £0.00, £0.00 → trades ×1, total value £10.00, bought £0.00, sold £2.00, cash after £2.00
an exact half unit rounds towards the units already held holdings ×2, £0.00, £0.00 → trades ×2, total value £100.00, bought £1.00, sold £1.00, cash after £0.00
a zero target sells the holding out holdings ×2, £0.00, £0.00 → trades ×2, total value £21.00, bought £21.00, sold £21.00, cash after £0.00
Show the other 12 tests
CaseArgumentsExpected
a portfolio already on target trades nothing holdings ×2, £0.00, £0.00 → trades ×2, total value £100.00, bought £0.00, sold £0.00, cash after £0.00
no holdings is an error , £1.00, £0.00 → error: holdings must not be empty
the same id twice is an error holdings ×2, £0.00, £0.00 → error: duplicate holding id "A"
targets over 10000 are an error holdings ×2, £0.00, £0.00 → error: targets must sum to at most 10000 basis points, received 10001
a negative target is an error holdings ×1, £0.00, £0.00 → error: targetBasisPoints must be a whole number from 0 to 10000
a fractional unit holding is an error holdings ×1, £0.00, £0.00 → error: units must be a whole number, 0 or more
negative units are an error holdings ×1, £10.00, £0.00 → error: units must be a whole number, 0 or more
a price of zero is an error holdings ×1, £0.00, £0.00 → error: unitPrice must be whole minor units greater than zero
negative cash is an error holdings ×1, -£0.01, £0.00 → error: cash must be whole minor units, 0 or more
a negative minimum trade is an error holdings ×1, £0.00, -£0.01 → error: minimumTrade must be whole minor units, 0 or more
a price in another currency is an error holdings ×1, £0.00, £0.00 → error: currency mismatch: GBP and USD
a portfolio worth nothing is an error holdings ×1, £0.00, £0.00 → error: the portfolio total must be greater than zero

More from the author

1. **Total** = cash + every holding's units x price. Targets sum to at most 10000 basis points; whatever is left over is the target for cash. 2. **Target units** for each holding = total x target / (10000 x price), rounded to the nearest whole unit. An exact half rounds towards the units already held, so a tie never causes a trade. 3. **Minimum trade.** A trade whose value (units x price) is less than `minimumTrade` is dropped. A trade exactly equal to it is kept. 4. **Funding.** Rounding up can leave the buys costing more than the cash plus the sells, and a dropped sell can leave a buy unfunded. While the cash after trading would be negative, the buy whose holding would end up furthest above its target value loses one unit (ties go to the holding listed first), and a buy that shrinks below the minimum trade is dropped. Sells are never enlarged to pay for buys, so the plan never trades more than the targets ask for.

The result lists every holding in input order, including those with no trade, so a caller can show a before-and-after table directly.

## Why not just divide the drift by the price

That is the naive plan, and it goes wrong three ways the vectors pin down: rounding two buys up overspends the cash, a sell dropped for being small leaves its matching buy unfunded, and truncating every target (to be safe) sells more than needed. The steps above are deterministic, so the same portfolio produces the same trades in every language.

## Edge cases

- A holding with a target of 0 is sold out (subject to the minimum trade). - Weights after trading are rounded independently, half-up, and need not sum to 10000. - Errors: no holdings, duplicate ids, negative or fractional units, a price of 0 or less, a target outside 0-10000 or targets over 10000 in total, negative cash or minimum trade, mixed currencies, and a portfolio worth nothing.

## Before you rely on this

**Not professional advice.** This capability calculates investment figures from published rules. It is a software component for developers, not financial advice. Rules change and every rate here has an effective date. Check that the dates cover your case. Verify results against the official sources listed above, and have a tax adviser review how you use it, before anyone relies on the output. Provided "as is" under its licence, without warranty.

**Unreviewed.** This capability's implementations agree in every language and pass its published test vectors, which were worked out from the official sources cited. But no qualified tax adviser has yet checked those vectors, or confirmed that the capability covers the cases it claims. Treat it as a draft. Do not use it for real people, money or decisions without your own expert review. Once a qualified reviewer signs off, this notice is replaced with their name, qualification and the date. Each new version needs fresh sign-off.

1.0.1 marks it unreviewed. The code and the tests are unchanged.

Files

PathBytes
README.md3,320
impl/python.py4,591
impl/rust.rs8,136
impl/typescript.ts4,680
vectors.json18,425