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
portfolioWeights(holdings ×2)→ total £10,000.00, holdings ×2, max abs drift basis points 0% a 60/40 portfolio exactly on targetportfolioWeights(holdings ×2)→ total £10,000.00, holdings ×2, max abs drift basis points 10% equities have run up to 70% against a 60% targetportfolioWeights(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.
export function portfolioWeights(holdings: readonly PortfolioHolding[]): PortfolioWeights
| holdings | PortfolioHolding[] | every position, in the order to report them; targets sum to 10000 |
| returns | PortfolioWeights |
The types it declares, generated into your project
/** One position and the share of the portfolio it should be. */
export interface PortfolioHolding {
/** a fund code, ticker or asset class; unique */
readonly id: string;
/** market value now, 0 or more */
readonly value: Money;
/** the intended weight, 0 to 10000 */
readonly targetBasisPoints: number;
}
/** Where one holding stands against its target. */
export interface HoldingWeight {
readonly id: string;
readonly value: Money;
/** value / total, half-up to a whole basis point */
readonly weightBasisPoints: number;
readonly targetBasisPoints: number;
/** weight minus target from the exact values, half away from zero; positive is overweight */
readonly driftBasisPoints: number;
/** total x target, half-up to a minor unit */
readonly targetValue: Money;
/** value minus targetValue; positive is overweight */
readonly driftValue: Money;
}
/** The portfolio total and every holding against its target. */
export interface PortfolioWeights {
readonly total: Money;
readonly holdings: readonly HoldingWeight[];
/** the largest drift either way, for threshold rebalancing */
readonly maxAbsDriftBasisPoints: number;
}
Your code names it in one line, in the file that uses it
import { portfolioWeights } from "#fune/invest.portfolio-weights@^1";
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 HoldingWeight, type PortfolioHolding, type PortfolioWeights } from "./invest_portfolio_weights_types.ts";
/** n / d rounded half away from zero; d > 0. */
function roundHalfAway(n: bigint, d: bigint): bigint {
const negative = n < 0n;
const a = negative ? -n : n;
let q = a / d;
if (2n * (a - q * d) >= d) q += 1n;
return negative ? -q : 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.
*/
export function portfolioWeights(holdings: readonly PortfolioHolding[]): PortfolioWeights {
if (holdings.length === 0) throw new RangeError("holdings must not be empty");
const currency = holdings[0].value.currency;
const seen = new Set<string>();
let total = 0n;
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.value.currency !== currency) throw new RangeError(`currency mismatch: ${currency} and ${h.value.currency}`);
if (!Number.isInteger(h.value.minor) || h.value.minor < 0) {
throw new RangeError(`holding values must be whole minor units, 0 or more; received ${h.value.minor} for "${h.id}"`);
}
if (!Number.isInteger(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}"`);
}
total += BigInt(h.value.minor);
targets += h.targetBasisPoints;
}
if (targets !== 10000) throw new RangeError(`targets must sum to 10000 basis points, received ${targets}`);
if (total === 0n) throw new RangeError("the portfolio total must be greater than zero");
let maxAbs = 0;
const rows: HoldingWeight[] = holdings.map((h) => {
const value = BigInt(h.value.minor);
const target = BigInt(h.targetBasisPoints);
const weight = Number(roundHalfAway(value * 10000n, total));
const drift = Number(roundHalfAway(value * 10000n - target * total, total));
const targetValue = Number(roundHalfAway(total * target, 10000n));
maxAbs = Math.max(maxAbs, Math.abs(drift));
return {
id: h.id,
value: money(h.value.minor, currency),
weightBasisPoints: weight,
targetBasisPoints: h.targetBasisPoints,
driftBasisPoints: drift,
targetValue: money(targetValue, currency),
driftValue: money(h.value.minor - targetValue, currency),
};
});
const totalMoney: Money = money(Number(total), currency);
return { total: totalMoney, holdings: rows, maxAbsDriftBasisPoints: maxAbs };
}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.portfolio-weights
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./invest.portfolio-weights-1.0.1-typescript.fune, or fetch it from a terminal with fune pull invest.portfolio-weights@1.0.1:typescript.
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.
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Path | Bytes |
|---|---|
| README.md | 2,855 |
| impl/python.py | 2,789 |
| impl/rust.rs | 5,349 |
| impl/typescript.ts | 2,756 |
| vectors.json | 15,220 |