Repository navigation
feat(returns): add rustledger-returns crate with XIRR (money-weighted return) - #1815
Conversation
First slice of the investment-returns feature (#1814): the shared, pure returns-math engine. Per canonical-function discipline, the math lives in a leaf crate so every future consumer (CLI report, BQL, FFI, rustfava) reuses ONE implementation instead of re-deriving it. This PR ships only the money-weighted return: - CashFlow { date, amount } with an investor-centric sign convention (outlay negative, proceeds/dividends/terminal-value positive). - xirr(&[CashFlow]) -> Option<f64>: annualized internal rate of return over an irregularly-spaced series, Newton's method with a bisection fallback, actual/365 day count (matching spreadsheet XIRR and beangrow). Returns None with no sign change, <2 flows, or non-finite results. No ledger loading, price DB, or I/O — cash-flow extraction (group boundary, dividend classification, currency conversion, terminal market valuation) and time-weighted return land in follow-up PRs, since TWR needs the per-date valuations only the extraction layer supplies. Tests validate against the canonical spreadsheet XIRR example (~0.3734), a clean 10% one-year case, a negative return, solver agreement (NPV ~0 at the root), and the None edge cases. Crate registered in the workspace and the crates.io publish list. Part of #1814.
📊 Benchmark Results
vs main branch (2026-07-20)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Adds a new leaf “engine” crate (rustledger-returns) that provides reusable investment-returns math (starting with money-weighted return via XIRR) to support the upcoming returns-reporting pipeline in #1814, keeping the numeric core centralized to avoid consumer-specific re-derivations.
Changes:
- Introduces
rustledger-returnswithCashFlowand anxirr(&[CashFlow]) -> Option<f64>solver (Newton + bisection fallback) plus unit tests. - Wires the new crate into the workspace (members + default-members) and the crates.io publish workflow.
- Adds crate metadata/docs (README + Cargo.toml) and updates the lockfile.
Reviewed changes
Copilot reviewed 5 out of 6 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger-returns/src/lib.rs | Implements CashFlow + XIRR solver and includes unit tests for common/reference cases and None conditions. |
| crates/rustledger-returns/README.md | Documents scope, status, and sign convention for the new returns-math crate. |
| crates/rustledger-returns/Cargo.toml | Defines the new crate package metadata and dependencies. |
| Cargo.toml | Adds rustledger-returns to workspace members and default-members. |
| Cargo.lock | Records the new workspace package in the lockfile. |
| .github/workflows/release-publish.yml | Adds rustledger-returns to the publish order list. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Deep numerical review found five real defects where the solver returned a wrong or fabricated rate; all fixed: - Absolute NPV tolerance (1e-7) was unreachable for large portfolios and trivially satisfied for tiny ones (any rate accepted as a "root"). Now a RELATIVE tolerance scaled to the gross flow magnitude, floored so a near-zero gross can't drive it to 0. - Same-date flows made NPV rate-independent, so Newton's first-iteration check passed at the 0.1 seed and xirr fabricated a 10% return. Now a degenerate "all flows on one day" guard returns None. - Newton's stall branch returned the stalled rate WITHOUT checking it was a root — a step underflowing near the rate=-1 pole was surfaced as a fake IRR and suppressed the bisection fallback. Now it only returns on a genuine NPV check; else bisection runs. - Bisection's lower bracket bound (-0.9999) could not reach near-total- loss IRRs below -99.99%. Lowered to -0.9999999, with explicit endpoint root checks so a root exactly on a bound is detected. - Bisection's `f_a * f_mid < 0` sub-interval test could overflow to ±inf for large NPV magnitudes and misclassify. Replaced with a sign comparison. Also: npv + derivative now share one pass (halves powf per Newton step). New edge-case tests: same-date → None, near-total-loss (~-99.995%), scale invariance across 1e6/1e-6 magnitudes, and a multiple-sign-change series asserting the returned rate is a genuine root. The canonical spreadsheet XIRR reference (~0.3734) still holds.
|
Deep review (16 agents, adversarial numerical verification): 5 real correctness defects in the solver, all fixed in 025a85e. This is exactly the kind of math where adversarial review pays off — the happy-path tests were green but the solver returned wrong or fabricated rates on several inputs:
Plus: npv + derivative share one pass (halves Four new edge-case tests pin the fixed paths: same-date → None, near-total-loss (~-99.995%), scale invariance across 1e6/1e-6 magnitudes, and a multiple-sign-change series asserting the returned rate is a genuine root. The canonical spreadsheet XIRR reference (~0.3734) still holds. 11 tests, clippy/doc/fmt clean. |
…zeroing Copilot review: `to_f64().unwrap_or(0.0)` silently turned an unrepresentable Decimal cash flow into 0, which would corrupt the XIRR with no signal. Collect into Option and propagate None from xirr instead, so a conversion failure yields no rate rather than a wrong one.
…(round-2 review) Second-round deep review found that round-1's bound-lowering was incomplete and could still return a garbage rate near the rate=-1 pole. Rather than chase the bracket bound (which worsens overflow), add a final root verification and document the true limits: - FINAL ROOT CHECK: xirr now verifies the solved candidate is a genuine root (|NPV| <= tol) before returning it. Any path that terminated on an iteration limit, a stalled Newton step, or a bracket corrupted by a non-finite NPV near the pole (a far-dated flow whose discount factor overflows) now yields None, never a fabricated/garbage rate. Genuine results sit well within tol, so valid roots are never rejected. - Documented that IRRs at/below ~-99.99999%/year (near-total annual loss, against the pole) are unresolvable and return None — graceful, not wrong. Bisection also only brackets odd-multiplicity roots; even- multiplicity (touch-without-cross) series may return None. Both noted. Tests: - Replaced the vacuous scale_invariance tiny case (it resolved under the 1e-12 floor with the seed already a root, never exercising relative tolerance) with tiny_magnitude_requires_relative_tolerance: ~1e-8 flows with a ~50% return, where an absolute 1e-7 tolerance would accept the 0.10 seed as a bogus root — asserts the true ~0.498. - large_magnitude_resolves keeps the million-scale case. - extreme_loss_below_supported_range_returns_none pins the graceful-None limit (no garbage) for an IRR against the pole.
|
Round-2 deep review (16 agents): found that round-1's bound-lowering was incomplete — it could still return a garbage rate near the rate=-1 pole. Fixed in 1acfafb, but with a better lever than more bound-tuning:
Also fixed a vacuous test the review flagged: 13 tests, clippy/doc/fmt clean. |
Comparison against the field (scipy brentq, the cskr/xirr Rust crate, Excel/LibreOffice, beangrow's fsolve) showed the one clear best-practice upgrade: the gold-standard 1-D bracketing root-finder is Brent's method, which keeps bisection's guaranteed convergence (a bracket is always maintained) but reaches the root SUPERLINEARLY via inverse-quadratic interpolation and the secant step, bisecting only when those would leave the bracket or fail to shrink it. scipy.optimize.brentq uses it. Replace the bisection fallback with Brent, dependency-free (~50 lines, no argmin/framework pull-in). Same bracket-finding (grow high until a sign change, endpoint-root checks), same relative tolerance, same final root verification — only the refinement inside the bracket changes, so robustness is unchanged and speed of the (cold-path) fallback improves. opposite_signs is reused for the sign tests to stay overflow-safe. New test brent_solves_a_bracketed_root_precisely calls brent directly and asserts full-precision convergence on a clean root; the existing near_total_loss / extreme_loss / newton_and_brent_agree tests exercise the Newton-diverges -> Brent path. 14 tests, clippy/doc/fmt clean.
Round-3 review found my round-2 final root guard was itself a bug: near the rate=-1 pole the NPV derivative is enormous, so a rate Brent pinned to full f64 precision can still have |NPV| a hair above tol — and the `|NPV| <= tol` re-check then WRONGLY rejected that genuine root, returning None for a legitimately-bracketed deep loss (verified: -0.9999995, inside the bracket, returned None). Fix by recognizing a converged, finite, sign-changing bracket is an IVT proof of a root regardless of NPV magnitude: - Drop xirr's `|NPV| <= tol` re-check. Both solvers already self-verify — Newton re-checks NPV at a stalled step; Brent returns only on genuine convergence — so no non-root can reach the caller. - Close the actual garbage path at its source: brent now rejects a bracket whose endpoint NPV is non-finite (a far-dated flow overflowing against the pole), so a corrupted bracket never reaches refinement. - brent's iteration-limit tail now returns None (non-convergence), not an unconverged b. Also (canonical-function discipline): a test-only counter observes accepted inverse-quadratic-interpolation steps, and brent_exercises_inverse_quadratic_interpolation asserts the IQI branch actually runs — so a future corrupted IQI formula can't hide behind the bisection safeguard. Added deep_loss_within_bracket_is_found pinning the fixed behavior (was None, now the rate). 16 tests.
|
Round-3 deep review (Brent-focused): found that my round-2 final guard was itself a bug — and it contradicted my own pre-review analysis, which is precisely why the independent pass earns its keep. The defect: near the rate=-1 pole the NPV derivative is enormous, so a rate Brent pins to full f64 precision can still have The fix — recognize that a converged, finite, sign-changing bracket is an IVT proof of a root regardless of NPV magnitude:
Second finding (test observability, per canonical-function discipline): no test observed which internal Brent branch ran, so a corrupted inverse-quadratic formula could ship masked by the bisection safeguard. Added a test-only IQI-accepted counter + 16 tests, clippy/doc/fmt clean. |
* feat(returns): cash-flow extraction from a booked ledger Adds the layer that turns a booked ledger into the CashFlow series xirr consumes (#1814 phase 1, building on the engine from #1815). The correctness core is a boundary-crossing model. Every account is classified by a `Scope` into one of three roles: - Investment: holdings + settlement cash (value tracked inside the portfolio, not itself a flow) - Income: dividends / gains / fees generated by the investment (internal to the return) - External: everything else (bank, outside cash) -- the money that actually crosses the boundary For a transaction touching an investment or income account, the flow is the sum of its external postings, converted to one reporting currency at the transaction's date. By double-entry this equals the negation of the investment+income side, and summing the external side directly lands the sign investor-centric with no manual negation. Three correctness properties fall out of the model rather than special cases: - a purchase (external cash debited negative) is an outflow - a sale or dividend-to-bank (external cash credited positive) is an inflow - an internal transfer -- shares or cash moved between two in-scope accounts -- has no external posting, so its flow is zero and it does NOT register. Double-counting internal transfers is the single most error-prone mistake in returns math; here it is excluded structurally. A synthetic terminal flow values the position still held on the end date at market, realized through the booking engine (the same realization as report_cmd::account_balances, so lots keep cost and reductions match the account's booking method) and priced via the oracle. Prices arrive through a new `PriceOracle` trait rather than a concrete price database, so the crate stays a leaf (no dependency on the query engine that owns the price index) and the extraction logic is unit-tested against a hand-specified rate table -- no price-DB fixtures leaking the index's own behavior into extraction tests. The trait method mirrors the price database's `convert`, so the CLI consumer wires it as a pass-through. Extraction fails loud (ExtractError::MissingPrice) rather than dropping a flow it cannot state in the reporting currency: a silently omitted flow does not error, it just yields the wrong rate. 15 extraction tests cover the sign conventions, the internal-transfer and reinvested-dividend traps, multi-currency conversion, the horizon cutoff, terminal valuation (including broker cash and the fully-sold case), missing-price errors, and an end-to-end extract -> xirr sanity check. Deferred to follow-ups (per #1814): dividend/ex-dividend breakout, TWR, and the `rledger report returns` CLI surface + the real `impl PriceOracle for PriceDatabase`. * docs(returns): clarify income role is P&L (fees belong there, not External) The income/--income role is semantically profit-and-loss: it must capture investment expenses (broker fees, commissions) as well as dividends and gains. A fee left in the External role is treated as money the investor received on a sale -- gross instead of net proceeds -- overstating the return. Spell this out on AccountRole::Income and Scope, and lock it with a test: a sale for 1100 gross minus a 10 fee scoped as P&L yields a +1090 flow, not +1100. * docs(returns): specify the input contract; prove opening-balance coherence Deep review found the extraction's input contract was unspecified, and the pad interaction was the sharpest question. Nail both down: - Input contract (on extract_cash_flows + module docs): the stream must be BOOKED and PAD-EXPANDED (the loader's balance_view -- what report_cmd::account_balances already consumes). A leaf crate cannot book or pad-expand a raw stream: un-booked input lets the booking engine silently realize the wrong inventory, un-expanded input drops pad-seeded positions. This is the same precondition apply/account_balances carry. - From-inception semantics: an opening balance (a pad, or an Equity:Opening-Balances posting) is a GENUINE flow -- the capital already in the position at the start. Its Equity leg is External, so a -500 opening outflow pairs with the +500 that account contributes to terminal value: a 0% return on an untouched opening balance. Dropping that flow is the actual bug (a +500 terminal with no offsetting outlay). Two new tests pin this coherence (0% untouched; +10% with internal dividend growth). - External postings are valued by UNITS (the money that moved through the outside account). Corrected the module's double-entry claim, which holds over balance weights / plain postings, not raw units in general. An external leg carrying its own @price or {cost} is valued by units through the oracle, not its stated weight -- documented as a deliberate common-case limitation (external legs are plain cash). - Documented terminal_value uses market (position.units) not cost, handles net-short (negative units) coherently, and needs no price when a holding is already in the reporting currency. The None-external-amount skip is defensive under the booked-stream contract (unreachable, not a silent drop of a real flow); comment clarified. 34 tests. * fix(returns): longest-prefix classify, deterministic terminal (round-2 review) Round-2 deep review found a real classification bug plus determinism, panic-doc, and test-coverage gaps. Correctness: - classify() now picks the LONGEST matching prefix across both role lists (most-specific wins) instead of "investment always wins". An income account nested under an investment prefix (income Assets:Broker:Dividends under investment Assets:Broker) was classified Investment, so a reinvested dividend's income leg was summed into the terminal value and cancelled the asset it created -- understating the return to ~0%. Regression test added. - terminal_value now reports a held position even when its market value nets to exactly zero (returns None only when NOTHING is held), so the series distinguishes "still holding, net-flat" from "fully liquidated". Determinism / canonical discipline: - terminal_value collects inventories into a BTreeMap (like the canonical account_balances) before valuing, so which currency a MissingPrice names is stable -- an FxHashMap made it hash-order dependent and differ across 32/64- bit targets. Added cross-reference comments at both this loop and account_balances documenting the deliberate re-derivation + the future drift-guard test (the returns CLI PR). Docs: - # Panics on terminal_value / extract_cash_flows: an un-booked stream (a contract violation the leaf crate cannot detect) can make the booking engine debug_assert rather than return Err. - PriceOracle now requires conversion be linear in the amount (convert(-x) == -convert(x)), which is what makes a short position value negatively; the trait previously only mandated same-currency-unchanged. Cleanup: - extract_flows classifies each posting once (collect externals in one pass) instead of twice per transaction. Tests (40 total, +6): longest-prefix classification, nested-income terminal regression, net-short terminal, multi-position terminal sum, net-flat-held terminal, and a same-end-date flow+terminal fed through xirr (~50%). * fix(returns): don't emit a zero terminal flow (round-3 review regression) Round-3 review audited the round-2 changes and caught a regression they introduced. Round 2 made terminal_value emit Some(CashFlow{amount:0}) for a held-but- worthless portfolio, to distinguish "still holding, net-flat" from "fully liquidated". That is wrong: a zero-valued flow on a date LATER than the real flows is not neutral to xirr -- it defeats xirr's all-same-date degenerate guard. A same-date deposit/withdrawal wash plus a worthless residual holding then produced [-1000, +1000] (same date) + [0 @ end_date]; the later zero flow bypassed the guard, NPV was identically zero, and Newton returned its 0.10 seed -- a fabricated +10% return for a genuinely-undefined series. Revert to: a terminal flow is emitted only when the held market value is nonzero (None otherwise, covering both empty and net-flat/worthless portfolios). Added a regression test asserting xirr returns None for the wash scenario, and corrected the round-2 net-flat test to expect None. Also reverted round-2's single-pass extract_flows rewrite. It allocated a Vec per transaction -- including the common irrelevant ones -- to save a re-classify on the few relevant transactions. The original allocation-free two-pass (relevance gate short-circuits, so an irrelevant transaction costs only the scan) is better for the common path; the double-classify it re-introduces touches only the minority of portfolio transactions. Note: the underlying xirr behavior -- returning its seed when NPV is identically zero across >=2 distinct dates (reachable only by pathological multi-date wash series) -- is a pre-existing engine edge, tracked separately for a small xirr hardening follow-up. This PR removes the extraction-side trigger. 41 tests.
* feat(returns): rledger report returns (money-weighted / XIRR) Wires the rustledger-returns engine (#1815 xirr, #1816 extraction) into a first-class CLI report, the consumer phase-1 piece of #1814. rledger report returns --investments <prefix> [--income <prefix>] [--currency USD] [--end YYYY-MM-DD] - Report::Returns clap variant + report_cmd/returns.rs. --investments (repeatable, required) and --income (repeatable) define the portfolio boundary; --currency defaults to the ledger's first operating_currency; --end defaults to today. Added Report::Returns to the needs_balance_view gate so extraction receives the booked, pad-expanded stream its contract requires. - impl PriceOracle for PriceDatabase via a PriceDbOracle newtype in the CLI (the composition root). The convert signatures are identical, so it is a pass-through; this keeps rustledger-returns a leaf and rustledger-query free of a returns dependency, rather than putting the impl in query. - Reports the money-weighted return plus supporting figures (capital invested, distributions received, current market value, flow count) in text / json / csv. An undefined series (no sign change) reports n/a, not a fabricated rate. - Drift-guard unit test (owed from #1816 round 2, CLAUDE.md Canonical- Function Discipline): terminal_value's realization must equal the market valuation of report_cmd::account_balances' inventories for the same scope and date. Plus 5 integration tests: the boundary model (a dividend-to-bank is a flow only when --income scopes it: 32.36% vs 30.00%), currency default, json fields, and the missing-currency error. Scope: XIRR (money-weighted) only, whole-scope. Time-weighted return and per-commodity grouping remain follow-ups per #1814. * fix(returns): pin series to extract_cash_flows; unify rate; fix -0.00% (review) Deep review of the returns CLI found two defects plus surfaced an output bug and a coverage gap. - Canonical-Function Discipline: report_returns hand-combines extract_flows + terminal_value into the xirr series (it needs the parts for the summary breakdown), duplicating the engine's canonical extract_cash_flows. Pinned the two as equivalent with a drift-guard test (series_matches_extract_cash_flows) and a cross-reference comment, so an engine change to how the series is assembled can't silently drift the CLI's rate. - Per-format precision: the money-weighted return was 2 decimals for text/csv but 4 for JSON, so the same ledger reported different rates across formats. Unified to 2 decimals everywhere. - Negative-zero display: a 0% return (capital returned unchanged) converges to a tiny signed epsilon that rendered as "-0.00%". Normalized so a rate rounding to zero shows "0.00%" in every format. - Coverage: added an integration test valuing a pad+balance-seeded holding, proving the needs_balance_view wiring (Report::Returns must be in that gate or the pad-expanded stream never reaches extraction and the position vanishes). The prior fixtures used only explicit buys. 8 returns tests (2 unit drift-guards + 6 integration). * test(returns): assert the reporting-currency line, not a bare contains Copilot review: the currency-default test used out.contains("USD"), which passes on the fixtures other USD literals even if the default were wrong. Assert the Reporting currency lines value is USD instead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
What
The first slice of investment-returns reporting (#1814): a new
rustledger-returnsleaf crate holding the money-weighted return (XIRR) math.Per the plan in #1814, the returns math is a pure engine crate so every eventual consumer (CLI
report returns, BQL, the FFI component, rustfava) reuses one implementation rather than re-deriving it — canonical-function discipline. This PR is deliberately just the numeric core: no ledger loading, no price DB, no I/O.CashFlow { date, amount }with an investor-centric sign convention (money put in = negative; sale proceeds, dividends, and the terminal market value of the held position = positive).xirr(&[CashFlow]) -> Option<f64>— annualized IRR over an irregularly-spaced series via Newton's method with a bisection fallback; actual/365 day count (matching spreadsheetXIRRand beangrow). ReturnsNonewhen there's no sign change, fewer than two flows, or a non-finite result.Why this scope
XIRR is the novel, self-contained, provably-correct-in-isolation part — the right thing to land and de-risk first. The follow-ups build on it:
PriceDatabasegets relocated intorustledger-core.rledger report returns --investments <pattern>, then the BQL/FFI surfaces.Tests
cargo test -p rustledger-returns(7, all pass):Nonefor no-sign-change, <2 flows, and a zero-flow-doesn't-count case.Clippy/doc/fmt clean. Crate registered in the workspace members/default-members and the crates.io publish
CRATESlist (sync check passes).Part of #1814.
🤖 Generated with Claude Code
https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU