Repository navigation
feat(report): realized IRR for capgains (--irr) - #1861
Conversation
Add the annualized money-weighted return of each closed tax lot, plus a pooled rate per term and per currency, behind an opt-in `--irr` flag. Each closed lot is a round trip — `-cost_basis` at acquisition, `+proceeds` at sale — so it has a well-defined IRR. The summary rates pool every eligible lot's flows into one series and solve once (a money-weighted return over all the capital that actually cycled through), rather than averaging per-lot rates. Solved with the canonical `rustledger_returns::xirr` (365-day basis, beangrow-compatible); no IRR solver is re-derived here. The text column reuses `returns`' `fmt_rate_pct` so the two rate columns cannot drift in formatting. This is a REALIZED-ONLY return: it sees only lots you actually closed, so it is not the portfolio's total return. `report returns` remains the beangrow-shaped total-return report (money- and time-weighted, including still-held positions valued at market); this adds the per-lot view `returns` cannot give. The docs state the distinction and cross-reference both ways. `n/a` (and excluded from the pooled rates) when the rate is undefined: short sales (money-in-then-out is unconventional and misleading), lots with no acquisition date (AVERAGE booking merges lots and drops dates), same-day round trips (a zero-day span cannot be annualized), and a non-positive cost basis. Opt-in keeps the default a lean tax report and leaves the CSV/JSON schema unchanged unless `--irr` is passed. Machine output carries the raw fraction (`0.1`, empty/`null` when undefined); percent formatting is text-only, matching the existing exact-machine-output policy. Verified against an independent bisection XIRR: per-lot and pooled rates agree to 6 decimals (a 1-year 1000->1100 and a 2-year 500->605 both annualize to 10.000000%). Tests cover annualization/compounding, the opt-in default, and every undefined case, at both the unit and end-to-end CLI level. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-07-24)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Adds an opt-in realized IRR (XIRR) calculation to the report capgains CLI report, computing annualized money-weighted return per closed lot and pooled per-term/per-currency aggregates, while keeping default output schemas unchanged.
Changes:
- Adds
--irrflag toreport capgainsand threads it through report rendering. - Computes per-lot IRR flows (when defined) and pooled aggregate IRRs using the canonical
rustledger_returns::xirr, with consistent text formatting shared fromreport returns. - Updates docs/README and adds CLI + unit tests covering opt-in schema changes and undefined cases.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| README.md | Mentions optional per-lot annualized return (--irr) in the feature list. |
| docs/commands/report.md | Documents --irr, includes example output, and explains realized-only semantics + undefined cases. |
| crates/rustledger/tests/report_capgains_test.rs | Adds end-to-end CLI tests for CSV/JSON/text output with and without --irr, plus undefined-case fixtures. |
| crates/rustledger/src/cmd/report_cmd/returns.rs | Exposes fmt_rate_pct for reuse to keep rate-column formatting consistent across reports. |
| crates/rustledger/src/cmd/report_cmd/mod.rs | Adds the --irr flag to the Capgains subcommand and passes it into the renderer. |
| crates/rustledger/src/cmd/report_cmd/capgains.rs | Implements per-lot IRR + pooled aggregate IRR computation and conditionally extends CSV/JSON/text output when --irr is enabled. |
Comments suppressed due to low confidence (3)
crates/rustledger/tests/report_capgains_test.rs:433
- The JSON schema assertion is also fragile as a plain substring search. Parse the JSON and assert the
irr/total_irrfields are absent; this avoids false failures if a string value containsirr.
let json = run(&bin, &["report", path, "capgains", "--format", "json"]);
assert!(!json.contains("irr"), "no irr field by default: {json}");
crates/rustledger/tests/report_capgains_test.rs:421
- These JSON assertions use exact equality against
0.1, which can be flaky for computedf64values. Convert tof64and compare within a tolerance instead.
assert_eq!(v["disposals"][0]["irr"], 0.1);
assert_eq!(v["total_irr"][0]["currency"], "USD");
assert_eq!(v["total_irr"][0]["irr"], 0.1);
crates/rustledger/tests/report_capgains_test.rs:474
- Same fragility as the short-sale check above: prefer asserting the last CSV field is empty rather than depending on a trailing comma.
assert!(
avg.lines().nth(1).is_some_and(|l| l.ends_with(',')),
"dateless lot has an empty irr cell: {avg}"
);
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
…e, units, clamping
Deep correctness + architecture review of the --irr feature. Fixes:
- POOLING CONSISTENCY (the real bug): a total-loss lot rendered `n/a` per-lot but
its outflow was still pooled into every aggregate, contradicting the docs and
`lot_flows`' own contract, and breaking the monotone-NPV property that keeps the
pooled solve single-rooted. A total loss is now the exact -100% pole (you cannot
lose more than the basis, at any horizon) returned directly by the new `lot_irr`,
so the per-lot cell and the pooled rate agree on which lots count. It stays in
the pool deliberately: dropping it would flatter every aggregate by hiding
capital that never came back. Negative proceeds are now excluded (outside a
round trip's domain).
- COVERAGE DENOMINATOR: summary lines printed a rate solved over only the eligible
lots beside counts/proceeds/gain covering ALL of them — a day-trading ledger
could show a big loss next to a positive IRR. `aggregate_irr` now returns
`PooledIrr { rate, eligible, total }` and renders `10.00% (1 of 3 lots)` whenever
those differ; JSON carries `irr_lots` / `irr_lots_total`.
- UNIT MISMATCH: machine output emitted a raw fraction (0.1) while the sibling
`returns` report emits a 2-decimal percent — a 100x scripting trap. capgains now
shares returns' `fmt_rate`/`json_rate` and names the field `irr_pct`, matching
`money_weighted_return_pct`.
- COLUMN OVERFLOW: an annualized rate is unbounded (a one-day 20% gain compounds to
~8e30 %/yr), which overflowed the fixed cell and merged into the Gain column,
destroying the table. The text cell now clamps to `>9999%` / `<-9999%`; CSV/JSON
keep the exact value.
- Unknown-term buckets no longer print a structurally-always-`n/a` IRR.
- Per-lot rates are solved AFTER the filters, so only printed rows cost a solve.
Tests (the weakest area the review found):
- Every IRR fixture used 10%, which is EXACTLY xirr's Newton seed accepted at
iteration 0 — the assertions could not distinguish a working solver from one
returning its seed. Fixtures now use 25% and 20% (distinct per lot, neither the
seed), with the pooled 21.67% independently computed by bisection.
- Replaced `ends_with(',')` proxy assertions with exact full-row / field-count
assertions.
- Added hermetic in-process render tests for every --irr output path (CSV, JSON,
text), which previously existed only in binary-gated integration tests that
silently skip.
- Added a total-loss regression test pinning -100% and its pooling.
Docs: percent unit + `irr_pct`, coverage annotation, total-loss behavior, the
display clamp, and the `--year`/`--end` windowing semantics (the rate covers round
trips that CLOSED in the window, using their full flow span).
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
…entable machine output
Third review round (deep correctness + architecture). Both passes converged on the
same headline defect, plus a machine-output bug:
- ONE PREDICATE FOR POOLING. `aggregate_irr` decided coverage from `lot_flows`
(can flows be built?) while the per-lot cell showed `lot_irr` (did a rate solve?).
A lot whose rate does not converge — e.g. a 1-day 4x round trip, whose annualized
root is ~1e219, past the solver's bracket — printed `n/a` yet still drove the
pooled rate AND was counted as covered, so no `(1 of 2 lots)` caveat appeared.
That contradicted the documented promise that `n/a` lots are excluded. Pooling now
keys off the solved rate, so the cell and the aggregate share one predicate.
(Verified: the reviewer's repro now prints `IRR 25.00% (1 of 2 lots)`, was 72.14%.)
- A bucket whose lots are ALL total losses pooled to a series with no inflow, which
`xirr` cannot bracket, so it printed `n/a` beside rows reading `-100.00%`. Both
paths now share `solve_irr`, so a bucket of one lot reports that lot's rate.
- MACHINE OUTPUT WAS UNREADABLE at extremes: an unclamped `{:.2}` percent for a
short hold is ~31 significant digits — more than `rust_decimal` (this project's
own type, ~28-29) can parse back. Rates above 9999% are now `>9999%` in text and
empty/`null` in CSV/JSON: no fabricated precision, nothing a consumer cannot read.
The negative clamp branch was unreachable (a round trip cannot lose more than its
basis) and is gone.
- Fixed a stale CSV comment that still claimed a raw fraction, and replaced the last
`ends_with(',')` proxy assertion with an exact field-index check.
Deliberately NOT changed, with the reasoning recorded in code: the total-loss pole
stays in capgains rather than moving into the canonical `xirr`. Moving it was tried
and reverted — `xirr` returning `None` for a no-sign-change series is CORRECT for its
other caller, where an all-negative series means "bought and still holding", not a
loss; reporting -100% there would be flatly wrong. Only capgains knows its series is
a closed round trip, so the special case belongs to the caller. (rustledger-returns
pins that contract in `no_sign_change_is_none`; the code comment says to revisit if
it ever changes.)
Tests: added coverage for the reporting cap (text vs machine), and for the
all-total-loss bucket agreeing with its rows.
Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
… schema assertions, fix stale docs - aggregate_irr no longer re-solves every lot on each of the four summary cells per currency: it keys eligibility off the already-solved `d.irr`. Beyond removing the redundant Newton/Brent runs, this makes the aggregate use the LITERAL value shown in each cell, so a summary rate cannot disagree with the rows above it. Documented the fill-before-render precondition. - Tests: the "no IRR by default" assertions matched a substring of the whole output, so a commodity or payee containing `irr` could flip them. They now assert on the schema itself — the CSV header (and its column count), the JSON keys, and the text table header. - Docs: a stale paragraph survived the previous edit and still claimed CSV/JSON carry "the exact value" and mentioned a `<-9999%` clamp. Machine output is a 2-decimal percent, extreme rates are omitted entirely (empty/null), and there is no lower clamp because a round trip cannot lose more than its basis. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
|
Addressed the Copilot review (commit Fixed now:
Already fixed in earlier commits on this branch (these comments are against superseded revisions):
|
Realized IRR for
report capgainsAdds
--irr: the annualized money-weighted return of each closed tax lot,plus a pooled rate per term and per currency.
Both lots read 10% although the second gained 21% in total — the rate is
annualized, so 1.21× over two years compounds to 10%/year. That is the thing the
raw gain column cannot tell you.
Design
-cost_basisat acquisition,+proceedsat sale), so it has a well-defined IRR.and solve once — a money-weighted return over all the capital that actually
cycled through — rather than averaging per-lot rates.
rustledger_returns::xirr(365-day basis,beangrow-compatible). No IRR solver is re-derived. The text column reuses
returns'fmt_rate_pctso the two rate columns cannot drift in formatting.unchanged unless
--irris passed. Machine output is a 2-decimal percent inan
irr_pctfield (empty /nullwhen undefined) — the same unit asreport returns'money_weighted_return_pct, so the two reports' rates are directlycomparable rather than 100x apart. JSON summaries also carry
irr_lots/irr_lots_total, the rate's coverage.one-day 20% gain compounds to ~8e30 %/yr) — too wide for the text column and more
digits than this project's own decimal type can parse back. Rates above 9999% show
as
>9999%in text and are omitted (empty/null) in machine output rather thanemitting a fabricated figure.
Positioning vs
report returnsThis is a realized-only return — it sees only lots you actually closed, so it
is not the portfolio's total return (a position you still hold contributes
nothing, however it has performed).
report returnsremains the beangrow-shapedtotal-return report (money- and time-weighted, including still-held positions
valued at market). This adds the per-lot view that
returnscannot give. Thedocs state the distinction and cross-reference both ways.
Undefined cases
n/a, and excluded from the pooled rates: short sales (money-in-then-out makesan IRR unconventional and misleading), lots with no acquisition date (AVERAGE
booking merges lots and drops dates), same-day round trips (a zero-day span
cannot be annualized), a non-positive cost basis, negative proceeds, and any lot
whose rate does not solve. A total loss is not excluded — it is exactly
-100%at any horizon and stays in the pool, since dropping it would flatter theaggregate by hiding capital that never came back.
When a bucket's rate covers fewer lots than the line's disposal count, the summary
says so:
IRR 25.00% (1 of 2 lots). The rate and the per-lot cells use onepredicate, so a summary can never contradict the rows above it.
Testing
Verified against an independent bisection XIRR — per-lot and pooled rates agree to
6 decimals (a 1-year 1000→1100 and a 2-year 500→605 both annualize to
10.000000%). Tests cover annualization/compounding, the opt-in default (schema
unchanged), and every undefined case, at both unit and end-to-end CLI level.
Full
rustledgersuite green; clippy + docs clean.🤖 Generated with Claude Code