Add a money-weighted return calculator

Merged
JA
3mo ago
+1129-0

Part of we-promise/sure#3494.

Fork pre-flight: https://github.com/jaysbeekay/sure/pull/172 — same branch, same commit. Its CI, Gatekeeper and CodeRabbit history is the review evidence for this change and is not visible from here.

Summary

A portfolio's time-weighted return says what the investments did; it says nothing about what the investor got. Two people holding the same fund over the same year, one of whom bought most of their position the week before a fall, did not have the same year. This adds Portfolio::Xirr — the internal rate of return of an irregularly-timed series of cash flows — so a money-weighted return can be reported.

Model only, no callers. Nothing reads it yet; the performance engine that does follows as its own PR.

The fork pre-flight is the same branch at the same commit; its base is the fork's mirror/upstream-main, so its diff is this one.

What changed

  • 6ac9ec2f3 Add a money-weighted return calculator
  • 46df1a443 Pin the convergence contract, and say that a root need not be unique
  • f22708a2a Say when a money-weighted rate is one of several
  • 1f83af9c5 Derive the bracket's low end from the series, not a constant
  • 09f99475b Sum flows that fall on one date before judging the series
  • d02706b24 Return a root that sits exactly on a bracket endpoint
  • 6fbab7f26 Say that ambiguous? is a bound, because it is
  • fd03b9d47 Memoise the solved rate, and say which input shapes are accepted
  • 1110d3436 Search above minus a half for the low end of the bracket
  • 1f9c14384 Make the residual tolerance relative and find roots the bracket hides

app/models/portfolio/xirr.rb (471 lines), test/models/portfolio/xirr_test.rb (625 lines). No other file is touched.

Four decisions worth arguing about, each of which arrived through review:

Three inputs raise rather than return a number — flows that never change sign, flows that all fall on one date, and a series neither method solves. Each has no rate rather than an unknown one, so a caller that renders "not available" tells the truth where a fallback guess would not. rate_or_nil is the non-raising variant for render paths.

A series that changes sign more than once can have more than one rate, and this says so rather than refusing. -1000, +2700, -1800 on three annual dates is solved by both 20% and 50%. Refusing every such series would refuse most real portfolios — one withdrawal between two deposits is two sign changes — so #rate returns the root the search reaches from its 10% start, and #ambiguous? / #sign_changes let a caller ask whether that figure is unique before printing it as the money-weighted return. By Descartes' rule ambiguous? == false guarantees a single positive root, so the predicate never under-hedges; it can over-hedge a unique figure, which is the safe direction for a render path.

The low end of the bisection bracket is derived per series rather than fixed. This is the correctness fix in 1f83af9c5, and it is the one to read the diff for. Every loss reaches bisection — Newton's first step from its 10% start leaves the domain on one — so the bracket decides whether half the ordinary cases have an answer at all. With the bracket pinned at -0.999999, present_value divided by 1e-6 ** units, which underflows to zero past about 51 units: the objective became Infinity, the endpoint was not finite, and bisection gave up before it started while #rate reported "XIRR did not converge" for a series it had never searched. A 30% loss read over 52 weekly units and a 50% loss over 100 daily ones both raised ConvergenceError although each has a plain closed-form rate — and days_per_unit is the API this class offers callers, so those are not exotic shapes. One fixed floor is wrong in both directions, which is why the fix is not a safer constant: it was also needlessly high for a short span, putting a near-total loss over a single year out of reach for no arithmetic reason. #low_endpoint now starts against -1 and backs away until the objective can be evaluated, and Newton takes its domain check from the same endpoint.

Flows that fall on one date are summed before anything judges the series. This is the correctness fix in 09f99475b, found by CodeRabbit on the previous head. Two flows on one date share an exponent, so present_value cancels them however they were written — but sign_changes counted them separately, and a pair that cancels looked to it like a sign change. The guard that exists to refuse a one-way series therefore passed a series that, once evaluated, has no root:

seriesbeforeafter
[-1000@2026-01-01, +1000@2026-01-01, +100@2027-01-01]rate = 151,182,848,818NoSignChangeError ✅
the same series netted to one row per dateNoSignChangeErrorNoSignChangeError ✅

The answer depended on whether the caller pre-netted its rows, and one of the two answers was catastrophic garbage. Money in and out on one day is ordinary — a buy and a sell, a deposit spent the moment it lands — so normalize is split into parse and aggregate, and a date whose flows cancel drops out with the zeros. present_value is unchanged for every series, since a/(1+r)^t + b/(1+r)^t is (a+b)/(1+r)^t.

This changes one error contract, stated here rather than buried. Summing can empty a date out entirely, so -1000 and +1000 on a single date now net to nothing. The duration check therefore moved ahead of the sign check and reads the caller's own dates, captured before summing — "you gave me no time span" is prior to "money only went one way", since without a span no rate exists whatever the signs do. Visible effect: a single flow on a single date now raises NoDurationError where it raised NoSignChangeError. rate_or_nil rescues both, so no render path moves.

The residual tolerance is relative to the size of the series, not an absolute number of currency units. This is the correctness fix in 1f9c14384, and it came out of the upstream maintainer's stress-test (see below). An absolute figure made the answer depend on the unit the series happened to be written in: [-1000, -250, +1400] on three annual dates solves at 6.480040%, and the identical series scaled by 1e-12 returned Newton's untouched 10% start, because every present value in it is already below 1e-9 and the first thing the loop does is accept. The same fixed figure was out of reach at the other end — a 10% year on a billion stalled at a residual of 1.2e-7, which is Float noise at that magnitude rather than an unsolved series, and had to be rescued by bisection. The tolerance is now RELATIVE_RESIDUAL_TOLERANCE (1e-12) times the sum of the flows' absolute amounts, so acceptance depends only on present value over size; because the derivative scales with size too, the rate accuracy this buys is the same at every magnitude.

A bracket with no sign change at its ends is now searched in sub-brackets rather than abandoned. Also 1f9c14384. The present value is built on 1 / (1 + r), so a series changing sign more than once can cross zero and cross back: +1, -5, +3 on three annual dates has two exact roots inside the supported range, (3 ± √13) / 2, and the widest bracket reads positive at both ends — Newton missed from 10%, the global bracket saw no sign change, and the series was refused outright. The range is now walked in 128 sub-brackets sampled geometrically in 1 + r. Reached only after the global bracket has failed, so no series that solves today can change its answer: it can turn a refusal into a root and nothing else.

RELATIVE_RESIDUAL_TOLERANCE (a fraction of the series' size) and RATE_TOLERANCE (a rate) are named apart for the same reason as before: one TOLERANCE in both places invited the assumption that they must agree.

Stress-test findings

@jjmata ported the algorithm to Python and ran it against PyXIRR, scipy.optimize.brentq and closed-form solutions, over 1,860 analytical two-flow cases and 5,000 seeded random ones. Four findings; all four were re-run against the Ruby class at 1110d343 before anything was changed.

FindingVerdict
Absolute NPV tolerance breaks scale invarianceConfirmed, fixed in 1f9c14384
Multiple roots defeat the single global bracketConfirmed, fixed in 1f9c14384
Width-only bisection acceptance returns a catastrophic non-root near -1False positive, with evidence: the loop only ever replaces an endpoint with one of the same sign, so the ends bracket a sign change on every iteration and a width below RATE_TOLERANCE puts the root inside it. On the reported series the returned rate is within 3.3e-11 of the closed-form -0.999999 while the present value there is -33,487,331 — the objective is astronomically steep, not the rate wrong. No code change; the invariant is written down and pinned by a test
Same-date aggregation is input-order dependentDoes not reproduce in Ruby. Enumerable#sum compensates Float summation (Kahan-Babuska) where inject(0.0, :+) does not, so all 24 permutations of the reported fixture give one answer. That is a property of the method chosen rather than of the arithmetic, so a permutation test and a comment now hold it

Demo data

No demo data needed: nothing renders it yet. The PR that introduces a caller carries the demo data for what it shows.

Migration notes

No migration. No schema change, no data rewritten, no new dependency.

Verification

  • bin/rails test test/models/portfolio/xirr_test.rb: 33 runs, 78 assertions, 0 failures, 0 errors
  • bin/rubocop app/models/portfolio/xirr.rb test/models/portfolio/xirr_test.rb: 2 files inspected, no offenses
  • CI ci / test_unit and ci / test_system green on this head (the full suite, not just this file)

Mutation-checked, not just green. Each guard was broken deliberately and watched to fail:

MutationFails
Drop the same-date guard"raises when every flow falls on one date"
Let a stalled Newton step return its guess"newton hands a stalled step to bisection…"
ambiguous? returns a constant false"a series with two valid rates…"
Count flows instead of sign changestwo tests
Pin low_endpoint back to -0.999999all three new bracket tests, two of them with the original ConvergenceError
Drop the per-date summing from normalizeall three new aggregation tests
Walk past a root sitting exactly on a bracket endpoint"a root sitting exactly on a bracket endpoint is returned, not walked past"
Stop the low-endpoint search at -0.5"a span too long to evaluate at minus a half is solved above it", and the endpoint-shape test
Make the residual tolerance absolute again"the same series scaled up or down solves to the same rate"
Remove the sub-bracket scan"a series whose roots both sit inside the bracket is solved, not refused"
Gate bisection acceptance on the residual alone"a rate near minus one is accepted on bracket width, not on its residual"
Swap sum for inject when summing a date's flows"the order of same date flows does not change the answer"
Let Newton accept a stalled step without confirming the residual"newton hands a stalled step to bisection rather than reporting it"

The bracket tests' expected figures come from the closed form (B/A) ** (1/t) - 1, not from the solver, so they cannot pass by agreeing with the implementation.

Blast radius

Who else hits this line, and what do they pass? Nobody — the class is new, has no callers in this diff, and touches no shared path. It reads no models, no config and no database. The only way it reaches a user is through a later PR that calls it, and that PR is where the FX and flow-classification questions get answered.

Internally, 1f83af9c5 removes the RATE_FLOOR constant and the private units_for. Neither is referenced anywhere else in app/, lib/, test/ or config/; the test file references only RATE_CEILING, DAYS_PER_YEAR, Flow and the three error classes.

Summary by CodeRabbit

  • New Features

    • Adds money-weighted return calculations for irregular cash-flow series.
    • Aggregates cash flows occurring on the same date, including removal of dates that net to zero.
    • Supports configurable time units and returns high-precision results.
    • Provides safe handling for expected calculation failures and ambiguous or invalid cash-flow series.
    • Improves convergence for challenging investment scenarios, including losses and multiple potential solutions.
  • Tests

    • Adds coverage for aggregation, validation, fallback calculations, endpoint results, and long-duration losses.