Functional Weave
Code in Rust

invest.cagr

Compound annual growth rate between two values over a whole or fractional number of years, in basis points.

1.0.0 (not the latest) · published 2026-10-03 by charlie · Anterra

Pinned by 22 tests, run in TypeScript, Python and Rust.

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 compound annual growth rate: the constant yearly rate that turns the start value into the end value over the holding period,

CAGR = (end / start)^(1 / years) − 1

For example

  • cagr(£100.00, £200.00, 10, 1) → 718 doubling over ten years is 7.18% a year (7.1773...%)
  • cagr(£100.00, £121.00, 2, 1) → 1,000 121 from 100 over two years is exactly 10%
  • cagr(£100.00, £107.25, 1, 1) → 725 one year is the simple return

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 cagr(start_value: &Money, end_value: &Money, years_numerator: i64, years_denominator: i64) -> i64
start_valueMoneythe value at the start; greater than zero
end_valueMoneythe value at the end, same currency; zero is a total loss
years_numeratorintthe holding period is yearsNumerator / yearsDenominator years: 18 months is 3 / 2
years_denominatorint1 to 100000
returnsintthe rate in basis points, half away from zero: 718 = 7.18% a year

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

fune!(invest.cagr@^1);  // then call cagr(…)
impl/rust.rs · 75 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::math_big_integer::BigInt;  ← from math.big-integer ^1.0.0 · built alongside by fune
use super::math_fractional_power::{fixed_scale, fractional_power_fixed};  ← from math.fractional-power ^1.0.0 · built alongside by fune
use super::money_amount::{money_from_value, Money};  ← from money.amount ^1.0.0 · built alongside by fune

/// The largest integer every language holds exactly (2^53 − 1).
const MAX_SAFE: i64 = 9007199254740991;

fn check_years(name: &str, value: i64) {
    if value < 1 || value > 100000 {
        panic!("{} must be a whole number from 1 to 100000, received {}", name, value);
    }
}

/// n / d rounded half away from zero; d > 0.
fn round_half_away(n: &BigInt, d: &BigInt) -> BigInt {
    let two = BigInt::from_i64(2);
    let magnitude = n.abs().mul(&two).add(d).div(&two.mul(d));
    if n.is_negative() {
        magnitude.neg()
    } else {
        magnitude
    }
}

/// Compound annual growth rate, (end / start)^(1 / years) − 1, in basis
/// points rounded half away from zero. Years are years_numerator /
/// years_denominator so no float ever enters the power.
///
/// # Panics
/// Panics on a start of zero or less, a negative end, mixed currencies, years
/// out of range, or a rate too large to express.
pub fn cagr(start_value: &Money, end_value: &Money, years_numerator: i64, years_denominator: i64) -> i64 {
    if start_value.currency != end_value.currency {
        panic!("currency mismatch: {} and {}", start_value.currency, end_value.currency);
    }
    check_years("yearsNumerator", years_numerator);
    check_years("yearsDenominator", years_denominator);
    if start_value.minor <= 0 {
        panic!("startValue must be greater than zero, received {}", start_value.minor);
    }
    if end_value.minor < 0 {
        panic!("endValue must not be negative, received {}", end_value.minor);
    }
    if end_value.minor == 0 {
        return -10000;
    }
    let scale = fixed_scale();
    let ratio = BigInt::from_i64(end_value.minor).mul(&scale).div(&BigInt::from_i64(start_value.minor));
    // Exponent 1 / years = years_denominator / years_numerator.
    let growth = fractional_power_fixed(&ratio, years_denominator, years_numerator);
    let bp = round_half_away(&growth.sub(&scale).mul(&BigInt::from_i64(10000)), &scale);
    if bp > BigInt::from_i64(MAX_SAFE) {
        panic!("the growth rate is too large to express in basis points");
    }
    bp.to_i64()
}

fn whole(v: &Value, what: &str) {
    if let Value::Float(f) = v {
        if f.fract() != 0.0 {
            panic!("{}, received {}", what, f);
        }
    }
}

pub fn fune_vector(args: &[Value]) -> Value {
    // Refuse what the typed signature cannot hold, with the wording TypeScript
    // and Python use, rather than let the conversion quietly truncate it.
    whole(args[0].get("minor"), "amounts must be whole minor units");
    whole(args[1].get("minor"), "amounts must be whole minor units");
    whole(&args[2], "yearsNumerator must be a whole number from 1 to 100000");
    whole(&args[3], "yearsDenominator must be a whole number from 1 to 100000");
    Value::Int(cagr(&money_from_value(&args[0]), &money_from_value(&args[1]), args[2].as_i64(), args[3].as_i64()))
}

Install

fune build

With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and its 3 dependencies, 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.cagr
Download for Rust invest.cagr-1.0.0-rust.fune · 12,417 bytes sha256 8f520ed5f29b73507941f7308b36c1cc80cb058192eece4506e9f29c420a59e4

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

The whole function, every language, is one file too: invest.cagr-1.0.0.fune, 16,835 bytes, sha256 ebc46061334ef247274a4bdfaf641207eda3ad7c2ab652d775e7b2b3f4b58356. 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.cagr

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

// fune: after invest.cagr

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 math.big-integer in invest.cagr
// fune: replace math.fractional-power in invest.cagr
// fune: replace money.amount in invest.cagr

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.cagr --steps.

// fune: step invest.cagr 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
doubling over ten years is 7.18% a year (7.1773...%) £100.00, £200.00, 10, 1 → 718
121 from 100 over two years is exactly 10% £100.00, £121.00, 2, 1 → 1,000
one year is the simple return £100.00, £107.25, 1, 1 → 725
18 months as 3/2 years: 1.21^(2/3) - 1 = 13.55% £100.00, £121.00, 3, 2 → 1,355
six months of 5% annualises to 10.25%, not 10% £100.00, £105.00, 1, 2 → 1,025
one month of 1% compounds to 12.68% a year £1.00, £1.01, 1, 12 → 1,268
30 days as 30/365 years £100.00, £101.00, 30, 365 → 1,287
halving over five years is -12.94% a year £100.00, £50.00, 5, 1 → -1,294
a total loss is -100% whatever the period £100.00, £0.00, 7, 1 → -10,000
no change is zero £555.55, £555.55, 3, 1 → 0
Show the other 12 tests
CaseArgumentsExpected
exactly +0.5 bp rounds away from zero to 1 £10,000.00, £10,000.50, 1, 1 → 1
exactly -0.5 bp rounds away from zero to -1 £10,000.00, £9,999.50, 1, 1 → -1
a third up in a year: 33.33% (repeating ratio) £3.00, £4.00, 1, 1 → 3,333
seven-year growth from awkward amounts £123,456.78, £987,654.32, 7, 1 → 3,459
works in any currency, yen included ¥1,000,000, ¥2,000,000, 10, 1 → 718
a start of zero is an error £0.00, £1.00, 1, 1 → error: startValue must be greater than zero
a negative end value is an error £1.00, -£0.01, 1, 1 → error: endValue must not be negative
mixed currencies are an error £1.00, €2.00, 1, 1 → error: currency mismatch
zero years is an error £1.00, £2.00, 0, 1 → error: yearsNumerator must be a whole number from 1 to 100000
a zero denominator is an error £1.00, £2.00, 1, 0 → error: yearsDenominator must be a whole number from 1 to 100000
a fractional number of years must be written as a fraction £1.00, £2.00, 1.5, 1 → error: yearsNumerator must be a whole number from 1 to 100000
fractional minor units are refused £100..5, £2.00, 1, 1 → error: amounts must be whole minor units

More from the author

returned in basis points (718 = 7.18% a year).

## Why it is shaped this way

- **Years are a fraction**, `yearsNumerator / yearsDenominator`, so 18 months is `3, 2` and 30 days is `30, 365`. A float number of years would put the platform's `pow` back into the answer, and it differs by an ulp across languages. - **Short periods are annualised by compounding**, not scaled: 5% in six months is 10.25% a year, not 10%. Whether a return under a year should be annualised at all is the caller's decision (GIPS says not to present one); this function does what it is asked. - **Exact arithmetic.** end / start is taken to 18 decimal places (floored), and raised to 1 / years with `math.fractional-power`'s 18-place fixed point, which floors every step in the same order in every language. The result is then rounded to a whole basis point, **half away from zero**: +0.5 bp is 1, −0.5 bp is −1. The fixed-point error is around 10^-16, far below the half basis point, and a power that is exact in 18 places (1.21^(1/2) = 1.1) comes out exact.

## Edge cases

- An end value of zero is a total loss, −10000 (−100%), for any period. - Equal values are 0. - The start must be greater than zero, the end must not be negative, and both must be in the same currency. - `yearsNumerator` and `yearsDenominator` are whole numbers from 1 to 100000. - A growth so large the rate cannot be held (e.g. a thousandfold rise in a week) is an error rather than an overflow.

Files

PathBytes
README.md1,677
impl/python.py2,113
impl/rust.rs3,068
impl/typescript.ts2,137
vectors.json4,877