SPB Git

Repository Public MIT

TVMCashFlowTests.swift 19.1 KB 310 lines swift

1// ORIX Calc2// File: Packages/ORIXFinancial/Tests/ORIXFinancialTests/TVMCashFlowTests.swift3// Description: Tests for the TVM solver, rate conversion, dates and the cash-flow worksheet against independent references.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXNumerics10@testable import ORIXFinancial1112@Suite struct TVMTests {13    static func inputs(_ c: JSON) -> TVMInputs {14        TVMInputs(n: c.num("n"), iy: c.num("iy"), pv: c.num("pv"), pmt: c.num("pmt"), fv: c.num("fv"),15                  py: c.num("py"), cy: c.num("cy"), timing: c.bool("begin") ? .begin : .end)16    }1718    /// Every reference case (FV obtained in Python by compounding period by period in 50 digits) is solved for each of the five variables.19    @Test func solvesEveryVariableOfEveryReferenceCase() throws {20        let cases = Ref.list("tvm")21        #expect(cases.count >= 11)22        for c in cases {23            let full = Self.inputs(c)24            #expect(try close(TVM.periodicRate(iy: full.iy, py: full.py, cy: full.cy), c.num("periodic_rate"), 1e-14), "\(c.str("name"))")25            for v in TVMVariable.allCases {26                var t = full27                t[v] = .nan   // the solved variable must be ignored28                let r = try TVM.solve(for: v, t)29                // I/Y is in percent and is the worst-conditioned unknown; N of a zero-payment lump sum is exact.30                let tol = v == .iy ? 1e-8 : 1e-931                #expect(close(r.value, full[v], tol), "\(c.str("name")) solve \(v.label): got \(r.value), expected \(full[v])")32                #expect(r.inputs[v] == r.value)33                #expect(r.verification.isVerified, "\(c.str("name")) \(v.label): \(r.verification.warnings)")34                #expect(r.explanation.plainText.contains(v.label))35            }36        }37    }3839    @Test func textbookValues() throws {40        // 100 000 at 6% nominal monthly over 30 years: payment 599.55.41        let pmt = try TVM.solve(for: .pmt, TVMInputs(n: 360, iy: 6, pv: 100_000, fv: 0, py: 12)).value42        #expect(abs(pmt - (-599.5505251527569)) < 1e-9)43        // 1 000 at 5% for 10 years: 1 628.89.44        let fv = try TVM.solve(for: .fv, TVMInputs(n: 10, iy: 5, pv: -1000)).value45        #expect(abs(fv - 1628.894626777442) < 1e-9)46        // Doubling time at 7%: ln 2 / ln 1.07.47        let n = try TVM.solve(for: .n, TVMInputs(iy: 7, pv: -1, fv: 2)).value48        #expect(abs(n - log(2.0) / log(1.07)) < 1e-12)49        // Canadian mortgage as a TVM problem: P/Y = 12, C/Y = 2.50        let cdn = try TVM.solve(for: .pmt, TVMInputs(n: 300, iy: 5, pv: 300_000, py: 12, cy: 2)).value51        #expect((cdn * 100).rounded() / 100 == -1744.81)52    }5354    @Test func beginVersusEnd() throws {55        let end = try TVM.solve(for: .pv, TVMInputs(n: 15, iy: 6, pmt: -500, timing: .end)).value56        let begin = try TVM.solve(for: .pv, TVMInputs(n: 15, iy: 6, pmt: -500, timing: .begin)).value57        #expect(close(begin, end * 1.06, 1e-13))58        #expect(close(begin, Ref.object("returns").num("pv_annuity_due_500_6pct_15"), 1e-12))59        let fvEnd = try TVM.solve(for: .fv, TVMInputs(n: 15, iy: 6, pmt: -500)).value60        #expect(close(fvEnd, Ref.object("returns").num("fv_annuity_ord_500_6pct_15"), 1e-12))61    }6263    @Test func paymentsPerYearDifferentFromCompounding() throws {64        let i = try TVM.periodicRate(iy: 5, py: 12, cy: 2)65        #expect(abs(i - (pow(1.025, 1.0 / 6) - 1)) < 1e-16)66        #expect(abs(TVM.nominalRatePercent(periodicRate: i, py: 12, cy: 2) - 5) < 1e-12)67        // cy defaults to py68        #expect(TVMInputs(py: 12).cy == 12)69    }7071    @Test func zeroRateIsExact() throws {72        let t = TVMInputs(n: 48, iy: 0, pv: 12_000, pmt: -250, fv: 0, py: 12)73        #expect(try TVM.solve(for: .pmt, t).value == -250)74        #expect(try TVM.solve(for: .n, t).value == 48)75        #expect(try TVM.solve(for: .pv, t).value == 12_000)76        #expect(try TVM.solve(for: .fv, t).value == 0)77        #expect(try TVM.solve(for: .iy, t).value == 0)78        #expect(try TVM.residual(t) == 0)79    }8081    @Test func negativeRates() throws {82        let fv = try TVM.solve(for: .fv, TVMInputs(n: 5, iy: -1.5, pv: -1000)).value83        #expect(close(fv, 1000 * pow(0.985, 5), 1e-13))84        let iy = try TVM.solve(for: .iy, TVMInputs(n: 5, pv: -1000, fv: fv)).value85        #expect(abs(iy - (-1.5)) < 1e-9)86    }8788    @Test func rateWithMultipleSolutionsIsRefused() {89        // −1000 + 2300·v − 1320·v² = 0 has v = 1/1.1 and 1/1.2: I/Y = 10% and 20%.90        expectFinancialError({ _ = try TVM.solve(for: .iy, TVMInputs(n: 2, pv: -1000, pmt: 2300, fv: -3620)) }) {91            guard case .multipleSolutions(let c, _) = $0 else { return false }92            return c.count == 2 && abs(c[0] - 10) < 1e-7 && abs(c[1] - 20) < 1e-793        }94    }9596    @Test func noSolutionCases() {97        expectFinancialError({ _ = try TVM.solve(for: .iy, TVMInputs(n: 10, pv: 100, pmt: 10, fv: 50)) }) { if case .noSolution = $0 { true } else { false } }98        expectFinancialError({ _ = try TVM.solve(for: .iy, TVMInputs(n: 10)) }) { if case .noSolution = $0 { true } else { false } }99        expectFinancialError({ _ = try TVM.solve(for: .n, TVMInputs(iy: 5, pv: -100, pmt: -10, fv: -5)) }) { if case .noSolution = $0 { true } else { false } }100        expectFinancialError({ _ = try TVM.solve(for: .n, TVMInputs(iy: 0, pv: -100, fv: 200)) }) { if case .noSolution = $0 { true } else { false } }101        expectFinancialError({ _ = try TVM.solve(for: .pmt, TVMInputs(n: 0, iy: 5, pv: 100)) }) { if case .noSolution = $0 { true } else { false } }102        // a loan whose payment does not cover the interest is never repaid103        expectFinancialError({ _ = try TVM.solve(for: .n, TVMInputs(iy: 12, pv: 100_000, pmt: -500, fv: 0, py: 12)) }) { if case .noSolution = $0 { true } else { false } }104    }105106    @Test func invalidInputs() {107        expectFinancialError({ _ = try TVM.solve(for: .fv, TVMInputs(n: 10, iy: 5, pv: -1, py: 0)) }) { if case .invalidInput = $0 { true } else { false } }108        expectFinancialError({ _ = try TVM.solve(for: .fv, TVMInputs(n: 10, iy: -100, pv: -1)) }) { if case .invalidInput = $0 { true } else { false } }109        expectFinancialError({ _ = try TVM.solve(for: .fv, TVMInputs(n: .infinity, iy: 5, pv: -1)) }) { if case .invalidInput = $0 { true } else { false } }110        expectFinancialError({ _ = try TVM.solve(for: .fv, TVMInputs(n: -3, iy: 5, pv: -1)) }) { if case .invalidInput = $0 { true } else { false } }111        expectFinancialError({ _ = try TVM.solve(for: .fv, TVMInputs(n: 1e7, iy: 900, pv: -1)) }) { if case .nonConvergence = $0 { true } else { false } }112    }113114    @Test func fractionalNIsFlagged() throws {115        let r = try TVM.solve(for: .n, TVMInputs(iy: 6, pv: 10_000, pmt: -300, py: 12))116        #expect(r.value > 36 && r.value < 37)117        #expect(r.verification.status == .warning)118        #expect(try abs(TVM.residual(r.inputs)) < 1e-8)119    }120121    @Test func rateConversions() throws {122        let ref = Ref.object("rates")123        #expect(try close(RateConversion.effectiveAnnual(nominal: 0.06, compounding: .periodic(12)), ref.num("eff_6_monthly"), 1e-15))124        #expect(try close(RateConversion.effectiveAnnual(nominal: 0.06, compounding: .continuous), ref.num("eff_6_continuous"), 1e-15))125        #expect(try close(RateConversion.nominal(effectiveAnnual: 0.05, compounding: .periodic(2)), ref.num("nom_semi_from_eff_5"), 1e-15))126        #expect(try close(RateConversion.nominal(effectiveAnnual: 0.05, compounding: .continuous), ref.num("nom_cont_from_eff_5"), 1e-15))127        #expect(try close(RateConversion.convert(nominal: 0.05, from: .periodic(2), to: .periodic(12)), ref.num("monthly_from_semi_5"), 1e-15))128        let back = try RateConversion.convert(nominal: try RateConversion.convert(nominal: 0.0725, from: .periodic(4), to: .continuous), from: .continuous, to: .periodic(4))129        #expect(abs(back - 0.0725) < 1e-15)130        expectFinancialError({ _ = try RateConversion.effectiveAnnual(nominal: 0.05, compounding: .periodic(0)) }) { if case .invalidInput = $0 { true } else { false } }131        expectFinancialError({ _ = try RateConversion.nominal(effectiveAnnual: -1, compounding: .continuous) }) { if case .invalidInput = $0 { true } else { false } }132    }133134    @Test func tinyRatesKeepPrecision() throws {135        let pv = try Annuity.presentValue(payment: 100, rate: 1e-10, periods: 360)136        #expect(close(pv, Ref.object("returns").num("pv_annuity_tiny_rate"), 1e-13))137    }138}139140@Suite struct FinancialDateTests {141    @Test func serialRoundTripAndLeapYears() throws {142        #expect(try FinancialDate(year: 1970, month: 1, day: 1).serial == 0)143        #expect(try FinancialDate(year: 2000, month: 3, day: 1).serial == 11_017)144        for s in stride(from: -200_000, through: 200_000, by: 37) {145            let d = FinancialDate(serial: s)146            #expect(d.serial == s)147            #expect(d.day <= FinancialDate.daysInMonth(year: d.year, month: d.month))148        }149        #expect(FinancialDate.isLeapYear(2000) && FinancialDate.isLeapYear(2024) && !FinancialDate.isLeapYear(1900) && !FinancialDate.isLeapYear(2023))150        #expect(date("2024-02-28").days(to: date("2024-03-01")) == 2)151        #expect(date("2023-02-28").days(to: date("2023-03-01")) == 1)152        #expect(date("2024-12-31").addingDays(1) == date("2025-01-01"))153        #expect(date("2024-01-05") < date("2024-01-06"))154        #expect("\(date("2024-03-09"))" == "2024-03-09")155    }156157    @Test func foundationCalendarAgrees() throws {158        var cal = Calendar(identifier: .gregorian)159        cal.timeZone = TimeZone(identifier: "UTC")!160        for (y, m, d) in [(1999, 12, 31), (2024, 2, 29), (2031, 7, 15), (1970, 1, 1), (2100, 3, 1)] {161            let fd = try FinancialDate(year: y, month: m, day: d)162            let foundation = cal.date(from: DateComponents(year: y, month: m, day: d))!163            #expect(Double(fd.serial) * 86_400 == foundation.timeIntervalSince1970)164            #expect(try FinancialDate(fd.dateComponents) == fd)165        }166    }167168    @Test func invalidDatesAreRejected() {169        expectFinancialError({ _ = try FinancialDate(year: 2025, month: 2, day: 29) }) { if case .invalidInput = $0 { true } else { false } }170        expectFinancialError({ _ = try FinancialDate(year: 2025, month: 13, day: 1) }) { if case .invalidInput = $0 { true } else { false } }171        expectFinancialError({ _ = try FinancialDate(DateComponents(year: 2025)) }) { if case .invalidInput = $0 { true } else { false } }172    }173174    @Test func addingMonths() {175        #expect(date("2024-08-31").addingMonths(-6) == date("2024-02-29"))176        #expect(date("2024-02-29").addingMonths(6) == date("2024-08-29"))177        #expect(date("2024-02-29").addingMonths(6, endOfMonth: true) == date("2024-08-31"))178        #expect(date("2025-01-15").addingMonths(-14) == date("2023-11-15"))179        #expect(date("2025-11-30").addingMonths(3, endOfMonth: true) == date("2026-02-28"))180    }181182    /// Each convention against the Python reference (datetime for actual days, independent 30/360 code).183    @Test func dayCountConventions() throws {184        let cases = Ref.list("daycounts")185        #expect(cases.count >= 10)186        for c in cases {187            for conv in DayCountConvention.allCases {188                #expect(conv.dayCount(from: date(c.str("a")), to: date(c.str("b"))) == c.int(conv.rawValue), "\(conv) \(c.str("a")) → \(c.str("b"))")189            }190        }191        let a = date("2025-01-31"), b = date("2025-07-31")192        #expect(try DayCountConvention.thirty360US.yearFraction(from: a, to: b) == 0.5)193        #expect(try DayCountConvention.thirtyE360.yearFraction(from: a, to: b) == 0.5)194        #expect(try DayCountConvention.actual360.yearFraction(from: a, to: b) == 181.0 / 360)195        #expect(try DayCountConvention.actual365Fixed.yearFraction(from: a, to: b) == 181.0 / 365)196        let period = CouponPeriod(start: a, end: b, frequency: 2)197        #expect(try DayCountConvention.actualActualICMA.yearFraction(from: a, to: b, in: period) == 0.5)198        #expect(try DayCountConvention.actualActualICMA.yearFraction(from: a, to: date("2025-03-02"), in: period) == 30.0 / 362)199        expectFinancialError({ _ = try DayCountConvention.actualActualICMA.yearFraction(from: a, to: b) }) { if case .invalidInput = $0 { true } else { false } }200        // the two 30/360 variants differ when the end date is a 31st and the start is not a 30th/31st201        #expect(DayCountConvention.thirty360US.dayCount(from: date("2025-01-15"), to: date("2025-03-31")) == 76)202        #expect(DayCountConvention.thirtyE360.dayCount(from: date("2025-01-15"), to: date("2025-03-31")) == 75)203    }204}205206@Suite struct CashFlowTests {207    @Test func referenceCases() throws {208        let cases = Ref.list("cashflows")209        #expect(cases.count >= 8)210        for c in cases {211            let name = c.str("name")212            let s = CashFlowSeries(flows: c.nums("flows"))213            let rate = c.num("rate")214            #expect(try close(s.npv(rate: rate), c.num("npv"), 1e-12), "\(name) npv")215            #expect(try close(s.nfv(rate: rate), c.num("nfv"), 1e-12), "\(name) nfv")216            let explained = try s.npvExplained(rate: rate)217            #expect(try explained.value == (s.npv(rate: rate)) && explained.verification.isVerified)218            let irr = try s.irr()219            let expected = c.nums("irrs")220            #expect(irr.rates.count == expected.count, "\(name): found \(irr.rates), expected \(expected)")221            for (a, b) in zip(irr.rates, expected) { #expect(abs(a - b) < 1e-10, "\(name) irr \(a) vs \(b)") }222            switch irr.outcome {223            case .unique: #expect(expected.count == 1)224            case .multiple: #expect(expected.count > 1)225            case .none: #expect(expected.isEmpty)226            }227            #expect(!irr.verification.checks.contains { $0.status == .failed }, "\(name)")228            if let m = c.optionalNum("mirr") {229                #expect(try close(s.mirr(financeRate: c.num("mirr_fin"), reinvestmentRate: c.num("mirr_re")), m, 1e-13), "\(name) mirr")230            }231            if let pi = c.optionalNum("pi") { #expect(try close(s.profitabilityIndex(rate: rate), pi, 1e-12), "\(name) PI") }232            let pb = try s.payback(), dpb = try s.discountedPayback(rate: rate)233            #expect((pb == nil) == (c.optionalNum("payback") == nil), "\(name) payback")234            if let pb, let e = c.optionalNum("payback") { #expect(close(pb, e, 1e-12)) }235            #expect((dpb == nil) == (c.optionalNum("discounted_payback") == nil), "\(name) discounted payback")236            if let dpb, let e = c.optionalNum("discounted_payback") { #expect(close(dpb, e, 1e-11)) }237        }238    }239240    @Test func multipleIRRsAreReportedDistinctly() throws {241        let r = try CashFlowSeries(flows: [-1000, 2300, -1320]).irr()242        guard case .multiple(let rates) = r.outcome else { Issue.record("expected multiple IRRs, got \(r.outcome)"); return }243        #expect(rates.count == 2 && abs(rates[0] - 0.10) < 1e-12 && abs(rates[1] - 0.20) < 1e-12)244        #expect(r.descartesSignChanges == 2)245        #expect(r.verification.checks.contains { $0.name == "Descartes sign changes" && $0.detail.contains("2 sign change") })246        #expect(r.verification.status == .warning)247        expectFinancialError({ _ = try r.uniqueRate() }) { if case .multipleIRR(let x) = $0 { x.count == 2 } else { false } }248        #expect(FinancialError.multipleIRR(rates).description.contains("10.0000%"))249    }250251    @Test func noRealIRRIsReportedDistinctly() throws {252        // 1000 − 3000x + 2500x² has a negative discriminant: two sign changes but no real root.253        let r = try CashFlowSeries(flows: [1000, -3000, 2500]).irr()254        guard case .none = r.outcome else { Issue.record("expected no IRR, got \(r.outcome)"); return }255        #expect(r.descartesSignChanges == 2 && r.rates.isEmpty)256        expectFinancialError({ _ = try r.uniqueRate() }) { if case .noRealIRR = $0 { true } else { false } }257        // no sign change at all258        let same = try CashFlowSeries(flows: [100, 200, 300]).irr()259        guard case .none(let reason) = same.outcome else { Issue.record("expected none"); return }260        #expect(same.descartesSignChanges == 0 && reason.contains("same sign"))261    }262263    @Test func uniqueIRRAndVerification() throws {264        let r = try CashFlowSeries(flows: [-10_000, 3000, 4200, 6800]).irr()265        let rate = try r.uniqueRate()266        #expect(try abs(CashFlowSeries(flows: [-10_000, 3000, 4200, 6800]).npv(rate: rate)) < 1e-9)267        #expect(r.descartesSignChanges == 1 && r.verification.isVerified)268        #expect(r.explanation.plainText.contains("Descartes"))269        // IRR of exactly zero and of −50%270        #expect(try CashFlowSeries(flows: [-100, 40, 60]).irr().uniqueRate() == 0)271        #expect(try abs(CashFlowSeries(flows: [-100, 50]).irr().uniqueRate() - (-0.5)) < 1e-14)272        // very large IRR273        #expect(try abs(CashFlowSeries(flows: [-1, 500]).irr().uniqueRate() - 499) < 1e-8)274    }275276    @Test func doubleRootIsFound() throws {277        // −1000 + 2200x − 1210x² = −1000(1 − 1.1x)²: NPV touches zero at 10% without changing sign.278        let r = try CashFlowSeries(flows: [-1000, 2200, -1210]).irr()279        #expect(r.rates.count == 1)280        if let rate = r.rates.first { #expect(abs(rate - 0.10) < 1e-6) }281    }282283    @Test func groupedFlowsAndLongSeries() throws {284        let c = Ref.object("cashflow_long")285        let s = CashFlowSeries(initial: c.num("initial"), groups: [CashFlowGroup(amount: c.num("amount"), count: c.int("count"))])286        #expect(s.flows.count == 361)287        #expect(try abs(s.irr().uniqueRate() - c.num("irr")) < 1e-12)288        #expect(try close(s.npv(rate: 0.004), c.num("npv_at_0004"), 1e-12))289        let g = CashFlowSeries(initial: -50_000, groups: [.init(amount: 12_000, count: 5), .init(amount: 20_000)])290        #expect(g.flows == [-50_000, 12_000, 12_000, 12_000, 12_000, 12_000, 20_000])291    }292293    @Test func invalidInputs() {294        let s = CashFlowSeries(flows: [-100, 60, 60])295        expectFinancialError({ _ = try s.npv(rate: -1) }) { if case .invalidInput = $0 { true } else { false } }296        expectFinancialError({ _ = try s.npv(rate: .nan) }) { if case .invalidInput = $0 { true } else { false } }297        expectFinancialError({ _ = try CashFlowSeries(initial: -1, groups: [.init(amount: 1, count: 0)]).irr() }) { if case .invalidInput = $0 { true } else { false } }298        expectFinancialError({ _ = try CashFlowSeries(initial: -1, groups: [.init(amount: 1, count: 30_000)]).irr() }) { if case .invalidInput = $0 { true } else { false } }299        expectFinancialError({ _ = try CashFlowSeries(flows: [100, 60]).profitabilityIndex(rate: 0.1) }) { if case .invalidInput = $0 { true } else { false } }300        expectFinancialError({ _ = try CashFlowSeries(flows: [100, 60]).mirr(financeRate: 0.1, reinvestmentRate: 0.1) }) { if case .noSolution = $0 { true } else { false } }301        expectFinancialError({ _ = try CashFlowSeries(flows: [-100]).irr() }) { if case .invalidInput = $0 { true } else { false } }302    }303304    @Test func paybackNeverRecovered() throws {305        #expect(try CashFlowSeries(flows: [-1000, 100, 100]).payback() == nil)306        #expect(try CashFlowSeries(flows: [-1000, 400, 400, 400]).payback() == 2.5)307        #expect(try CashFlowSeries(flows: [-1000, 400, 400, 400]).discountedPayback(rate: 0.2) == nil)308    }309}310
Files main
Menu

Theme