Functional Weave
Code in Rust

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.

pub fn rebalance(holdings: &[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

/// A position held in whole units, and the weight it should have.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RebalanceHolding {
    /// unique
    pub id: String,
    /// whole units held now, 0 or more
    pub units: i64,
    /// price of one unit, greater than zero
    pub unit_price: Money,
    /// 0 to 10000
    pub target_basis_points: i64,
}

/// What to do with one holding, and where it ends up.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RebalanceTrade {
    pub id: String,
    /// positive to buy, negative to sell, 0 for no trade
    pub units: i64,
    /// units x unitPrice, signed the same way
    pub value: Money,
    pub units_after: i64,
    pub value_after: Money,
    /// valueAfter / total, half-up
    pub weight_after_basis_points: i64,
}

/// Every holding's trade, in input order, and the cash left afterwards.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RebalancePlan {
    pub trades: Vec<RebalanceTrade>,
    /// holdings plus cash; trades do not change it
    pub total_value: Money,
    /// total of the buys
    pub bought: Money,
    /// total of the sells, as a positive amount
    pub sold: Money,
    /// never negative: buys are funded from cash and sells
    pub cash_after: Money,
}

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

fune!(invest.rebalance@^1);  // then call rebalance(…)
impl/rust.rs · 215 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, Money};  ← from money.amount ^1.0.0 · built alongside by fune

/// 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.
///
/// # Panics
/// Panics on no holdings, a duplicate id, mixed currencies, negative units or
/// cash or minimum trade, a price of 0 or less, a target outside 0 to 10000,
/// targets over 10000 in total, or a portfolio worth nothing.
pub fn rebalance(holdings: &[RebalanceHolding], cash: &Money, minimum_trade: &Money) -> RebalancePlan {
    if holdings.is_empty() {
        panic!("holdings must not be empty");
    }
    let currency = cash.currency.clone();
    if minimum_trade.currency != currency {
        panic!("currency mismatch: {} and {}", currency, minimum_trade.currency);
    }
    if cash.minor < 0 {
        panic!("cash must be whole minor units, 0 or more; received {}", cash.minor);
    }
    if minimum_trade.minor < 0 {
        panic!("minimumTrade must be whole minor units, 0 or more; received {}", minimum_trade.minor);
    }
    let mut seen: Vec<&str> = Vec::new();
    let mut total: i128 = cash.minor as i128;
    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.unit_price.currency != currency {
            panic!("currency mismatch: {} and {}", currency, h.unit_price.currency);
        }
        if h.units < 0 {
            panic!("units must be a whole number, 0 or more; received {} for \"{}\"", h.units, h.id);
        }
        if h.unit_price.minor <= 0 {
            panic!(
                "unitPrice must be whole minor units greater than zero; received {} for \"{}\"",
                h.unit_price.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
            );
        }
        targets += h.target_basis_points;
        total += h.units as i128 * h.unit_price.minor as i128;
    }
    if targets > 10000 {
        panic!("targets must sum to at most 10000 basis points, received {}", targets);
    }
    if total == 0 {
        panic!("the portfolio total must be greater than zero");
    }

    let minimum = minimum_trade.minor as i128;
    let mut trades: Vec<i128> = holdings
        .iter()
        .map(|h| {
            let price = h.unit_price.minor as i128;
            let units = h.units as i128;
            let n = total * h.target_basis_points as i128;
            let d = 10000 * price;
            let mut target = n / d;
            let twice = 2 * (n - target * d);
            if twice > d || (twice == d && units > target) {
                target += 1;
            }
            let trade = target - units;
            if trade.abs() * price < minimum {
                0
            } else {
                trade
            }
        })
        .collect();

    let spent = |trades: &Vec<i128>| -> i128 {
        trades
            .iter()
            .zip(holdings)
            .map(|(t, h)| t * h.unit_price.minor as i128)
            .sum()
    };
    let mut cash_after = cash.minor as i128 - spent(&trades);
    while cash_after < 0 {
        let mut pick: Option<usize> = None;
        let mut worst: i128 = 0;
        for (i, h) in holdings.iter().enumerate() {
            if trades[i] <= 0 {
                continue;
            }
            let excess = (h.units as i128 + trades[i]) * h.unit_price.minor as i128 * 10000
                - total * h.target_basis_points as i128;
            if pick.is_none() || excess > worst {
                pick = Some(i);
                worst = excess;
            }
        }
        let i = pick.unwrap();
        trades[i] -= 1;
        if trades[i] > 0 && trades[i] * (holdings[i].unit_price.minor as i128) < minimum {
            trades[i] = 0;
        }
        cash_after = cash.minor as i128 - spent(&trades);
    }

    let mut bought: i128 = 0;
    let mut sold: i128 = 0;
    let rows: Vec<RebalanceTrade> = holdings
        .iter()
        .zip(&trades)
        .map(|(h, t)| {
            let price = h.unit_price.minor as i128;
            let value = t * price;
            if value > 0 {
                bought += value;
            } else {
                sold -= value;
            }
            let units_after = h.units as i128 + t;
            let value_after = units_after * price;
            let mut weight = value_after * 10000 / total;
            if 2 * (value_after * 10000 - weight * total) >= total {
                weight += 1;
            }
            RebalanceTrade {
                id: h.id.clone(),
                units: *t as i64,
                value: money(value as i64, &currency),
                units_after: units_after as i64,
                value_after: money(value_after as i64, &currency),
                weight_after_basis_points: weight as i64,
            }
        })
        .collect();
    RebalancePlan {
        trades: rows,
        total_value: money(total as i64, &currency),
        bought: money(bought as i64, &currency),
        sold: money(sold as i64, &currency),
        cash_after: money(cash_after as i64, &currency),
    }
}

fn fraction(v: &Value) -> Option<f64> {
    match v {
        Value::Float(f) if f.fract() != 0.0 => Some(*f),
        _ => None,
    }
}

pub fn rebalance_holding_from_value(v: &Value) -> RebalanceHolding {
    let id = v.get("id").as_str().to_string();
    if let Some(f) = fraction(v.get("units")) {
        panic!("units must be a whole number, 0 or more; received {} for \"{}\"", f, id);
    }
    if let Some(f) = fraction(v.get("unitPrice").get("minor")) {
        panic!("unitPrice must be whole minor units greater than zero; received {} for \"{}\"", f, id);
    }
    if let Some(f) = fraction(v.get("targetBasisPoints")) {
        panic!("targetBasisPoints must be a whole number from 0 to 10000; received {} for \"{}\"", f, id);
    }
    RebalanceHolding {
        units: v.get("units").as_i64(),
        unit_price: money_from_value(v.get("unitPrice")),
        target_basis_points: v.get("targetBasisPoints").as_i64(),
        id,
    }
}

pub fn rebalance_plan_to_value(plan: &RebalancePlan) -> Value {
    Value::obj(vec![
        (
            "trades",
            Value::Arr(
                plan.trades
                    .iter()
                    .map(|t| {
                        Value::obj(vec![
                            ("id", Value::str(&t.id)),
                            ("units", Value::Int(t.units)),
                            ("value", money_to_value(&t.value)),
                            ("unitsAfter", Value::Int(t.units_after)),
                            ("valueAfter", money_to_value(&t.value_after)),
                            ("weightAfterBasisPoints", Value::Int(t.weight_after_basis_points)),
                        ])
                    })
                    .collect(),
            ),
        ),
        ("totalValue", money_to_value(&plan.total_value)),
        ("bought", money_to_value(&plan.bought)),
        ("sold", money_to_value(&plan.sold)),
        ("cashAfter", money_to_value(&plan.cash_after)),
    ])
}

pub fn fune_vector(args: &[Value]) -> Value {
    let holdings: Vec<RebalanceHolding> = args[0].as_arr().iter().map(rebalance_holding_from_value).collect();
    if let Some(f) = fraction(args[1].get("minor")) {
        panic!("cash must be whole minor units, 0 or more; received {}", f);
    }
    if let Some(f) = fraction(args[2].get("minor")) {
        panic!("minimumTrade must be whole minor units, 0 or more; received {}", f);
    }
    rebalance_plan_to_value(&rebalance(&holdings, &money_from_value(&args[1]), &money_from_value(&args[2])))
}

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.rebalance
Download for Rust invest.rebalance-1.0.1-rust.fune · 37,454 bytes sha256 0356fbc0c7506938fd6b1c0a109166da787d56ab47395b25e54fc61920ac139a

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

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