Skip to content

feat(returns): rledger report returns (money-weighted / XIRR) - #1818

Merged
robcohen merged 3 commits into
mainfrom
feat/returns-report-cli
Jul 20, 2026
Merged

robcohen merged 3 commits into
mainfrom
feat/returns-report-cli

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

The consumer that makes investment returns reachable from the command line — phase 1's user-facing piece of #1814, built on the merged XIRR engine (#1815) and cash-flow extraction (#1816):

rledger report returns --investments Assets:Investments [--income Income:Dividends] \
                       [--currency USD] [--end 2020-12-31]

How it wires together

  • 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 option; --end defaults to today. Report::Returns is added to the needs_balance_view gate so extraction receives the booked, pad-expanded stream its input contract requires.
  • impl PriceOracle for PriceDatabase via a PriceDbOracle newtype in the CLI (the composition root). The convert signatures are byte-identical, so it's a pass-through. This keeps rustledger-returns a leaf and rustledger-query free of a returns dependency, rather than putting the impl in query and pulling returns into every BQL build.
  • 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, never a fabricated rate.

The boundary model, visible in the tests

The --income scope decides whether a dividend-to-bank counts. On the same ledger (buy 10 AAPL for 1000, a 20 dividend to the bank, hold to a 130 close):

invocation flows money-weighted return
--investments Assets:Broker --income Income:Dividends −1000, +20, +1300 32.36%
--investments Assets:Broker (no --income) −1000, +1300 30.00%

Without --income, the dividend transaction touches no investment account, so it isn't a flow — the boundary model, working as designed.

Tests

  • Drift-guard unit test (owed from feat(returns): cash-flow extraction from a booked ledger #1816 round 2, per CLAUDE.md Canonical-Function Discipline): terminal_value's realization must equal the market valuation of report_cmd::account_balances' inventories for the same scope/date. The two deliberately re-derive the same realization loop across a crate boundary; this pins their agreement.
  • 5 integration tests: the boundary model (both rows above), the reporting-currency default, the json fields, and the missing-currency error path.

Scope

XIRR (money-weighted) only, whole-scope. Time-weighted return and per-commodity grouping remain follow-ups per #1814 (TWR isn't in the engine yet). No new publishable crate (returns landed in #1815).

Part of #1814.

🤖 Generated with Claude Code

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

github-actions Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.3ms ± 0.5ms 23.8 MB
beancount 757.1ms ± 6.5ms 50.7 MB
Comparison 22.1x faster 2.1x less

vs main branch (2026-07-20)

Metric main this PR Change
Time 31.6ms 34.3ms +8.5% 🟡
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

❌ Patch coverage is 89.52880% with 20 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/report_cmd/returns.rs 88.50% 20 Missing ⚠️

📢 Thoughts on this report? Let us know!

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 a new CLI report (rledger report returns) that wires the existing rustledger-returns XIRR engine into the rustledger binary, including text/json/csv output and end-to-end tests. This sits in the rustledger (CLI) crate as the consumer/composition root, keeping rustledger-returns as a leaf by adapting the query crate’s PriceDatabase behind the PriceOracle trait.

Changes:

  • Introduces Report::Returns clap variant and dispatcher plumbing to ensure the report receives the booked, pad-expanded directive stream (balance_input).
  • Implements the new report in report_cmd/returns.rs, including PriceDbOracle adapter, currency defaulting, flow extraction, terminal valuation, and output rendering (text/json/csv).
  • Adds integration tests covering the boundary model (--income), JSON fields, default reporting currency behavior, and missing-currency error path; updates Cargo dependencies to include rustledger-returns.

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/tests/report_returns_test.rs New end-to-end tests for rledger report returns behavior and error paths.
crates/rustledger/src/cmd/report_cmd/returns.rs New returns report implementation + PriceDbOracle adapter + drift-guard unit test.
crates/rustledger/src/cmd/report_cmd/mod.rs Registers the report module/variant, routes balance_input, and plumbs operating_currency into rendering.
crates/rustledger/Cargo.toml Adds rustledger-returns dependency to the CLI crate.
Cargo.toml Adds workspace dependency entry for rustledger-returns.
Cargo.lock Records the new dependency in the lockfile.

💡 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

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

Copy link
Copy Markdown
Member Author

Deep review — round 1

Workflow-backed review (4 finder angles + adversarial verify) on the CLI consumer. Two confirmed findings, one refuted; it also cleared the JSON-NaN worry I flagged (the engine's xirr only returns Some for finite values, so the unquoted money_weighted_return_pct can never be a bare NaN/Infinity). All addressed in a32eddbe.

Canonical-Function Discipline (CONFIRMED)

report_returns hand-combines extract_flows + terminal_value into the xirr series — duplicating the engine's canonical extract_cash_flows. I build it from the parts deliberately (the summary needs invested/distributions/current_value separately, and calling extract_cash_flows too would re-realize inventory a second time), but nothing pinned the equivalence. Fixed: a drift-guard test series_matches_extract_cash_flows asserts the manual combine equals extract_cash_flows on the same input, plus a cross-reference comment. Per CLAUDE.md rule 3.

Per-format rate precision (CONFIRMED)

The money-weighted return was formatted at 2 decimals for text/csv but 4 for JSON — the same ledger reported different rates across formats. Fixed: unified to 2 decimals everywhere (JSON emits the bare 2dp number).

Surfaced while adding coverage

  • -0.00%: the new pad test exposed that a 0% return (capital returned unchanged) converges to a tiny signed epsilon rendering as -0.00%. Fixed in rate_pct (a rate rounding to zero now shows 0.00% in every format) — a real output-quality bug, not just a test tweak.
  • Pad coverage: my fixtures used only explicit buys, so nothing proved the needs_balance_view addition (the whole reason Report::Returns is in that gate). Added pad_seeded_holding_is_valued — a pad+balance-seeded position valued end-to-end (invested 500, current value 500, 0%), which fails if the pad-expanded stream doesn't reach extraction.

Refuted (agreed)

Money fields not json_escaped in the JSON branch — correct to refute: format_amount_number emits only digits/commas/dots/minus (no "/\/control chars), and holdings.rs's JSON doesn't escape them either.

8 returns tests (2 unit drift-guards + 6 integration); clippy/doc/fmt clean.

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

Copy link
Copy Markdown
Member Author

Good catch on the vacuous contains("USD") — fixed in b3ad683: the currency-default test now asserts the Reporting currency line's value is USD (via the field extractor), so it can't pass on the fixture's other USD literals if the default were wrong. Resolving.

@robcohen
robcohen merged commit 16e13e7 into main Jul 20, 2026
46 checks passed
@robcohen
robcohen deleted the feat/returns-report-cli branch July 20, 2026 16:06
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