Functional Weave
Code in Python

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.

def rebalance(holdings: Sequence[RebalanceHolding], cash: Money, minimum_trade: 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
minimum_tradeMoneya trade worth less than this is not placed; 0 places every trade
returnsRebalancePlan

The types it declares, generated into your project

@dataclass(frozen=True)
class RebalanceHolding:
    """A position held in whole units, and the weight it should have."""

    #: unique
    id: str
    #: whole units held now, 0 or more
    units: int
    #: price of one unit, greater than zero
    unit_price: Money
    #: 0 to 10000
    target_basis_points: int

@dataclass(frozen=True)
class RebalanceTrade:
    """What to do with one holding, and where it ends up."""

    id: str
    #: positive to buy, negative to sell, 0 for no trade
    units: int
    #: units x unitPrice, signed the same way
    value: Money
    units_after: int
    value_after: Money
    #: valueAfter / total, half-up
    weight_after_basis_points: int

@dataclass(frozen=True)
class RebalancePlan:
    """Every holding's trade, in input order, and the cash left afterwards."""

    trades: List[RebalanceTrade]
    #: holdings plus cash; trades do not change it
    total_value: Money
    #: total of the buys
    bought: Money
    #: total of the sells, as a positive amount
    sold: Money
    #: never negative: buys are funded from cash and sells
    cash_after: Money

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

from fune.invest.rebalance import rebalance  # invest.rebalance@^1
impl/python.py · 112 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.

from typing import List, Sequence, Set

from .invest_rebalance_types import RebalanceHolding, RebalancePlan, RebalanceTrade
from .money_amount import Money, money  ← from money.amount ^1.0.0 · built alongside by fune


def _is_whole(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def rebalance(holdings: Sequence[RebalanceHolding], cash: Money, minimum_trade: Money) -> RebalancePlan:
    """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."""
    if len(holdings) == 0:
        raise ValueError("holdings must not be empty")
    currency = cash.currency
    if minimum_trade.currency != currency:
        raise ValueError("currency mismatch: %s and %s" % (currency, minimum_trade.currency))
    if not _is_whole(cash.minor) or cash.minor < 0:
        raise ValueError("cash must be whole minor units, 0 or more; received %s" % (cash.minor,))
    if not _is_whole(minimum_trade.minor) or minimum_trade.minor < 0:
        raise ValueError("minimumTrade must be whole minor units, 0 or more; received %s" % (minimum_trade.minor,))
    seen: Set[str] = set()
    total = cash.minor
    targets = 0
    for h in holdings:
        if h.id in seen:
            raise ValueError('duplicate holding id "%s"' % h.id)
        seen.add(h.id)
        if h.unit_price.currency != currency:
            raise ValueError("currency mismatch: %s and %s" % (currency, h.unit_price.currency))
        if not _is_whole(h.units) or h.units < 0:
            raise ValueError('units must be a whole number, 0 or more; received %s for "%s"' % (h.units, h.id))
        if not _is_whole(h.unit_price.minor) or h.unit_price.minor <= 0:
            raise ValueError(
                'unitPrice must be whole minor units greater than zero; received %s for "%s"' % (h.unit_price.minor, h.id)
            )
        t = h.target_basis_points
        if not _is_whole(t) or t < 0 or t > 10000:
            raise ValueError('targetBasisPoints must be a whole number from 0 to 10000; received %s for "%s"' % (t, h.id))
        targets += t
        total += h.units * h.unit_price.minor
    if targets > 10000:
        raise ValueError("targets must sum to at most 10000 basis points, received %d" % targets)
    if total == 0:
        raise ValueError("the portfolio total must be greater than zero")

    minimum = minimum_trade.minor
    trades: List[int] = []
    for h in holdings:
        price = h.unit_price.minor
        n = total * h.target_basis_points
        d = 10000 * price
        target, rem = divmod(n, d)
        if 2 * rem > d or (2 * rem == d and h.units > target):
            target += 1
        trade = target - h.units
        trades.append(0 if abs(trade) * price < minimum else trade)

    def spent() -> int:
        return sum(t * h.unit_price.minor for t, h in zip(trades, holdings))

    cash_after = cash.minor - spent()
    while cash_after < 0:
        pick = -1
        worst = 0
        for i, h in enumerate(holdings):
            if trades[i] <= 0:
                continue
            excess = (h.units + trades[i]) * h.unit_price.minor * 10000 - total * h.target_basis_points
            if pick < 0 or excess > worst:
                pick = i
                worst = excess
        trades[pick] -= 1
        if trades[pick] > 0 and trades[pick] * holdings[pick].unit_price.minor < minimum:
            trades[pick] = 0
        cash_after = cash.minor - spent()

    bought = 0
    sold = 0
    rows: List[RebalanceTrade] = []
    for t, h in zip(trades, holdings):
        price = h.unit_price.minor
        value = t * price
        if value > 0:
            bought += value
        else:
            sold -= value
        units_after = h.units + t
        value_after = units_after * price
        weight, rem = divmod(value_after * 10000, total)
        if 2 * rem >= total:
            weight += 1
        rows.append(
            RebalanceTrade(
                id=h.id,
                units=t,
                value=money(value, currency),
                units_after=units_after,
                value_after=money(value_after, currency),
                weight_after_basis_points=weight,
            )
        )
    return RebalancePlan(
        trades=rows,
        total_value=money(total, currency),
        bought=money(bought, currency),
        sold=money(sold, currency),
        cash_after=money(cash_after, currency),
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Python 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 Python invest.rebalance-1.0.1-python.fune · 33,736 bytes sha256 1aa7296af857da241f9e0b8583602ab455affa1a30bd7f622b82e836e8bff2de

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

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