The personal finance app for everyone (by everyone)
Ruby
Add a money-weighted return calculator (#3611)
jaysbeekay411585878ae8
diff --git a/app/models/portfolio/xirr.rb b/app/models/portfolio/xirr.rbnew file mode 100644index 0000000000..684d22345e--- /dev/null+++ b/app/models/portfolio/xirr.rb@@ -0,0 +1,478 @@+# The internal rate of return of an irregularly-timed series of cash flows --+# the money-weighted return of a portfolio, where TWR answers what the+# investments did and this answers what the investor got.+#+# Newton-Raphson with a bisection fallback. Newton converges in a handful+# of iterations on ordinary portfolios; bisection is slower but cannot diverge,+# so it catches the pathological series -- large early withdrawals, near-zero+# terminal values -- where Newton's derivative sends it off to infinity. Every+# loss takes the bisection path, because Newton's first step from its 10% start+# leaves the domain on one, so the bracket bisection searches is load-bearing+# for a whole half of the ordinary cases rather than only for exotic ones.+#+# ARITHMETIC NOTE. Money in this codebase is BigDecimal, but root-finding+# needs `(1 + r) ** (days / 365.0)` with a fractional exponent, which BigDecimal+# cannot do without BigMath.exp/log at a chosen precision -- slow, and delicate+# around r near -1. The iteration therefore runs in Float, which carries about+# fifteen significant digits for a figure displayed to two decimal places, and+# the result is returned as a BigDecimal. Amounts are converted once on the way+# in. This is the deliberate exception to the BigDecimal rule the money figures+# elsewhere follow.+#+# MULTIPLE ROOTS. The present value is a generalised polynomial in the rate, so+# a series that changes sign more than once can cross zero twice inside the+# bracket, and two rates are then equally "the" answer. -1000, +2700, -1800 on+# three annual dates is solved by both 20% and 50%.+#+# This returns the root the search reaches from its 10% start, which is the+# lower one for that series and is what every other XIRR does -- Excel's takes+# a `guess` argument for exactly this reason. It is a deliberate choice rather+# than an accident, because the alternative, refusing every series that changes+# sign twice, refuses most real portfolios: any account with a withdrawal+# between two deposits changes sign twice.+#+# `#ambiguous?` is how a caller finds out, and it is a CONSERVATIVE bound+# rather than a root count. Descartes' rule bounds the number of positive roots+# from ABOVE by the sign-change count, so `false` guarantees the figure is the+# only one that fits, while `true` means only that it MAY be one of several --+# -1000, +2000, -1000 changes sign twice and yet has a single distinct root at+# 0, with multiplicity two. Counting the distinct roots instead would mean+# solving for all of them on a render path to answer a question whose honest+# answer is "possibly".+#+# So a page printing an ambiguous figure as "the" money-weighted return may be+# overstating what was computed, and the safe direction is to hedge: over-hedging+# a unique figure is a smaller error than presenting one of several as the+# answer. The caller that renders this is a later PR; the predicate is here so+# that PR has something to ask.+#+# No gem: AGENTS.md asks for Rails and few dependencies, and this is a few+# hundred lines of arithmetic with no upstream to track.+class Portfolio::Xirr+ # The flows never change sign, so no rate exists -- money only ever went in, or+ # only ever came out. Callers render "not available"; they must not substitute+ # a guess.+ class NoSignChangeError < StandardError; end++ # Neither method reached the tolerance inside the iteration cap.+ class ConvergenceError < StandardError; end++ # Every flow falls on the same date, so no time passes and no annual rate+ # exists. Without this check the present value is the same at every rate,+ # and Newton returns its starting guess of 10% as if it had solved.+ class NoDurationError < StandardError; end++ Flow = Data.define(:date, :amount)++ DAYS_PER_YEAR = 365.0+ MAX_NEWTON_ITERATIONS = 50+ MAX_BISECTION_ITERATIONS = 200+ # Two different quantities, deliberately named apart. The residual tolerance+ # is a present value -- money -- and says the objective is close enough to+ # zero; RATE_TOLERANCE is a rate, and says the search has stopped moving.+ # Reading one `TOLERANCE` in both places invited the assumption that they+ # must match.+ #+ # The residual one is RELATIVE, and the constant is the fraction rather than+ # the amount: see #residual_tolerance for why an absolute figure made the+ # answer depend on the unit the series happened to be written in.+ RELATIVE_RESIDUAL_TOLERANCE = 1e-12+ RATE_TOLERANCE = 1e-9++ # How many sub-brackets #bisect_sub_brackets splits the search range into+ # when the range as a whole shows no sign change. Sampled geometrically, so+ # 128 steps span the whole range from a low endpoint one Float tick above -1+ # up to RATE_CEILING at a ratio of about 1.5 per step.+ BRACKET_SCAN_STEPS = 128++ # The high end of the bracket we search. 1e7 is 1,000,000,000% -- absurd as+ # a return, but the bracket only has to contain the root, not be plausible.+ RATE_CEILING = 1.0e7++ # The low end is never -1, where the objective is undefined (a total loss of+ # every future-dated flow), and it is not a constant either: how close to -1+ # the arithmetic can get depends on the series. See #low_endpoint. The search+ # starts one Float tick above -1 -- below EPSILON, `-1.0 + distance` IS -1.0+ # -- and backs off from there.+ NARROWEST_FLOOR_DISTANCE = Float::EPSILON++ attr_reader :flows, :days_per_unit++ # `flows` is any enumerable of objects answering `date` and `amount`, or+ # [date, amount] pairs. Those two shapes only -- a Hash of+ # `{ date:, amount: }` is neither, and fails on `to_date` with a+ # NoMethodError rather than with anything that names the problem.+ #+ # Sign convention: money leaving the investor is negative, money returning to+ # them is positive. The terminal value of the portfolio is the final positive+ # flow.+ #+ # `days_per_unit` is the length of the unit the rate is expressed in. The+ # default is a year, so `rate` is the annualised figure unless a caller says+ # otherwise. A caller reporting a period return passes the period's own+ # length instead, which is not a presentational choice: the rate+ # for a short period expressed annually is an extrapolation, and a large one+ # is outside what Newton reaches or what a Float holds, so the annual form of+ # a few days' return is unreliable where the period form is ordinary.+ def initialize(flows, days_per_unit: DAYS_PER_YEAR)+ moves = parse(flows).reject { |flow| flow.amount.zero? }++ # The caller's own dates, captured before same-date flows are summed.+ # The duration contract is about the span handed over, and summing can+ # empty a date out entirely -- -1000 and +1000 on one day net to nothing --+ # which would otherwise turn "no time passes" into "no sign change".+ @input_dates = moves.map(&:date).uniq+ @flows = aggregate(moves)+ @days_per_unit = days_per_unit.to_f++ # Finite as well as positive: Float::INFINITY is positive, and it would make+ # every elapsed interval zero, so the present value stops depending on the+ # rate and Newton returns its starting guess of 10% as if it had solved --+ # the same trap NoDurationError exists to close.+ raise ArgumentError, "days_per_unit must be a positive, finite number of days" unless+ @days_per_unit.finite? && @days_per_unit.positive?+ end++ def self.rate(flows, days_per_unit: DAYS_PER_YEAR)+ new(flows, days_per_unit: days_per_unit).rate+ end++ # How many times the series changes sign, once zero amounts are dropped. One+ # is the ordinary shape: money goes out, money comes back.+ def sign_changes+ @sign_changes ||= flows.map { |flow| flow.amount <=> 0 }+ .each_cons(2)+ .count { |previous, current| previous != current }+ end++ # True when the series MAY have more than one rate -- a conservative upper+ # bound, not a count. Descartes' rule bounds the root count from above by the+ # sign-change count, so false is a guarantee of uniqueness and true is a+ # "possibly": -1000, +2000, -1000 changes sign twice and has one distinct+ # root. See MULTIPLE ROOTS above for why that is the direction to err in.+ def ambiguous?+ sign_changes > 1+ end++ # The money-weighted rate per `days_per_unit`, as a BigDecimal+ # (0.0725 == 7.25%). Annualised unless the caller said otherwise.+ # Memoised on success. The search is deterministic for a given series, so a+ # second call re-solves to the same answer at full cost -- `sign_changes` was+ # already memoised and this was not. A raise is not memoised: the two guards+ # that raise are O(1), and the third only fires after a search that did not+ # converge, which is rare enough not to cache.+ def rate+ return @rate if defined?(@rate)++ # Duration is checked first, and against the caller's dates rather than the+ # summed ones. "You gave me no time span" is prior to "money only went one+ # way": without a span no rate exists whatever the signs do. It also keeps+ # -1000 and +1000 on a single date reporting the span problem, which is the+ # useful diagnostic, rather than the empty series that summing leaves.+ raise NoDurationError, "cash flows all fall on one date" if @input_dates.one?+ raise NoSignChangeError, "cash flows never change sign" unless sign_change?++ result = newton_rate || bisection_rate+ raise ConvergenceError, "XIRR did not converge" if result.nil?++ @rate = BigDecimal(result.to_s)+ end++ # Non-raising variant for render paths: returns nil where #rate would raise.+ def self.rate_or_nil(flows, days_per_unit: DAYS_PER_YEAR)+ rate(flows, days_per_unit: days_per_unit)+ rescue NoSignChangeError, NoDurationError, ConvergenceError+ nil+ end++ private+ # Flows on the same date are summed into one, and a date whose flows net to+ # nothing drops out with the zeros.+ #+ # Summing is not a tidy-up, it is what makes the sign-change contract mean+ # anything. Two flows on one date share an exponent, so `present_value`+ # cancels them however they were written -- but `sign_changes` counts them+ # separately, and a pair that cancels looks like a sign change to it. So+ # -1000 and +1000 on one day followed by +100 passed the "money has to go+ # both ways" guard while presenting the solver with a series that is only+ # +100, has no root, and cannot be refused for the reason it should be.+ # It returned 15,118,284,881,800% rather than raising NoSignChangeError,+ # which the same series written as a single netted row does raise.+ #+ # Money in and out on one day is ordinary -- a buy and a sell, a deposit+ # spent the moment it lands -- so whether a caller pre-nets its rows is not+ # something this class should give a different answer for.+ def parse(flows)+ Array(flows).map do |flow|+ if flow.respond_to?(:date) && flow.respond_to?(:amount)+ Flow.new(date: flow.date.to_date, amount: flow.amount.to_f)+ else+ date, amount = flow+ Flow.new(date: date.to_date, amount: amount.to_f)+ end+ end+ end++ # `sum` and not `inject(0.0, :+)`, and not by accident. Ruby's+ # Enumerable#sum compensates Float summation (Kahan-Babuska), so a day's+ # flows add to the same total whatever order the caller listed them in;+ # `inject` does not. -1e16, +1 and +1e16 on one date sum to 1.0 in all six+ # orders through `sum`, and to 0.0 in four of the six through `inject` --+ # and a lost +1 is the difference between a series that solves and one that+ # is refused for never changing sign. Group order is input order, so the+ # order really is the caller's.+ # Frozen, because `flows` is public and every figure on the instance is+ # memoised from it -- sign_changes, terms, first_date, residual_tolerance+ # and `rate` itself. Without this a caller could append a flow after asking+ # for the rate and get an object that reports three rows, one sign change+ # and the answer for two. `Flow` is a Data and already frozen, so the array+ # is the whole of the mutable surface.+ def aggregate(moves)+ moves.group_by(&:date)+ .map { |date, on_date| Flow.new(date: date, amount: on_date.sum(&:amount)) }+ .reject { |flow| flow.amount.zero? }+ .sort_by(&:date)+ .freeze+ end++ def sign_change?+ sign_changes.positive?+ end++ # The residual that counts as zero for THIS series, in the series' own+ # money: a fraction of its nominal size, not a fixed number of currency+ # units.+ #+ # An absolute figure is not scale invariant, and the present value scales+ # with the flows: the same series written in cents and in millions asks the+ # same question and must get the same answer. With a fixed 1e-9 it did not.+ # -1000, -250, +1400 on three annual dates solves at 6.480040%, and the+ # identical series multiplied 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 is out of+ # reach at the other end: a 10% year on a billion stalls at a residual of+ # 1.2e-7, which is Float noise on that magnitude rather than an unsolved+ # series, and had to be rescued by bisection.+ #+ # The scale is the nominal size of the series, summed once and independent+ # of the rate, so acceptance depends only on present value over size. The+ # derivative scales with size too, so the RATE accuracy this buys is the+ # same at every magnitude rather than merely different.+ def residual_tolerance+ @residual_tolerance ||= RELATIVE_RESIDUAL_TOLERANCE * flows.sum { |flow| flow.amount.abs }+ end++ def first_date+ @first_date ||= flows.first.date+ end++ # Each flow as [units elapsed from the first flow, amount]. One unit is a+ # year unless the caller asked for a different one.+ #+ # Computed once rather than per evaluation: the intervals do not move+ # between iterations, and the two objective functions below are evaluated a+ # few hundred times per solve.+ def terms+ @terms ||= flows.map { |flow| [ (flow.date - first_date).to_i / days_per_unit, flow.amount ] }+ end++ # Present value of every flow at `rate`. The root of this is the answer.+ def present_value(rate)+ terms.sum { |units, amount| amount / ((1 + rate)**units) }+ end++ def present_value_derivative(rate)+ terms.sum do |units, amount|+ next 0.0 if units.zero?++ -units * amount / ((1 + rate)**(units + 1))+ end+ end++ # The low end of the bracket: as close to -1 as this series' arithmetic can+ # actually be evaluated, or nil if no endpoint below zero can be.+ #+ # `present_value` divides by `(1 + rate) ** units`. Near -1 that power is+ # tiny, and once it underflows to zero the quotient is Infinity -- bisection+ # sees a non-finite endpoint and abandons a series whose root is perfectly+ # ordinary. Where the underflow starts depends on the span, so a single+ # fixed floor is wrong in both directions. At -0.999999 it was too low for a+ # long series -- a 30% loss over 52 weekly units, or a 50% loss over 100+ # daily ones, both raised ConvergenceError although a rate exists and every+ # loss reaches bisection -- and needlessly high for a short one, putting a+ # near-total loss over a single year out of reach for no arithmetic reason.+ #+ # So derive it instead: start against -1 and back away until the objective+ # can be evaluated. Doubling the distance reaches any usable endpoint in at+ # most the ~52 steps it takes to cross from EPSILON to 1, and the endpoint+ # is then within a factor of two of the closest one this series admits,+ # which is ample for a bracket end. Giving up at a distance of 1 is giving+ # up at a rate of 0: a series whose amounts overflow even there has no+ # bracket to search, and nil says so rather than a fabricated figure.+ def low_endpoint+ return @low_endpoint if defined?(@low_endpoint)++ distance = NARROWEST_FLOOR_DISTANCE++ while distance < 1.0+ candidate = -1.0 + distance+ return @low_endpoint = candidate if present_value(candidate).finite?++ distance *= 2.0+ end++ # Doubling from EPSILON lands on -1 + 2 ** -k, so the last candidate it+ # reaches is -0.5 and the next distance is the loop's own limit. That+ # leaves (-0.5, 0) unprobed, and for a long series it is the only place a+ # usable endpoint exists: 0.5 ** units underflows to zero past about+ # 1,074 units -- three years read daily, twenty read weekly -- so every+ # candidate at or below -0.5 divides by zero and the series was refused+ # although its rate is ordinary.+ #+ # Halving the remaining gap to zero covers that interval with the same+ # number of steps and the same "within a factor of two of the closest+ # usable endpoint" guarantee. It stops short of zero: a low end of zero+ # is not a low end, and an endpoint that cannot be evaluated anywhere+ # below it means there is no bracket to search.+ gap = 0.5+ while gap > NARROWEST_FLOOR_DISTANCE+ gap /= 2.0+ candidate = -gap+ return @low_endpoint = candidate if present_value(candidate).finite?+ end++ @low_endpoint = nil+ end++ def newton_rate+ rate = 0.1++ MAX_NEWTON_ITERATIONS.times do+ value = present_value(rate)+ return rate if value.abs < residual_tolerance++ derivative = present_value_derivative(rate)+ return nil if derivative.zero? || !derivative.finite?++ step = value / derivative+ next_rate = rate - step++ # Newton has left the domain; hand over to bisection rather than+ # producing a NaN and calling it a return. The floor is the endpoint+ # bisection uses, so the two agree on where the domain ends instead of+ # each carrying its own idea of it.+ return nil if !next_rate.finite? || next_rate <= (low_endpoint || -1.0)++ # A step this small means Newton has stopped moving. That is NOT the+ # same as having solved: on a flat or ill-conditioned stretch it can+ # stall far from the root, and returning the rate here skipped the only+ # check that says so. Confirm the residual, and hand over to bisection+ # when it fails rather than reporting a stalled guess as an answer.+ if (next_rate - rate).abs < RATE_TOLERANCE+ return next_rate if present_value(next_rate).abs < residual_tolerance++ return nil+ end++ rate = next_rate+ end++ nil+ end++ def bisection_rate+ low = low_endpoint+ return nil if low.nil?++ bisect(low, RATE_CEILING) || bisect_sub_brackets(low, RATE_CEILING)+ end++ def bisect(low, high)+ low_value = present_value(low)+ high_value = present_value(high)+ return nil unless low_value.finite? && high_value.finite?++ # An endpoint can BE the root, and the sign test below cannot see it: a+ # residual of exactly zero makes the product zero, not negative, so+ # bisection walked past a solved endpoint and converged on whichever end+ # the interval collapsed towards. `[-1 today, +Float::EPSILON a year on]`+ # solves exactly at the low endpoint and returned RATE_CEILING -- a+ # 1,000,000,000% gain reported for a total loss.+ return low if low_value.abs < residual_tolerance+ return high if high_value.abs < residual_tolerance++ # No sign change across this bracket. The caller decides whether that is+ # the end of the search or the cue to look inside it.+ return nil if low_value * high_value > 0++ MAX_BISECTION_ITERATIONS.times do+ mid = (low + high) / 2.0+ mid_value = present_value(mid)++ # Two acceptances, and the second is not a weaker form of the first.+ # The loop only ever replaces an endpoint with one of the same sign, so+ # `low` and `high` bracket a sign change on every iteration; once they+ # are within RATE_TOLERANCE of each other, so is the root, whatever the+ # residual there reads.+ #+ # That distinction is load-bearing near -1, where the objective is+ # astronomically steep and the residual stops measuring rate accuracy+ # at all. -1, -1,000,000, +1 on three annual dates has the exact root+ # -0.999999; this returns it to within 3.4e-11 while the present value+ # there is still about -33,487,331, because one Float tick of `1 + r`+ # is a ten-billionth of it at that rate. Refusing on the residual would+ # refuse a rate that is right to ten decimal places.+ return mid if mid_value.abs < residual_tolerance || (high - low).abs < RATE_TOLERANCE++ if low_value * mid_value < 0+ high = mid+ else+ low = mid+ low_value = mid_value+ end+ end++ nil+ end++ # Both ends of the range can sit on the same side of zero while roots sit+ # between them. The present value is built on 1 / (1 + r), so a series that+ # changes sign more than once can cross zero and cross back: +1, -5, +3 on+ # three annual dates has two exact roots inside the range, (3 - sqrt 13) / 2+ # and (3 + sqrt 13) / 2, and the widest bracket reads positive at both ends.+ # Newton misses from 10%, the single global bracket sees no sign change, and+ # a series with two ordinary answers was refused outright.+ #+ # Sampled geometrically in `1 + r` rather than evenly in `r`, because that+ # is the variable the objective is built on: an even walk from just above+ # -1 up to 1e7 spends every step out at the top, where the function is flat,+ # and none of them near -1, where all of the structure is.+ #+ # Only reached once the whole range has shown no sign change, so no series+ # that solves today can change its answer -- this can only turn a refusal+ # into a root. The walk runs upward from the low end, so where a series has+ # several roots it reaches the lowest one; `#ambiguous?` is still how a+ # caller finds out that there were several. See MULTIPLE ROOTS above.+ def bisect_sub_brackets(low, high)+ ratio = ((1.0 + high) / (1.0 + low))**(1.0 / BRACKET_SCAN_STEPS)++ previous = low+ previous_value = present_value(previous)++ BRACKET_SCAN_STEPS.times do+ rate = ((1.0 + previous) * ratio) - 1.0+ value = present_value(rate)+ return nil unless value.finite?++ if previous_value * value <= 0+ root = bisect(previous, rate)+ return root unless root.nil?+ end++ previous = rate+ previous_value = value+ end++ nil+ end+enddiff --git a/test/models/portfolio/xirr_test.rb b/test/models/portfolio/xirr_test.rbnew file mode 100644index 0000000000..8366ae8f6b--- /dev/null+++ b/test/models/portfolio/xirr_test.rb@@ -0,0 +1,651 @@+require "test_helper"++class Portfolio::XirrTest < ActiveSupport::TestCase+ # Money that only ever went one way has no rate of return: there+ # is no r for which the present value crosses zero. Returning a plausible+ # number here would be inventing one.+ test "raises when the series never changes sign" do+ flows = [+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2026, 6, 1), -1_000 ]+ ]++ assert_raises Portfolio::Xirr::NoSignChangeError do+ Portfolio::Xirr.rate(flows)+ end++ assert_nil Portfolio::Xirr.rate_or_nil(flows),+ "the render path must degrade to nil rather than raise"+ end++ # A year, a single outlay, a single return: the rate is the plain growth.+ test "solves a simple one year doubling" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 2_000 ]+ ])++ assert_in_delta 1.0, rate.to_f, 0.0005, "1000 -> 2000 over one year is 100%"+ end++ test "solves a flat series at zero" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 1_000 ]+ ])++ assert_in_delta 0.0, rate.to_f, 0.0005+ end++ # 1,000 in at the start, 1,000 more at six months, 2,200 out at twelve.+ #+ # Sanity check first, because it is the one an author can do in their head:+ # the first 1,000 was invested for a full year and the second for half of one,+ # so the weighted capital is 1,000 + 500 = 1,500, and a 200 gain on 1,500 is+ # 13.3%. Compounding lifts it slightly.+ #+ # Exactly, with t = 182/365 = 0.49863 and x = 1 + r, the closed form is+ # -1000x - 1000·x^0.50137 + 2200 = 0+ # At x = 1.1346 the left side is -1134.60 - 1065.37 + 2200 ≈ 0.03, so the root+ # is 0.1346.+ test "solves an irregular series with a mid period contribution" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2026, 7, 2), -1_000 ],+ [ Date.new(2027, 1, 1), 2_200 ]+ ])++ assert_in_delta 0.1346, rate.to_f, 0.002+ end++ test "handles a loss" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 500 ]+ ])++ assert_in_delta(-0.5, rate.to_f, 0.0005)+ end++ # Halving over a year. From its 10% starting guess Newton's first step lands+ # below -100%, outside the domain, so it hands over; bisection finds -50%.+ # Asserting that Newton alone gives up is what proves the fallback ran.+ test "falls back to bisection when newton leaves the domain" do+ flows = [+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 500 ]+ ]+ xirr = Portfolio::Xirr.new(flows)++ assert_nil xirr.send(:newton_rate), "the fixture must defeat Newton, or this proves nothing"+ assert_in_delta(-0.5, xirr.rate.to_f, 0.0005)+ end++ # A step below RATE_TOLERANCE means Newton stopped moving, which is not the+ # same as having solved: on an ill-conditioned stretch it stalls far from any+ # root, and returning the rate there reports a guess as an answer. So the+ # residual is confirmed before the step is accepted, and a stall hands over+ # to bisection instead.+ #+ # -50,000 out, 500 and 20,000 back, 100 out again, on four annual dates: the+ # stall fires at about -0.99493 with a residual of -4.8e-6 against a tolerance+ # of 7.1e-8. What is pinned is the handover, not the stalling rate -- the+ # figure must come from bisection, and it must be a rate the objective+ # actually crosses zero at.+ test "newton hands a stalled step to bisection rather than reporting it" do+ flows = [+ [ Date.new(2026, 1, 1), -50_000 ],+ [ Date.new(2027, 1, 1), 500 ],+ [ Date.new(2028, 1, 1), 20_000 ],+ [ Date.new(2029, 1, 1), -100 ]+ ]+ xirr = Portfolio::Xirr.new(flows)++ assert_nil xirr.send(:newton_rate), "a small step without a small residual is not a solution"++ rate = xirr.rate.to_f+ below = xirr.send(:present_value, rate - 1e-8)+ above = xirr.send(:present_value, rate + 1e-8)++ assert_operator below * above, :<, 0,+ "the reported rate must sit on a sign change, i.e. on a root"+ end++ # Money scale is not part of the question. The same series written in cents+ # and in billions is the same series, and an ABSOLUTE residual tolerance made+ # it two different ones: below the tolerance every present value looks solved,+ # and above it none of them do.+ #+ # Both halves are pinned. The tiny one accepted Newton's untouched 10% start+ # because its whole present value is smaller than 1e-9; the billion-dollar one+ # stalled at a residual of 1.2e-7, which is Float noise at that magnitude and+ # not an unsolved series, and had to be rescued by bisection.+ test "the same series scaled up or down solves to the same rate" do+ shape = [+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), -250 ],+ [ Date.new(2028, 1, 1), 1_400 ]+ ]++ ordinary = Portfolio::Xirr.rate(shape).to_f+ tiny = Portfolio::Xirr.rate(shape.map { |date, amount| [ date, amount * 1e-12 ] }).to_f+ huge = Portfolio::Xirr.rate(shape.map { |date, amount| [ date, amount * 1e9 ] }).to_f++ assert_in_delta ordinary, tiny, 1e-9, "the same question in picodollars has the same answer"+ assert_in_delta ordinary, huge, 1e-9, "and so does the same question in billions"++ # The two-flow form, where the closed rate is exact and PyXIRR agrees: a+ # doubling is 100% whether the amounts are 1e-12 or 1.+ assert_in_delta 1.0,+ Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1e-12 ],+ [ Date.new(2027, 1, 1), 2e-12 ]+ ]).to_f,+ 0.0005++ # And the 10% year on a billion is now Newton's own answer rather than a+ # stall handed to bisection.+ billion = Portfolio::Xirr.new([+ [ Date.new(2026, 1, 1), -1_000_000_000 ],+ [ Date.new(2027, 1, 1), 1_100_000_000 ]+ ])++ assert_in_delta 0.1, billion.send(:newton_rate), 1e-9+ end++ # A fivefold gain in 30 days annualises to 5^(365/30) - 1, about 3.2e8. That+ # is above RATE_CEILING, so bisection could not find it; Newton must, and to+ # the right magnitude, not merely to some positive number.+ test "newton solves a steep series whose root lies beyond the bisection bracket" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2026, 1, 31), 5_000 ]+ ])++ expected = (5.0**(365.0 / 30)) - 1+ assert_operator expected, :>, Portfolio::Xirr::RATE_CEILING+ assert_in_delta expected, rate.to_f, expected * 1e-6+ end++ test "raises when every flow falls on one date" do+ flows = [+ [ Date.new(2026, 3, 2), -1_000 ],+ [ Date.new(2026, 3, 2), 1_000 ]+ ]++ assert_raises(Portfolio::Xirr::NoDurationError) { Portfolio::Xirr.rate(flows) }+ assert_nil Portfolio::Xirr.rate_or_nil(flows)+ end++ # 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 like a sign change. So -1000 and +1000 on one day+ # followed by +100 passed the "money has to go both ways" guard and handed the+ # solver a series that is only +100 and has no root. It returned+ # 15,118,284,881,800% rather than raising.+ #+ # Same-date flows are summed before any of that, so the guard now sees the+ # series that actually exists.+ test "flows on one date are summed before the sign-change guard" do+ flows = [+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2026, 1, 1), 1_000 ],+ [ Date.new(2027, 1, 1), 100 ]+ ]++ assert_raises Portfolio::Xirr::NoSignChangeError do+ Portfolio::Xirr.rate(flows)+ end+ assert_nil Portfolio::Xirr.rate_or_nil(flows)+ end++ # The invariant behind that fix, and the one worth keeping: whether a caller+ # pre-nets its rows must not change the answer. Money in and out on one day is+ # ordinary -- a buy and a sell, a deposit spent the moment it lands -- and a+ # caller that groups by date should not get a different figure from one that+ # does not.+ test "a netted series and the same series written out agree" do+ start = Date.new(2026, 1, 1)+ finish = Date.new(2027, 1, 1)++ # The deposit is listed before the purchase it funds, so unsummed this+ # reads +500, -1500, +2000 -- two sign changes, and therefore "ambiguous"+ # -- where the series it describes changes sign once. Ordering rows within+ # a day must not decide whether the caller is told its figure is one of+ # several.+ written_out = Portfolio::Xirr.new([+ [ start, 500 ], [ start, -1_500 ], [ finish, 2_000 ]+ ])+ pre_netted = Portfolio::Xirr.new([ [ start, -1_000 ], [ finish, 2_000 ] ])++ assert_in_delta pre_netted.rate.to_f, written_out.rate.to_f, 1e-12+ assert_in_delta 1.0, written_out.rate.to_f, 0.0005, "and both are the doubling"++ assert_equal pre_netted.sign_changes, written_out.sign_changes+ assert_not written_out.ambiguous?, "one deposit and one withdrawal is one sign change"+ end++ # A date whose flows cancel contributes nothing and drops out with the zeros,+ # so it cannot supply a phantom term to the present value.+ test "a date whose flows net to nothing drops out" do+ start = Date.new(2026, 1, 1)+ xirr = Portfolio::Xirr.new([+ [ start, -1_000 ],+ [ Date.new(2026, 6, 1), 750 ],+ [ Date.new(2026, 6, 1), -750 ],+ [ Date.new(2027, 1, 1), 2_000 ]+ ])++ assert_equal [ start, Date.new(2027, 1, 1) ], xirr.flows.map(&:date)+ assert_in_delta 1.0, xirr.rate.to_f, 0.0005+ end++ # A bracket endpoint can BE the root, and the sign test cannot see it: a+ # residual of exactly zero makes the product zero rather than negative, so+ # bisection walked past a solved endpoint and converged on whichever end the+ # interval collapsed towards.+ #+ # -1 today and Float::EPSILON a year later is a total loss, and it solves+ # exactly at the low endpoint. It returned RATE_CEILING -- a 1,000,000,000%+ # gain reported for losing everything.+ test "a root sitting exactly on a bracket endpoint is returned, not walked past" do+ flows = [ [ Date.new(2026, 1, 1), -1 ], [ Date.new(2027, 1, 1), Float::EPSILON ] ]+ xirr = Portfolio::Xirr.new(flows)++ assert_in_delta 0.0, xirr.send(:present_value, xirr.send(:low_endpoint)), 1e-12,+ "the fixture must actually solve at the endpoint, or this proves nothing"+ assert_operator xirr.rate.to_f, :<, -0.99,+ "losing everything is about -100%, not the top of the bracket"+ end++ # Every loss reaches bisection, so the low end of its bracket decides whether+ # an ordinary loss has a rate at all. A fixed -0.999999 floor meant dividing+ # by 1e-6 ** units, which underflows to zero past about 51 units and made the+ # present value Infinity: bisection saw a non-finite endpoint and gave up, and+ # `rate` reported "did not converge" for a series it had never searched.+ #+ # Both fixtures are ordinary shapes in the unit this class offers callers --+ # a 30% loss over a year read weekly, a 50% loss over 100 days read daily --+ # and both raised ConvergenceError before the endpoint was derived per series.+ # Closed form: a single outlay A returning B after t units solves exactly at+ # (B/A) ** (1/t) - 1, so the expected figures here are not the solver's own.+ test "an ordinary loss is solved however many units it spans" do+ start = Date.new(2026, 1, 1)++ weekly = Portfolio::Xirr.rate(+ [ [ start, -1_000 ], [ start + 364, 700 ] ], days_per_unit: 7+ )+ assert_in_delta (700.0 / 1_000)**(7.0 / 364) - 1, weekly.to_f, 1e-9,+ "52 weekly units: a 30% loss has a rate, and this is it"++ daily = Portfolio::Xirr.rate(+ [ [ start, -1_000 ], [ start + 100, 500 ] ], days_per_unit: 1+ )+ assert_in_delta (500.0 / 1_000)**(1.0 / 100) - 1, daily.to_f, 1e-9,+ "100 daily units: likewise"+ end++ # The other direction of the same defect. A fixed floor is not only too low+ # for a long span, it is needlessly high for a short one: a near-total loss+ # over a single year has a real rate below -99.9999%, and nothing about the+ # arithmetic at one unit of span puts it out of reach. Deriving the endpoint+ # from the series reaches it.+ test "a near total loss over one unit is solved rather than refused" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 0.0001 ]+ ])++ assert_in_delta(-0.9999999, rate.to_f, 1e-9, "0.0001 back on 1,000 in one year")+ end++ # The same defect once more, at the other end of the search. Backing away from+ # -1 by doubling reaches -0.5 and then stops: the next distance is 1.0, the+ # loop's own limit, so everything between -0.5 and 0 was never probed. That+ # interval is where a long series' only evaluable endpoint lives, because+ # 0.5 ** units underflows to zero past about 1,074 units and every candidate+ # at or below -0.5 is Infinity.+ #+ # Both fixtures are ordinary shapes in the units this class offers: a 10%+ # loss over three years read daily, and the same loss over twenty years read+ # weekly. Newton cannot rescue either -- from its 10% start the derivative+ # underflows to zero at these exponents -- so the endpoint decides whether+ # there is an answer at all, and both raised ConvergenceError.+ test "a span too long to evaluate at minus a half is solved above it" do+ start = Date.new(2006, 1, 1)++ daily = Portfolio::Xirr.rate(+ [ [ start, -1_000 ], [ start + 1_095, 900 ] ], days_per_unit: 1+ )+ # RATE_TOLERANCE is the width bisection stops at, so 1e-9 is the accuracy+ # the class offers and the closed form is what it is measured against.+ assert_in_delta (900.0 / 1_000)**(1.0 / 1_095) - 1, daily.to_f, 1e-9,+ "1,095 daily units: a 10% loss over three years has a rate"++ weekly = Portfolio::Xirr.rate(+ [ [ start, -1_000 ], [ start + 7_600, 900 ] ], days_per_unit: 7+ )+ assert_in_delta (900.0 / 1_000)**(7.0 / 7_600) - 1, weekly.to_f, 1e-9,+ "1,085 weekly units: likewise"+ end++ # What the endpoint for such a series has to look like, so the fix above+ # cannot be satisfied by widening the doubling loop's limit past 1.0 -- which+ # would hand bisection a positive "low" end and a bracket that excludes every+ # negative rate.+ test "an endpoint above minus a half is still a negative rate the objective can be evaluated at" do+ start = Date.new(2006, 1, 1)+ xirr = Portfolio::Xirr.new([ [ start, -1_000 ], [ start + 1_095, 900 ] ], days_per_unit: 1)+ endpoint = xirr.send(:low_endpoint)++ assert_not_nil endpoint, "a series this class can solve must have an endpoint to solve it from"+ assert_operator endpoint, :>, -0.5, "nothing at or below -0.5 can be evaluated at 1,095 units"+ assert_operator endpoint, :<, 0.0, "it is still the low end of the bracket"+ assert xirr.send(:present_value, endpoint).finite?,+ "an endpoint bisection cannot evaluate is not an endpoint"+ assert_operator endpoint, :<, xirr.rate.to_f,+ "and the root has to be inside the bracket it opens"+ end++ # The bracket only moves as far from -1 as the arithmetic forces it to, so a+ # short span keeps an endpoint that a long one cannot afford. Pinning both+ # ends stops a future "just use a safer constant" from quietly reintroducing+ # either half of the defect above.+ test "the low endpoint is derived from the series, not fixed" do+ start = Date.new(2026, 1, 1)++ short = Portfolio::Xirr.new([ [ start, -1_000 ], [ start + 365, 500 ] ])+ long = Portfolio::Xirr.new([ [ start, -1_000 ], [ start + 365 * 60, 500 ] ])++ assert_operator short.send(:low_endpoint), :<, -0.99999,+ "one unit of span can be evaluated hard against -1"+ assert_operator long.send(:low_endpoint), :>, short.send(:low_endpoint),+ "sixty units cannot, and the endpoint has to back off"+ assert_operator long.send(:low_endpoint), :<, 0.0,+ "but it is still a low end, not a positive rate"++ assert Float::INFINITY > short.send(:present_value, short.send(:low_endpoint)).abs,+ "the endpoint the bracket uses must be one the objective can be evaluated at"+ assert Float::INFINITY > long.send(:present_value, long.send(:low_endpoint)).abs+ end++ # The third rescue branch, which no fixture reaches: bisection searches from a+ # derived low endpoint up to 1e7, and a series that changes sign almost always puts a root+ # somewhere in it -- I tried three shapes built to defeat both methods (a+ # bigger outflow after an inflow, an alternating series, a near-zero terminal+ # value) and all three converged. What is pinned here is the CONTRACT rather+ # than a numeric case: when neither method solves, the answer is an error and+ # a nil, never the last guess either method held.+ test "a series neither method solves has no rate, not the guess it stopped on" do+ flows = [+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 2_000 ]+ ]++ Portfolio::Xirr.any_instance.stubs(:newton_rate).returns(nil)+ Portfolio::Xirr.any_instance.stubs(:bisection_rate).returns(nil)++ assert_raises(Portfolio::Xirr::ConvergenceError) { Portfolio::Xirr.rate(flows) }+ assert_nil Portfolio::Xirr.rate_or_nil(flows),+ "the render path degrades to nil here too, or it raises in a view"+ end++ # -1000, +2700, -1800 on three annual dates is 1000x^2 - 2700x + 1800 = 0 for+ # x = 1 + r, whose roots are 1.2 and 1.5: 20% and 50% both satisfy the series+ # exactly, and neither is more "correct" than the other.+ #+ # The decision this pins is that the figure is the root the search reaches+ # from its 10% start -- the lower one here -- rather than a refusal. Refusing+ # every series that changes sign twice would refuse most real portfolios: one+ # withdrawal between two deposits is two sign changes. What a caller must not+ # do is print it as THE money-weighted return without asking #ambiguous?.+ test "a series with two valid rates returns the one the search reaches, and says it is ambiguous" do+ flows = [+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 2_700 ],+ [ Date.new(2028, 1, 1), -1_800 ]+ ]++ xirr = Portfolio::Xirr.new(flows)++ assert_in_delta 0.0, xirr.send(:present_value, 0.2), 1e-9, "0.2 must actually solve it"+ assert_in_delta 0.0, xirr.send(:present_value, 0.5), 1e-9, "and so must 0.5, or there is one root"++ assert_in_delta 0.2, xirr.rate.to_f, 1e-9+ assert xirr.ambiguous?, "two sign changes, so the figure is one of several"+ assert_equal 2, xirr.sign_changes+ end++ # BOTH ends of the widest bracket can sit on the same side of zero while roots+ # sit between them, and a single global bracket cannot see it. +1, -5, +3 on+ # three annual dates is 1 - 5u + 3u**2 for u = 1 / (1 + r), whose roots are+ # (3 -/+ sqrt 13) / 2: about -30.2776% and about +330.2776%, both inside the+ # supported range. The present value is positive at the low endpoint and+ # positive at the ceiling, Newton misses from its 10% start, and the series+ # was refused outright although it has two ordinary answers.+ #+ # What is pinned: the refusal is gone, and the figure returned is a rate the+ # objective actually crosses zero at rather than any number at all.+ test "a series whose roots both sit inside the bracket is solved, not refused" do+ flows = [+ [ Date.new(2026, 1, 1), 1 ],+ [ Date.new(2027, 1, 1), -5 ],+ [ Date.new(2028, 1, 1), 3 ]+ ]++ xirr = Portfolio::Xirr.new(flows)+ low = xirr.send(:low_endpoint)++ assert_operator xirr.send(:present_value, low) * xirr.send(:present_value, Portfolio::Xirr::RATE_CEILING),+ :>, 0,+ "the premise: no sign change across the widest bracket"+ assert_nil xirr.send(:newton_rate), "and Newton does not reach either root from 10%"++ lower_root = (3 - Math.sqrt(13)) / 2+ assert_in_delta lower_root, xirr.rate.to_f, 1e-8,+ "the scan walks up from the low end, so it reaches the lower root"+ assert xirr.ambiguous?, "two sign changes, so the caller is told there may be another"+ end++ # Near -1 the objective is astronomically steep, and there the residual stops+ # measuring how close the rate is. -1, -1,000,000, +1 on three annual dates+ # has one exact root, -0.999999; bisection returns it to within 3.4e-11 while+ # the present value AT that rate is about -33,487,331, because one Float tick+ # of `1 + r` is a ten-billionth of it there.+ #+ # So bisection accepts on bracket width as well as on residual, and the width+ # is the stronger claim of the two: the loop only ever replaces an endpoint+ # with one of the same sign, so the two ends bracket a sign change on every+ # iteration and a width below RATE_TOLERANCE puts the root inside it. Gating+ # acceptance on the residual alone would refuse a rate that is right to ten+ # decimal places.+ test "a rate near minus one is accepted on bracket width, not on its residual" do+ flows = [+ [ Date.new(2026, 1, 1), -1 ],+ [ Date.new(2027, 1, 1), -1_000_000 ],+ [ Date.new(2028, 1, 1), 1 ]+ ]++ xirr = Portfolio::Xirr.new(flows)+ rate = xirr.rate.to_f++ assert_in_delta(-0.999999, rate, 1e-9, "the closed-form root of 1 - 1e6 u + u**2 at u = 1 / (1 + r)")++ residual = xirr.send(:present_value, rate)+ assert_operator residual.abs, :>, xirr.send(:residual_tolerance),+ "the premise: the residual there is nowhere near zero"+ assert_operator xirr.send(:present_value, rate - 1e-9) * xirr.send(:present_value, rate + 1e-9),+ :<, 0,+ "and yet the root is inside one RATE_TOLERANCE of the answer"+ end++ # Flows landing on one date are summed in Float, and Float addition is not+ # associative: -1e16, +1 and +1e16 add to 1.0 or to 0.0 depending on the+ # order, and a lost +1 is the difference between a series that solves and one+ # refused for never changing sign.+ #+ # Ruby's Enumerable#sum compensates for that (Kahan-Babuska) where a hand+ # written `inject(0.0, :+)` does not, so the answer does not depend on the+ # order the caller happened to list a day's rows in. That is a property of+ # the method chosen, not of the arithmetic, so it is pinned here: every+ # permutation of the same day must give the same rate.+ test "the order of same date flows does not change the answer" do+ on_the_day = [ -1e16, 1.0, 1e16 ]++ rates = on_the_day.permutation.map do |amounts|+ flows = amounts.map { |amount| [ Date.new(2026, 1, 1), amount ] }+ flows << [ Date.new(2027, 1, 1), -2.0 ]++ Portfolio::Xirr.rate(flows).to_f+ end++ assert_equal 1, rates.uniq.size, "six orderings, one answer: #{rates.inspect}"+ assert_in_delta 1.0, rates.first, 0.0005, "1 in and 2 out a year later is 100%"+ end++ # The predicate is an upper bound, not a count, and this is the case that+ # shows the difference: -1000, +2000, -1000 annually is -1000(x-1)**2 for+ # x = 1/(1+r), so it has ONE distinct root at 0 with multiplicity two, and+ # `ambiguous?` still reports true.+ #+ # That is the documented, deliberate direction -- counting distinct roots+ # would mean solving for all of them on a render path -- and it is pinned+ # here so the docs and the behaviour cannot drift apart again.+ test "ambiguous? is an upper bound, so it can flag a series with one root" do+ xirr = Portfolio::Xirr.new([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 2_000 ],+ [ Date.new(2028, 1, 1), -1_000 ]+ ])++ assert_in_delta 0.0, xirr.send(:present_value, 0.0), 1e-9, "0 solves it"++ # 1e-5 rather than the 1e-9 the residual tolerance would suggest, and the+ # gap is the double root, not slack. Near a simple root the present value+ # falls off linearly with the rate, so a residual of e buys a rate accurate+ # to about e; near a double root it falls off with the SQUARE, so the same+ # residual buys only sqrt(e). Here that is sqrt(4e-9 / 1000), about 2e-6.+ assert_in_delta 0.0, xirr.rate.to_f, 1e-5, "and it is the only rate that does"+ assert_equal 2, xirr.sign_changes+ assert xirr.ambiguous?, "two sign changes, so the bound says 'possibly', not 'is'"+ end++ # The ordinary shape -- money out, money back -- has one sign change and one+ # root, so nothing is hedged for the common case.+ test "an ordinary series is not ambiguous" do+ xirr = Portfolio::Xirr.new([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2026, 6, 1), -500 ],+ [ Date.new(2027, 1, 1), 1_800 ]+ ])++ assert_equal 1, xirr.sign_changes+ assert_not xirr.ambiguous?+ end++ # `flows` is a public reader, and every derived figure on the instance is+ # memoised from it: sign_changes, terms, first_date, residual_tolerance and+ # rate itself. An exposed mutable array lets a caller change the flows the+ # object reports while it goes on answering from the cache built before the+ # change -- 1000 doubling over a year returns 100%, a third flow of -5000 is+ # appended, and the instance still says 100% with one sign change while+ # showing three rows.+ #+ # The Flow objects are Data and already frozen, so the array is the whole of+ # the mutable surface.+ test "the flows a caller can see cannot be changed underneath the figures" do+ xirr = Portfolio::Xirr.new([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2027, 1, 1), 2_000 ]+ ])++ assert_in_delta 1.0, xirr.rate.to_f, 0.0005++ assert xirr.flows.frozen?, "the exposed array is the object's own state"+ assert xirr.flows.all?(&:frozen?), "and so is every row in it"++ assert_raises FrozenError do+ xirr.flows << Portfolio::Xirr::Flow.new(date: Date.new(2028, 1, 1), amount: -5_000.0)+ end+ end++ test "ignores zero amounts" do+ rate = Portfolio::Xirr.rate([+ [ Date.new(2026, 1, 1), -1_000 ],+ [ Date.new(2026, 6, 1), 0 ],+ [ Date.new(2027, 1, 1), 2_000 ]+ ])++ assert_in_delta 1.0, rate.to_f, 0.0005+ end++ test "accepts flow objects as well as pairs" do+ flows = [+ Portfolio::Xirr::Flow.new(date: Date.new(2026, 1, 1), amount: -1_000),+ Portfolio::Xirr::Flow.new(date: Date.new(2027, 1, 1), amount: 2_000)+ ]++ assert_in_delta 1.0, Portfolio::Xirr.rate(flows).to_f, 0.0005+ end++ test "orders flows by date regardless of input order" do+ unordered = Portfolio::Xirr.rate([+ [ Date.new(2027, 1, 1), 2_000 ],+ [ Date.new(2026, 1, 1), -1_000 ]+ ])++ assert_in_delta 1.0, unordered.to_f, 0.0005+ end++ # The control for every test below: the default unit is a year, so nothing+ # that does not ask for a period rate changes.+ test "the rate is annualised unless a unit is asked for" do+ flows = [ [ Date.new(2026, 1, 1), -1_000 ], [ Date.new(2027, 1, 1), 2_000 ] ]++ assert_in_delta 1.0, Portfolio::Xirr.rate(flows).to_f, 0.0005+ assert_equal Portfolio::Xirr::DAYS_PER_YEAR, Portfolio::Xirr.new(flows).days_per_unit+ end++ # A rate over the period is the same root as the annual rate, read in a+ # different unit: (1 + period) ** (days / 365) == 1 + annual. Intermediate+ # flows are in the series because the identity is not special to two flows.+ test "a period rate and the annual rate are the same root in different units" do+ start = Date.new(2026, 3, 2)+ flows = [ [ start, -1_000.0 ], [ start + 10, -500.0 ], [ start + 30, 1_600.0 ] ]++ annual = Portfolio::Xirr.rate(flows).to_f+ period = Portfolio::Xirr.rate(flows, days_per_unit: 30).to_f++ assert_in_delta annual, (1 + period)**(365 / 30.0) - 1, 1e-9+ end++ # Why the period form is solved rather than the annual one de-annualised.+ # A day's gain of this size needs an annual rate of about 7.5e109, which is+ # outside the bracket Newton reaches, so the annual form reports nothing at+ # all. The period form is an ordinary number.+ test "a short period rate is reported where the annual form cannot be solved" do+ start = Date.new(2026, 3, 2)+ flows = [ [ start, -1_000.0 ], [ start + 1, 2_000.0 ] ]++ assert_nil Portfolio::Xirr.rate_or_nil(flows), "the annual form is expected to be unreachable here"+ assert_in_delta 1.0, Portfolio::Xirr.rate(flows, days_per_unit: 1).to_f, 1e-9++ # rate_or_nil is the variant a render path calls, and it must forward the+ # unit. One that dropped it would return nil here -- the assertion above+ # establishes that the annual form is unreachable on this fixture -- so a+ # silently-annualised rate_or_nil cannot pass this line.+ assert_in_delta 1.0, Portfolio::Xirr.rate_or_nil(flows, days_per_unit: 1).to_f, 1e-9+ end++ # An infinite unit is positive, so a bare positivity check lets it through,+ # and it makes every elapsed interval zero: the present value stops depending+ # on the rate and Newton hands back its 10% starting guess as an answer.+ test "a unit that is not a positive finite number of days is refused" do+ flows = [ [ Date.new(2026, 1, 1), -1_000 ], [ Date.new(2027, 1, 1), 2_000 ] ]++ assert_raises(ArgumentError) { Portfolio::Xirr.new(flows, days_per_unit: 0) }+ assert_raises(ArgumentError) { Portfolio::Xirr.new(flows, days_per_unit: -30) }+ assert_raises(ArgumentError) { Portfolio::Xirr.new(flows, days_per_unit: Float::INFINITY) }+ assert_raises(ArgumentError) { Portfolio::Xirr.new(flows, days_per_unit: Float::NAN) }+ end+end