Skip to content

feat(report): realized IRR for capgains (--irr) - #1861

Merged
robcohen merged 4 commits into
mainfrom
feat/capgains-irr
Jul 24, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/capgains-irr

Conversation

@robcohen

@robcohen robcohen commented Jul 24, 2026 •

Copy link
Copy Markdown
Member

Realized IRR for report capgains

Adds --irr: the annualized money-weighted return of each closed tax lot,
plus a pooled rate per term and per currency.

Sold       Commodity / account        Units  Acquired    Term       Proceeds           Gain       IRR
-----------------------------------------------------------------------------------------------------
2020-12-31 AAA Stock                     10  2020-01-01    ST           1100            100    10.00%
2021-12-31 BBB Stock                      5  2020-01-01    LT            605            105    10.00%
-----------------------------------------------------------------------------------------------------
Short-term    1 disposals   proceeds            1100   gain             100 USD   IRR 10.00%
Long-term     1 disposals   proceeds             605   gain             105 USD   IRR 10.00%
TOTAL       net realized gain             205 USD   IRR 10.00%

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

  • Per-lot: each closed lot is a round trip (-cost_basis at acquisition,
    +proceeds at sale), so it has a well-defined IRR.
  • Aggregate: 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.
  • Reuses the canonical solver: rustledger_returns::xirr (365-day basis,
    beangrow-compatible). No IRR solver is re-derived. The text column reuses
    returns' fmt_rate_pct so the two rate columns cannot drift in formatting.
  • Opt-in: keeps the default a lean tax report, and leaves the CSV/JSON schema
    unchanged unless --irr is passed. Machine output is a 2-decimal percent in
    an irr_pct field (empty / null when undefined) — the same unit as report returns' money_weighted_return_pct, so the two reports' rates are directly
    comparable rather than 100x apart. JSON summaries also carry irr_lots /
    irr_lots_total, the rate's coverage.
  • Bounded reporting: a very short hold annualizes to an enormous number (a
    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 than
    emitting a fabricated figure.

Positioning vs report returns

This 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 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 that returns cannot give. The
docs state the distinction and cross-reference both ways.

Undefined cases

n/a, and excluded from the pooled rates: short sales (money-in-then-out makes
an 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 the
aggregate 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 one
predicate, 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 rustledger suite green; clippy + docs clean.

🤖 Generated with Claude Code

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
@robcohen
robcohen requested a review from a team as a code owner July 24, 2026 19:01
Copilot AI review requested due to automatic review settings July 24, 2026 19:01
@codecov

codecov Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.39759% with 2 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/report_cmd/capgains.rs 99.38% 2 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 34.3ms ± 2.3ms 24 MB
beancount 903.4ms ± 9.8ms 50.7 MB
Comparison 26.3x faster 2.1x less

vs main branch (2026-07-24)

Metric main this PR Change
Time 27.7ms 34.3ms +23.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

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 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 --irr flag to report capgains and 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 from report 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_irr fields are absent; this avoids false failures if a string value contains irr.
    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 computed f64 values. Convert to f64 and 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.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 812
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

…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
Copilot AI review requested due to automatic review settings July 24, 2026 19:28

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

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Comment thread docs/commands/report.md Resolved
…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
Copilot AI review requested due to automatic review settings July 24, 2026 19:53

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

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

Comment thread docs/commands/report.md Resolved
Comment thread docs/commands/report.md Resolved
… 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
Copilot AI review requested due to automatic review settings July 24, 2026 20:13
@robcohen

Copy link
Copy Markdown
Member Author

Addressed the Copilot review (commit 2bfb5781):

Fixed now:

  • aggregate_irr no longer re-solves every lot on each of the four summary cells per currency — it keys off the already-solved d.irr. Beyond 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.
  • The "no IRR by default" assertions matched a substring of the whole output (a commodity or payee containing irr could flip them). They now assert on the schema: the CSV header and its column count, the JSON keys, and the text table header.
  • A stale docs paragraph survived an earlier edit and still claimed CSV/JSON carry "the exact value" and mentioned a <-9999% clamp. Corrected: machine output is a 2-decimal percent, rates above 9999% are omitted entirely (empty/null), and there is no lower clamp since a round trip cannot lose more than its basis.
  • PR description updated to the actual output contract (percent in irr_pct, not a raw fraction).

Already fixed in earlier commits on this branch (these comments are against superseded revisions):

  • The stale "raw fraction" CSV code comment — corrected in e464708f.
  • ends_with(',') proxy assertions — replaced with exact field-index checks in a9d1854a/e464708f.
  • The 0.1 stringify-flakiness concern is moot: output is now a rounded 2-decimal percent (25.00), which is deterministic, and the fixtures deliberately avoid 0.10 because that is xirr's Newton seed.

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

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

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