Skip to content

feat(returns): cash-flow extraction from a booked ledger - #1816

Merged
robcohen merged 5 commits into
mainfrom
feat/returns-cashflow-extraction
Jul 20, 2026
Merged

robcohen merged 5 commits into
mainfrom
feat/returns-cashflow-extraction

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

Phase 1, part 2 of investment returns reporting (#1814), building directly on the XIRR engine merged in #1815. This adds cash-flow extraction: the layer that turns a booked ledger into the CashFlow series xirr consumes.

The model — boundary crossing

Every account is classified by a Scope into one of three roles:

Role What it is Contributes a flow?
Investment holdings + settlement cash No — value tracked inside the portfolio
Income dividends / gains / fees generated by the investment No — internal to the return
External bank, outside cash Yes — money crossing 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:

cashflow_t = Σ { external postings }  =  −Σ { investment + income postings }   (equal, by double-entry)

Summing the external side directly makes the sign land investor-centric with no manual negation.

Three correctness properties fall out of the model, not special cases

  • Purchase (Assets:Bank -1000 USD) → −1000 (outflow) ✓
  • Sale / dividend-to-bank (Assets:Bank +500 USD) → +500 (inflow) ✓
  • Internal transfer — shares/cash moved between two in-scope accounts — has no external posting, so its flow is 0 and it does not register. Double-counting internal transfers is the single most error-prone mistake in returns math (flagged as the trap in feat: investment returns reporting (rledger report returns — XIRR + TWR) #1814); 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 each account's booking method) and priced via the oracle.

PriceOracle — keeping the crate a leaf

Prices arrive through a new PriceOracle trait, not a concrete price database. This:

  • keeps rustledger-returns a leaf (no dependency on rustledger-query, which owns the price index);
  • makes the correctness core unit-testable against a hand-specified rate table — no price-DB fixtures leaking the index's own behavior into extraction tests;
  • is a pass-through to wire up: the trait method mirrors PriceDatabase::convert, so the CLI consumer implements it in one line.

The full core-relocation of PriceDatabase that #1814 sketches can still happen on its own merits; the trait means extraction doesn't have to wait on it.

Fails loud

extract returns ExtractError::MissingPrice rather than dropping a flow it can't state in the reporting currency — a silently omitted flow doesn't error, it just yields the wrong rate.

Tests (15 extraction + 16 existing xirr = 31)

Sign conventions; the internal-transfer and reinvested-dividend traps; multi-currency conversion; the horizon cutoff; terminal valuation (held position, broker cash, fully-sold → None); missing-price errors on both flow and terminal paths; segment-aware classification; and an end-to-end extract_cash_flows → xirr sanity check (~10%).

Deferred to follow-ups (per #1814)

  • Dividend / ex-dividend breakout (total vs. ex-income return)
  • Time-weighted return (built on the same realization primitive as terminal_value)
  • The rledger report returns --investments <pattern> CLI surface + the real impl PriceOracle for PriceDatabase (integration-tested there, where both crates are in scope)

Part of #1814.

🤖 Generated with Claude Code

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`.
@robcohen
robcohen requested a review from a team as a code owner July 20, 2026 12:26
Copilot AI review requested due to automatic review settings July 20, 2026 12:26
@github-actions

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35ms ± 0.4ms 23.8 MB
beancount 763.2ms ± 16.4ms 50.7 MB
Comparison 21.8x faster 2.1x less

vs main branch (2026-07-20)

Metric main this PR Change
Time 31.6ms 35ms +10.8% 🔴
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@codecov

codecov Bot commented Jul 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…ernal)

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.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds the cash-flow extraction layer to rustledger-returns, turning a booked ledger into a single-currency CashFlow series suitable for the existing xirr engine, while keeping price conversion abstract via a PriceOracle trait (so the crate remains a leaf).

Changes:

  • Introduces extract_cash_flows/extract_flows and terminal_value to compute boundary-crossing flows plus a terminal market valuation at end_date.
  • Adds Scope/AccountRole classification and PriceOracle for caller-supplied currency/price conversion, with explicit MissingPrice failure.
  • Updates crate docs/README and adds dependencies needed for extraction (booking + thiserror).

Reviewed changes

Copilot reviewed 4 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
crates/rustledger-returns/src/lib.rs Wires the new extraction module and re-exports the public extraction API alongside xirr.
crates/rustledger-returns/src/extract.rs Implements boundary-based flow extraction, terminal valuation via the booking engine, and unit tests for key correctness traps.
crates/rustledger-returns/README.md Updates crate description/status to include extraction + terminal valuation and the PriceOracle design.
crates/rustledger-returns/Cargo.toml Adds rustledger-booking and thiserror dependencies required by extraction.
Cargo.lock Locks new dependency edges introduced by the crate changes.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 811
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

…rence

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.
@robcohen

Copy link
Copy Markdown
Member Author

Deep review — round 1

Ran the workflow-backed review (4 finder angles, adversarial verify pass, high effort) against the branch diff. It surfaced 7 verified findings (3 more were correctly refuted). Dispositions below.

The headline finding — and why its framing inverts the correctness

The finders flagged that terminal_value ignores Pad/Balance directives, and that "no single input stream is correct for both extract_flows and terminal_value" because a pad's Equity:Opening-Balances leg would inject a "spurious" cash flow. I worked through it and the opposite holds:

With the booked, pad-expanded stream (Ledger::balance_view — exactly what the canonical report_cmd::account_balances is fed), both halves are coherent. A pad seeding Assets:Broker:Cash 500 / Equity:Opening-Balances -500 produces a -500 opening flow (capital in) that pairs with the +500 that account contributes to the terminal value. xirr([-500, +500]) -> ~0%, which is correct for an untouched opening balance. Dropping that flow is the actual bug: a +500 terminal with no offsetting outlay is an undefined return.

So the opening flow is not spurious — it is required. The real defect the finders correctly exposed is that my input contract was unspecified (I never stated "pass balance_view") and I had no test proving pad coherence.

Fixed (419ca1cc): a precise # Input contract on extract_cash_flows + module docs (booked + pad-expanded; from-inception semantics; opening balances are genuine capital flows), and two tests pinning the coherence — opening_balance_pairs_with_terminal_to_a_zero_return (0%) and opening_balance_then_internal_growth_is_a_positive_return (+10% via an internal dividend). This is the same booked-input precondition apply/account_balances already carry.

Units vs. balance-weight (CONFIRMED — doc corrected)

External postings are summed by units (the money that actually moved through the outside account). The module's double-entry identity was stated over units; it holds over balance weights / plain postings, not raw units in general. Corrected the claim, and documented the deliberate limitation: an external leg carrying its own @price or {cost} (an in-kind transfer, or a cash leg with an explicit rate) is valued by units through the oracle, not its stated weight. Common-case external legs are plain cash; honoring per-posting weights is a noted follow-up.

None-amount external posting (PLAUSIBLE — clarified)

The defensive continue on an external posting with no resolved amount is unreachable under the booked-stream contract (interpolation fills every posting), so it is not a silent drop of a real flow. Comment clarified to say so and tie it to the contract.

Declined / deferred, with reasons

  • Decimal += overflow panic (PLAUSIBLE) — declined. The overflow ceiling is ~7.9e28; a monetary sum reaching it exceeds world GDP by ~14 orders of magnitude, and checked_add on every += would diverge from how the rest of the codebase (booking, inventory) does Decimal arithmetic. Not worth an error variant for an unreachable case.
  • Double directive pass / re-book (CONFIRMED, perf) — deferred. Not a correctness issue; extract_flows iterates once and terminal_value rebuilds the engine once, called once per report. Optimizing before the consumer exists is premature; a future refactor can have terminal_value accept a pre-realized inventory (also lets the caller own pad expansion).

Refuted (agreed)

Three findings claimed the !net.is_zero() guard drops legitimate zero-netting flows. Correctly refuted: a zero-valued flow is neutral to xirr (contributes 0 to NPV at every rate and is not a sign change), so dropping it is harmless.

34 tests; clippy/doc/fmt clean.

…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%).
@robcohen

Copy link
Copy Markdown
Member Author

Deep review — round 2

Second workflow-backed pass (4 finder angles + adversarial verify), pointed at the post-round-1 state with deeper angles (real BookingEngine lot semantics, mixed-currency positions, classify precedence under nested trees, short terminals, same-date flows vs xirr, determinism, vacuous-test check). 9 verified findings, 3 refuted. All addressed in e195f799.

Real correctness bug — overlapping-prefix classification (CONFIRMED)

classify() used "investment always wins" on an account matching both role lists. With income scoped under an investment prefix (income Assets:Broker:Dividends, investment Assets:Broker), a reinvested dividend's income leg was classified Investment and summed into the terminal value, cancelling the asset it created — understating the return toward ~0%.

Fixed: classify() now takes the role of the longest (most-specific) matching prefix across both lists, so nesting resolves either direction correctly (Investment breaks an exact-length tie). Added a classification test and an end-to-end nested-income terminal regression test.

Net-flat held portfolio reported as None (CONFIRMED)

terminal_value returned None when a held portfolio's market value netted to exactly zero, indistinguishable from fully-liquidated. Fixed: a held position is always reported (keyed off held); None only when nothing is held. Test added (offsetting AAPL/GOOG positions → Some(0)).

Determinism + canonical drift (CONFIRMED / PLAUSIBLE)

terminal_value iterated into_inventories() (an FxHashMap), so which currency a MissingPrice named was hash-order dependent and differed 32/64-bit. Fixed: collect into a BTreeMap like the canonical account_balances. Added cross-reference comments at both this loop and account_balances documenting the deliberate re-derivation (a leaf crate can't call the CLI-side helper) and flagging the drift-guard parity test for the returns CLI PR.

Docs (CONFIRMED)

  • # Panics added to terminal_value / extract_cash_flows: an un-booked stream (a contract violation the leaf can't 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)) — the property that makes a short position value negatively. (This grounds a finding the verifier had refuted as unstated-contract; I tightened the contract rather than leave the reliance implicit.)

Test gaps (CONFIRMED) + cleanup

Added the three missing coverage cases the finders flagged as vacuously-passable: net-short terminal (−1500), multi-position terminal sum (AAPL+GOOG → 2500), and a same-end-date flow+terminal fed through xirr (~50%). Also: extract_flows now classifies each posting once (single pass) instead of twice per transaction.

Refuted (agreed)

Two duplicate FxHashMap-nondeterminism entries (kept one), and the PriceOracle sign-linearity concern — which I nonetheless closed by tightening the trait doc.

40 tests (+6); clippy/doc/fmt clean; CLI crate builds with the cross-reference comment.

…ion)

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.
@robcohen

Copy link
Copy Markdown
Member Author

Deep review — round 3

Third pass, split between auditing the round-2 changes for regressions and new angles. It found one live bug — a regression round 2 introduced — plus the already-documented deferred drift-guard. Two findings refuted (both of which I'd reasoned through). The round-2 changes it audited (longest-prefix classify, BTreeMap determinism, currency comparison, date arithmetic, docs) all held up.

Regression: zero-valued terminal flow fabricates a return (CONFIRMED)

Round-2 finding-2 asked terminal_value to emit a flow even when the held value is zero (to distinguish "net-flat holding" from "liquidated"). I took it — and it was wrong. A zero-valued terminal on a date later than the real flows is not neutral to xirr: it defeats xirr's all-same-date degenerate guard. Concrete failure the finder gave: a same-date deposit/withdrawal wash (-1000/+1000 on one date) plus a worthless residual holding yields [-1000, +1000] (same date) + [0 @ end_date]; the later zero flow bypasses the guard, NPV is identically zero, and Newton returns its 0.10 seed → a fabricated +10% return for a genuinely-undefined series.

Fixed (cce68559): reverted to emitting a terminal flow only when the held market value is nonzero (None otherwise — covering empty and net-flat/worthless portfolios). Added a regression test asserting xirr returns None for the wash, and corrected the round-2 net-flat test to expect None. The informational "net-flat vs liquidated" distinction round 2 wanted must not be smuggled through a zero cash flow; if a consumer ever needs it, it belongs in a richer report API.

I also reverted round-2's single-pass extract_flows rewrite. It allocated a Vec per every transaction — including the common irrelevant ones — to save a re-classify on only the few relevant ones. The original allocation-free two-pass (the relevance gate short-circuits, so an irrelevant transaction costs only the scan) is better for the common path; this also moots the refuted-but-real allocation concern.

Deferred (PLAUSIBLE): canonical drift-guard test

terminal_value re-derives account_balances' realization loop. I've documented the divergence at both sites (round 2); the parity drift-guard test genuinely needs the CLI crate (account_balances is CLI-side), so it lands with the rledger report returns consumer PR. Deferral stands.

Follow-up noted (out of scope): xirr degenerate edge

The underlying xirr behavior — returning its Newton seed when NPV is identically zero across ≥2 distinct dates (reachable only by a pathological multi-date wash series) — is a pre-existing edge in the merged engine, not introduced here. This PR removes the extraction-side trigger; I'll file a small xirr-hardening follow-up (evaluate NPV at a second rate to detect a flat-zero function) rather than expand this PR into the merged solver.

Refuted (agreed)

The single-pass None-skip (unreachable under the booked contract) and the Vec-vs-SmallVec allocation (moot after the revert above).

41 tests (+1 net regression test); clippy/doc/fmt clean.

@robcohen

Copy link
Copy Markdown
Member Author

Re: Copilot inline review

Thanks — all three checked against the current head (cce68559); Copilot reviewed an earlier commit, and the manual review rounds already cover these:

  1. sort_by_key "unstable" (extract.rs:263) — slice::sort_by_key is a stable sort in Rust (sort_unstable_by_key is the unstable variant). Same-date flows therefore keep insertion order (real flows before the terminal), so the series is deterministic as documented. Independently, xirr is order-independent within a date, so ordering can't affect the result either way.

  2. "single positive terminal cash flow" (extract.rs:271) — already corrected (round 2): the docs now say "a single terminal cash flow" and explicitly document that a net-short position values negatively. The only remaining "positive terminal" text is a comment on one test describing that specific positive case.

  3. amount() == None silently skipped (extract.rs:250) — documented as unreachable under the input contract: extraction requires the booked, pad-expanded stream (interpolation fills every posting's units), the same precondition BookingEngine::apply and account_balances carry. The skip is defense-in-depth, not a silent drop of a real flow; the contract is spelled out on extract_cash_flows and in the module docs.

Resolving these threads.

@robcohen
robcohen merged commit eeb988f into main Jul 20, 2026
46 checks passed
@robcohen
robcohen deleted the feat/returns-cashflow-extraction branch July 20, 2026 14:17
robcohen added a commit that referenced this pull request Jul 20, 2026
* 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]>
robcohen added a commit that referenced this pull request Jul 21, 2026
#1840)

Closes #1817. A cash-flow series whose flows net to zero on EVERY date has
NPV(r) = Σ Sₜ/(1+r)ᵗ with every date-net Sₜ = 0 — i.e. NPV is identically
zero at every rate, so the IRR is undefined. With ≥2 distinct dates (two
same-day washes on different days) this slips past both the sign-change guard
(the canceling flows are +/-) and the all-same-date guard, and Newton's
iteration-0 `|NPV| < tol` check then succeeds at the 0.10 seed — so xirr
fabricated a +10% return for an undefined series.

Detect it exactly: group flows by date and, if every date's net is zero
(checked in Decimal — the (1+r)⁻ᵗ for distinct t are linearly independent, so
identically-zero NPV ⟺ every Sₜ = 0), return None. This complements the
existing all-same-date guard (which catches the nonzero-constant NPV case).

Tests: the two-date wash now returns None (was 0.10); and a guard against
over-firing — a series whose UNDISCOUNTED total is zero but whose dates differ
(-1000 then +1000 a year later) is a genuine 0% return and is still solved.

Found in the #1816 round-3 review; the extraction side already avoids emitting
the trigger, this closes the underlying engine edge.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants