Functional Weave
Code in Rust

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.

pub fn portfolio_weights(holdings: &[PortfolioHolding]) -> PortfolioWeights
holdingsPortfolioHolding[]every position, in the order to report them; targets sum to 10000
returnsPortfolioWeights

The types it declares, generated into your project

/// One position and the share of the portfolio it should be.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortfolioHolding {
    /// a fund code, ticker or asset class; unique
    pub id: String,
    /// market value now, 0 or more
    pub value: Money,
    /// the intended weight, 0 to 10000
    pub target_basis_points: i64,
}

/// Where one holding stands against its target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HoldingWeight {
    pub id: String,
    pub value: Money,
    /// value / total, half-up to a whole basis point
    pub weight_basis_points: i64,
    pub target_basis_points: i64,
    /// weight minus target from the exact values, half away from zero; positive is overweight
    pub drift_basis_points: i64,
    /// total x target, half-up to a minor unit
    pub target_value: Money,
    /// value minus targetValue; positive is overweight
    pub drift_value: Money,
}

/// The portfolio total and every holding against its target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortfolioWeights {
    pub total: Money,
    pub holdings: Vec<HoldingWeight>,
    /// the largest drift either way, for threshold rebalancing
    pub max_abs_drift_basis_points: i64,
}

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

fune!(invest.portfolio-weights@^1);  // then call portfolio_weights(…)
impl/rust.rs · 148 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.

use super::funejson::Value;  ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::money_amount::{money, money_from_value, money_to_value};  ← from money.amount ^1.0.0 · built alongside by fune

/// n / d rounded half away from zero; d > 0.
fn round_half_away(n: i128, d: i128) -> i128 {
    let a = n.abs();
    let mut q = a / d;
    if 2 * (a - q * d) >= d {
        q += 1;
    }
    if n < 0 {
        -q
    } else {
        q
    }
}

/// 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.
///
/// # Panics
/// Panics on an empty list, a duplicate id, mixed currencies, a negative
/// value, a target outside 0 to 10000, targets that do not sum to 10000, or a
/// portfolio worth nothing.
pub fn portfolio_weights(holdings: &[PortfolioHolding]) -> PortfolioWeights {
    if holdings.is_empty() {
        panic!("holdings must not be empty");
    }
    let currency = holdings[0].value.currency.clone();
    let mut seen: Vec<&str> = Vec::new();
    let mut total: i128 = 0;
    let mut targets: i64 = 0;
    for h in holdings {
        if seen.contains(&h.id.as_str()) {
            panic!("duplicate holding id \"{}\"", h.id);
        }
        seen.push(&h.id);
        if h.value.currency != currency {
            panic!("currency mismatch: {} and {}", currency, h.value.currency);
        }
        if h.value.minor < 0 {
            panic!(
                "holding values must be whole minor units, 0 or more; received {} for \"{}\"",
                h.value.minor, h.id
            );
        }
        if h.target_basis_points < 0 || h.target_basis_points > 10000 {
            panic!(
                "targetBasisPoints must be a whole number from 0 to 10000; received {} for \"{}\"",
                h.target_basis_points, h.id
            );
        }
        total += h.value.minor as i128;
        targets += h.target_basis_points;
    }
    if targets != 10000 {
        panic!("targets must sum to 10000 basis points, received {}", targets);
    }
    if total == 0 {
        panic!("the portfolio total must be greater than zero");
    }
    let mut max_abs: i64 = 0;
    let rows: Vec<HoldingWeight> = holdings
        .iter()
        .map(|h| {
            let value = h.value.minor as i128;
            let target = h.target_basis_points as i128;
            let drift = round_half_away(value * 10000 - target * total, total) as i64;
            let target_value = round_half_away(total * target, 10000) as i64;
            max_abs = max_abs.max(drift.abs());
            HoldingWeight {
                id: h.id.clone(),
                value: money(h.value.minor, &currency),
                weight_basis_points: round_half_away(value * 10000, total) as i64,
                target_basis_points: h.target_basis_points,
                drift_basis_points: drift,
                target_value: money(target_value, &currency),
                drift_value: money(h.value.minor - target_value, &currency),
            }
        })
        .collect();
    PortfolioWeights {
        total: money(total as i64, &currency),
        holdings: rows,
        max_abs_drift_basis_points: max_abs,
    }
}

fn whole(v: &Value, what: &str, id: &str) -> i64 {
    if let Value::Float(f) = v {
        if f.fract() != 0.0 {
            match what {
                "value" => panic!(
                    "holding values must be whole minor units, 0 or more; received {} for \"{}\"",
                    f, id
                ),
                _ => panic!(
                    "targetBasisPoints must be a whole number from 0 to 10000; received {} for \"{}\"",
                    f, id
                ),
            }
        }
    }
    v.as_i64()
}

pub fn portfolio_holding_from_value(v: &Value) -> PortfolioHolding {
    let id = v.get("id").as_str().to_string();
    whole(v.get("value").get("minor"), "value", &id);
    PortfolioHolding {
        target_basis_points: whole(v.get("targetBasisPoints"), "target", &id),
        value: money_from_value(v.get("value")),
        id,
    }
}

pub fn portfolio_weights_to_value(result: &PortfolioWeights) -> Value {
    Value::obj(vec![
        ("total", money_to_value(&result.total)),
        (
            "holdings",
            Value::Arr(
                result
                    .holdings
                    .iter()
                    .map(|h| {
                        Value::obj(vec![
                            ("id", Value::str(&h.id)),
                            ("value", money_to_value(&h.value)),
                            ("weightBasisPoints", Value::Int(h.weight_basis_points)),
                            ("targetBasisPoints", Value::Int(h.target_basis_points)),
                            ("driftBasisPoints", Value::Int(h.drift_basis_points)),
                            ("targetValue", money_to_value(&h.target_value)),
                            ("driftValue", money_to_value(&h.drift_value)),
                        ])
                    })
                    .collect(),
            ),
        ),
        ("maxAbsDriftBasisPoints", Value::Int(result.max_abs_drift_basis_points)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let holdings: Vec<PortfolioHolding> = args[0].as_arr().iter().map(portfolio_holding_from_value).collect();
    portfolio_weights_to_value(&portfolio_weights(&holdings))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 1 dependency, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. Or pin a range in fune.project and build in one step:

fune add invest.portfolio-weights
Download for Rust invest.portfolio-weights-1.0.1-rust.fune · 29,627 bytes sha256 67fd85bae7995c4dbbd568a0f249cc64020f026522d97007c8c3a09ae8b1ac95

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

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