Functional Weave
Code in Python

invest.portfolio-weights Unreviewed

Each holding's share of a portfolio and its drift from a target weight, in basis points, from exact arithmetic.

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

Pinned by 19 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

Each holding's weight in a portfolio, the weight it is meant to have, and how far it has drifted, in basis points (10000 = 100%) and in money. It is the first step of any rebalancing policy: "rebalance when anything drifts more than 5 percentage points" is `maxAbsDriftBasisPoints > 500`.

## Why it is shaped this way

For example

  • portfolio_weights(holdings ×2) → total £10,000.00, holdings ×2, max abs drift basis points 0% a 60/40 portfolio exactly on target
  • portfolio_weights(holdings ×2) → total £10,000.00, holdings ×2, max abs drift basis points 10% equities have run up to 70% against a 60% target
  • portfolio_weights(holdings ×3) → total £3.00, holdings ×3, max abs drift basis points 0.01% three equal holdings are 3333 bp each and the weights do not sum to 10000

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 portfolio_weights(holdings: Sequence[PortfolioHolding]) -> PortfolioWeights
holdingsPortfolioHolding[]every position, in the order to report them; targets sum to 10000
returnsPortfolioWeights

The types it declares, generated into your project

@dataclass(frozen=True)
class PortfolioHolding:
    """One position and the share of the portfolio it should be."""

    #: a fund code, ticker or asset class; unique
    id: str
    #: market value now, 0 or more
    value: Money
    #: the intended weight, 0 to 10000
    target_basis_points: int

@dataclass(frozen=True)
class HoldingWeight:
    """Where one holding stands against its target."""

    id: str
    value: Money
    #: value / total, half-up to a whole basis point
    weight_basis_points: int
    target_basis_points: int
    #: weight minus target from the exact values, half away from zero; positive is overweight
    drift_basis_points: int
    #: total x target, half-up to a minor unit
    target_value: Money
    #: value minus targetValue; positive is overweight
    drift_value: Money

@dataclass(frozen=True)
class PortfolioWeights:
    """The portfolio total and every holding against its target."""

    total: Money
    holdings: List[HoldingWeight]
    #: the largest drift either way, for threshold rebalancing
    max_abs_drift_basis_points: int

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

from fune.invest.portfolio_weights import portfolio_weights  # invest.portfolio-weights@^1
impl/python.py · 71 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_portfolio_weights_types import HoldingWeight, PortfolioHolding, PortfolioWeights
from .money_amount import money  ← from money.amount ^1.0.0 · built alongside by fune


def _round_half_away(n: int, d: int) -> int:
    """n / d rounded half away from zero; d > 0."""
    a = -n if n < 0 else n
    q, r = divmod(a, d)
    if 2 * r >= d:
        q += 1
    return -q if n < 0 else q


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


def portfolio_weights(holdings: Sequence[PortfolioHolding]) -> PortfolioWeights:
    """Each holding's weight, target and drift. Everything is derived from the
    integer values and rounded once at the end, so a weight is never computed
    from another rounded figure."""
    if len(holdings) == 0:
        raise ValueError("holdings must not be empty")
    currency = holdings[0].value.currency
    seen: Set[str] = set()
    total = 0
    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.value.currency != currency:
            raise ValueError("currency mismatch: %s and %s" % (currency, h.value.currency))
        if not _is_int(h.value.minor) or h.value.minor < 0:
            raise ValueError(
                'holding values must be whole minor units, 0 or more; received %s for "%s"' % (h.value.minor, h.id)
            )
        t = h.target_basis_points
        if not _is_int(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)
            )
        total += h.value.minor
        targets += t
    if targets != 10000:
        raise ValueError("targets must sum to 10000 basis points, received %d" % targets)
    if total == 0:
        raise ValueError("the portfolio total must be greater than zero")

    max_abs = 0
    rows: List[HoldingWeight] = []
    for h in holdings:
        value = h.value.minor
        target = h.target_basis_points
        drift = _round_half_away(value * 10000 - target * total, total)
        target_value = _round_half_away(total * target, 10000)
        max_abs = max(max_abs, abs(drift))
        rows.append(
            HoldingWeight(
                id=h.id,
                value=money(value, currency),
                weight_basis_points=_round_half_away(value * 10000, total),
                target_basis_points=target,
                drift_basis_points=drift,
                target_value=money(target_value, currency),
                drift_value=money(value - target_value, currency),
            )
        )
    return PortfolioWeights(total=money(total, currency), holdings=rows, max_abs_drift_basis_points=max_abs)

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.portfolio-weights
Download for Python invest.portfolio-weights-1.0.1-python.fune · 26,946 bytes sha256 101a618bfb43af3e58ee087ae1904c02ad40dc0b580c7a8074c3a182f901ede0

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

The whole function, every language, is one file too: invest.portfolio-weights-1.0.1.fune, 35,377 bytes, sha256 71b36d3c97468580a8343302d7f638bdd4a8437780e9831038a47dd616f9607e. 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.portfolio-weights

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

# fune: after invest.portfolio-weights

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.portfolio-weights

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.portfolio-weights --steps.

# fune: step invest.portfolio-weights 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
a 60/40 portfolio exactly on target holdings ×2 → total £10,000.00, holdings ×2, max abs drift basis points 0%
equities have run up to 70% against a 60% target holdings ×2 → total £10,000.00, holdings ×2, max abs drift basis points 10%
three equal holdings are 3333 bp each and the weights do not sum to 10000 holdings ×3 → total £3.00, holdings ×3, max abs drift basis points 0.01%
half a basis point rounds up for both holdings, so the weights sum to 10001 holdings ×2 → total £200.00, holdings ×2, max abs drift basis points 0.01%
drift comes from the exact values, not weight minus target: -0.5 bp is -1, not 1 - 1 = 0 holdings ×2 → total £200.00, holdings ×2, max abs drift basis points 0.01%
a new fund worth nothing yet is fully underweight holdings ×2 → total £5,000.00, holdings ×2, max abs drift basis points 50%
a holding with a zero target is all drift holdings ×2 → total £10,000.00, holdings ×2, max abs drift basis points 25%
values whose x10000 passes 2^53 stay exact holdings ×2 → total £10,000,000,000,000.00, holdings ×2, max abs drift basis points 40%
a single holding is the whole portfolio holdings ×1 → total £123.45, holdings ×1, max abs drift basis points 0%
a third of a basis point rounds down both ways holdings ×2 → total £1,000.00, holdings ×2, max abs drift basis points 3.33%
Show the other 9 tests
CaseArgumentsExpected
an empty portfolio is an error → error: holdings must not be empty
the same id twice is an error holdings ×2 → error: duplicate holding id "A"
targets summing to 9999 are an error holdings ×2 → error: targets must sum to 10000 basis points, received 9999
mixed currencies are an error holdings ×2 → error: currency mismatch: GBP and USD
a negative value is an error holdings ×2 → error: holding values must be whole minor units, 0 or more
a fractional minor unit is an error holdings ×2 → error: holding values must be whole minor units, 0 or more
a target above 10000 is an error even if the sum works out holdings ×2 → error: targetBasisPoints must be a whole number from 0 to 10000
a fractional target is an error holdings ×2 → error: targetBasisPoints must be a whole number from 0 to 10000
a portfolio worth nothing is an error holdings ×2 → error: the portfolio total must be greater than zero

More from the author

- **Integer arithmetic throughout.** Values are `Money` in minor units and every ratio is computed from them exactly (with 128-bit or arbitrary-size integers inside, so a portfolio of billions does not overflow), then rounded once. - **Each weight is rounded on its own**, half-up to a whole basis point. The weights therefore need not add up to exactly 10000: three equal holdings are 3333 bp each. Forcing them to sum (largest remainder) would move one holding's weight by a basis point it does not have, and the drift of that holding would be wrong. If you need weights that sum for a pie chart, use `money.allocate` on the values. - **Drift is computed from the exact values**, (value x 10000 - target x total) / total, and rounded once, half away from zero. At an exact half basis point this can differ by one from `weightBasisPoints - targetBasisPoints`, which rounds twice. - **`driftValue` is the money to sell (positive) or buy (negative)** to hit the target exactly, before any whole-unit or minimum-trade constraint; `invest.rebalance` applies those.

## Edge cases

- Targets must sum to exactly 10000. A holding may have a target of 0 (something to sell out of) and a holding may be worth 0 (something to buy). - A portfolio worth nothing has no weights and is an error, as are negative values (short positions are out of scope), duplicate ids, mixed currencies and an empty list.

## 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.md2,855
impl/python.py2,789
impl/rust.rs5,349
impl/typescript.ts2,756
vectors.json15,220