Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/SheetAnalytics/Tests/FinanceModelsTests/CashFlowTests.swift10// Module : FinanceModelsTests11// Repository : https://git.spboucher.ai/orix-sheet12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import Testing89import AnalyticsTestSupport90import Statistics91@testable import FinanceModels9293@Suite struct IRRTests {94 @Test func allRootsMatchPolynomialRoots() throws {95 for (name, c) in financeFixture["irr"].dict {96 let flows = c["flows"].arr97 let r = try CashFlowAnalysis.irr(cashFlows: flows)98 let want = c["roots"].arr99 #expect(r.allRoots.count == want.count, "\(name): found \(r.allRoots) vs \(want)")100 if r.allRoots.count == want.count {101 #expect(allClose(r.allRoots, want, rel: 1e-9, abs: 1e-11), "\(name): \(r.allRoots) vs \(want)")102 }103 #expect(r.signChanges == c["sign_changes"].i, "\(name) sign changes")104 #expect(isClose(CashFlowAnalysis.npv(rate: 0.1, cashFlows: flows), c["npv10"].d, rel: 1e-12, abs: 1e-9), "\(name) NPV")105 #expect(r.converged == !want.isEmpty)106 if let irr = r.irr {107 #expect(abs(r.residual) < 1e-7 * flows.reduce(0) { $0 + abs($1) }, "\(name) residual \(r.residual)")108 #expect(want.contains { isClose($0, irr, rel: 1e-9, abs: 1e-11) })109 }110 #expect(r.allRoots.count <= max(r.signChanges, 0), "\(name): Descartes bound")111 }112 }113114 @Test func multipleRootDiagnostics() throws {115 let two = try CashFlowAnalysis.irr(cashFlows: [-1600, 10000, -10000])116 #expect(allClose(two.allRoots, [0.25, 4.0], rel: 1e-12))117 #expect(two.hasMultipleRoots && two.signChanges == 2 && two.message.contains("Multiple"))118 #expect(isClose(two.irr!, 0.25, rel: 1e-12)) // nearest the default 10 % guess119 #expect(isClose(try CashFlowAnalysis.irr(cashFlows: [-1600, 10000, -10000], guess: 3).irr!, 4.0, rel: 1e-12))120 let three = try CashFlowAnalysis.irr(cashFlows: [-1000, 3600, -4310, 1716])121 #expect(allClose(three.allRoots, [0.1, 0.2, 0.3], rel: 1e-9))122 let none = try CashFlowAnalysis.irr(cashFlows: [100, 200, 300])123 #expect(none.irr == nil && !none.converged && none.signChanges == 0 && none.message.contains("never change sign"))124 let complex = try CashFlowAnalysis.irr(cashFlows: [-100, 100, -100])125 #expect(complex.irr == nil && complex.signChanges == 2 && complex.message.contains("No IRR found"))126 let unique = try CashFlowAnalysis.irr(cashFlows: [-1000, 300, 420, 680])127 #expect(unique.message.contains("Unique") && unique.table().count == 7)128 // tangent (double) root: −100 + 220v − 121v² = −(11v − 10)², r = 10 % exactly, no sign change in NPV129 let tangent = try CashFlowAnalysis.irr(cashFlows: [-100, 220, -121])130 #expect(tangent.allRoots.count == 1 && isClose(tangent.allRoots[0], 0.1, rel: 1e-6))131 // root outside the default range is found once the range is widened132 let big = [-1.0, 30]133 #expect(try CashFlowAnalysis.irr(cashFlows: big).irr == nil)134 #expect(isClose(try CashFlowAnalysis.irr(cashFlows: big, upper: 100).irr!, 29, rel: 1e-12))135 #expect(throws: StatError.self) { try CashFlowAnalysis.irr(cashFlows: [1]) }136 #expect(throws: StatError.self) { try CashFlowAnalysis.irr(cashFlows: [-1, 2], lower: -2) }137 #expect(throws: StatError.self) { try CashFlowAnalysis.irr(cashFlows: [-1, .nan]) }138 }139140 @Test func excelDocumentedExamples() throws {141 // IRR({-70000,12000,15000,18000,21000,26000}) = 8.66 %; first four flows = −2.1 %142 #expect(isClose(try CashFlowAnalysis.irr(cashFlows: [-70000, 12000, 15000, 18000, 21000, 26000]).irr!, 0.0866, abs: 5e-5))143 #expect(isClose(try CashFlowAnalysis.irr(cashFlows: [-70000, 12000, 15000, 18000, 21000]).irr!, -0.021, abs: 5e-4))144 // NPV(10%, -10000, 3000, 4200, 6800) = 1188.44 (Excel discounts the first value)145 #expect(isClose(CashFlowAnalysis.excelNPV(rate: 0.1, values: [-10000, 3000, 4200, 6800]), 1188.44, abs: 5e-3))146 // MIRR({-120000,39000,30000,21000,37000,46000}, 10%, 12%) = 12.61 %147 #expect(isClose(try CashFlowAnalysis.mirr(cashFlows: [-120000, 39000, 30000, 21000, 37000, 46000], financeRate: 0.1, reinvestRate: 0.12), 0.126094, abs: 5e-7))148 // XIRR / XNPV documentation example149 let flows: [Double] = [-10000, 2750, 4250, 3250, 2750]150 let dates = [CalendarDate(2008, 1, 1), CalendarDate(2008, 3, 1), CalendarDate(2008, 10, 30), CalendarDate(2009, 2, 15), CalendarDate(2009, 4, 1)]151 #expect(isClose(try CashFlowAnalysis.xirr(cashFlows: flows, dates: dates).irr!, 0.373362535, abs: 5e-9))152 #expect(isClose(try CashFlowAnalysis.xnpv(rate: 0.09, cashFlows: flows, dates: dates), 2086.647602, abs: 5e-6))153 }154155 @Test func xirrAndMirrReferences() throws {156 for c in financeFixture["xirr"].list {157 let dates = c["dates"].list.map(date)158 let r = try CashFlowAnalysis.xirr(cashFlows: c["flows"].arr, dates: dates)159 #expect(isClose(r.irr!, c["xirr"].d, rel: 1e-10), "xirr \(r.irr!) vs \(c["xirr"].d)")160 #expect(isClose(try CashFlowAnalysis.xnpv(rate: 0.09, cashFlows: c["flows"].arr, dates: dates), c["xnpv9"].d, rel: 1e-12))161 #expect(abs(try CashFlowAnalysis.xnpv(rate: r.irr!, cashFlows: c["flows"].arr, dates: dates)) < 1e-6)162 // unsorted input gives the same answer163 let perm = Array(dates.indices.reversed())164 let shuffled = try CashFlowAnalysis.xirr(cashFlows: perm.map { c["flows"].arr[$0] }, dates: perm.map { dates[$0] })165 #expect(isClose(shuffled.irr!, c["xirr"].d, rel: 1e-10))166 }167 // yearly dated flows on a 365-day grid reproduce the periodic IRR168 let yearly = (0..<4).map { CalendarDate(dayNumber: CalendarDate(2021, 1, 1).dayNumber + 365 * $0) }169 let periodic = try CashFlowAnalysis.irr(cashFlows: [-1000, 300, 420, 680]).irr!170 #expect(isClose(try CashFlowAnalysis.xirr(cashFlows: [-1000, 300, 420, 680], dates: yearly).irr!, periodic, rel: 1e-11))171 let m = financeFixture["mirr"]172 #expect(isClose(try CashFlowAnalysis.mirr(cashFlows: m["flows"].arr, financeRate: m["fin"].d, reinvestRate: m["re"].d), m["mirr"].d, rel: 1e-13))173 #expect(isClose(try CashFlowAnalysis.mirr(cashFlows: financeFixture["irr"]["late_outflow"]["flows"].arr, financeRate: 0.07, reinvestRate: 0.05), m["mirr2"].d, rel: 1e-13))174 #expect(throws: StatError.self) { try CashFlowAnalysis.mirr(cashFlows: [100, 200], financeRate: 0.1, reinvestRate: 0.1) }175 #expect(throws: StatError.self) { try CashFlowAnalysis.xirr(cashFlows: [1, 2], dates: [CalendarDate(2020, 1, 1)]) }176 #expect(CashFlowAnalysis.signChanges([-1, 0, 0, 2, 3, -1, 0, -2, 5]) == 3)177 #expect(CashFlowAnalysis.npv(rate: 0, cashFlows: [-5, 2, 4]) == 1)178 #expect(CashFlowAnalysis.npv(rate: -1.5, cashFlows: [1, 2]).isNaN)179 }180}181182@Suite struct CapitalBudgetingTests {183 let f = financeFixture["capbudget"]184185 @Test func projectMetrics() {186 let rate = f["rate"].d187 for name in ["A", "B"] {188 let c = f[name]189 let m = CapitalBudgeting.metrics(Project(name: name, cashFlows: c["flows"].arr), rate: rate)190 #expect(isClose(m.npv, c["npv"].d, rel: 1e-12), "\(name) npv")191 #expect(isClose(m.irr!, c["irr"].d, rel: 1e-9), "\(name) irr")192 #expect(isClose(m.payback!, c["payback"].d, rel: 1e-13), "\(name) payback")193 #expect(isClose(m.discountedPayback!, c["dpayback"].d, rel: 1e-12), "\(name) discounted payback")194 #expect(isClose(m.profitabilityIndex!, c["pi"].d, rel: 1e-12), "\(name) PI")195 #expect(isClose(m.equivalentAnnualAnnuity!, c["eaa"].d, rel: 1e-12), "\(name) EAA")196 #expect(isClose(m.mirr!, c["mirr"].d, rel: 1e-12), "\(name) MIRR")197 #expect(m.irrCount == 1)198 }199 }200201 @Test func comparisonAndCrossover() {202 let a = Project(name: "A", cashFlows: f["A"]["flows"].arr), b = Project(name: "B", cashFlows: f["B"]["flows"].arr)203 let cmp = CapitalBudgeting.compare([a, b], rate: f["rate"].d)204 let best = f["A"]["npv"].d > f["B"]["npv"].d ? "A" : "B"205 #expect(cmp.bestByNPV == best)206 #expect(Set(cmp.projects.map(\.npvRank)) == [1, 2])207 #expect(cmp.projects.first { $0.name == best }?.npvRank == 1)208 #expect(allClose(cmp.crossoverRates, f["crossover"].arr, rel: 1e-9))209 // at the crossover rate both NPVs coincide210 if let x = cmp.crossoverRates.first {211 #expect(isClose(CashFlowAnalysis.npv(rate: x, cashFlows: a.cashFlows), CashFlowAnalysis.npv(rate: x, cashFlows: b.cashFlows), rel: 1e-9, abs: 1e-7))212 }213 #expect(cmp.table().count == 5 && cmp.table()[0].count == 10)214 }215216 @Test func paybackEdgeCases() {217 #expect(CapitalBudgeting.payback(cashFlows: [-1000, 400, 400, 400]) == 2.5)218 #expect(CapitalBudgeting.payback(cashFlows: [-1000, 500, 500]) == 2)219 #expect(CapitalBudgeting.payback(cashFlows: [-1000, 100, 100]) == nil)220 #expect(CapitalBudgeting.payback(cashFlows: [50, 10]) == 0)221 #expect(CapitalBudgeting.discountedPayback(cashFlows: [-1000, 500, 500], rate: 0.1) == nil)222 #expect(CapitalBudgeting.discountedPayback(cashFlows: [-1000, 500, 500], rate: 0) == 2)223 #expect(CapitalBudgeting.profitabilityIndex(cashFlows: [100, 50], rate: 0.1) == nil)224 #expect(isClose(CapitalBudgeting.profitabilityIndex(cashFlows: [-100, 110], rate: 0.1)!, 1, rel: 1e-14))225 #expect(CapitalBudgeting.equivalentAnnualAnnuity(cashFlows: [-100], rate: 0.1) == nil)226 #expect(isClose(CapitalBudgeting.equivalentAnnualAnnuity(cashFlows: [-100, 60, 60], rate: 0)!, 10, rel: 1e-14))227 }228229 @Test func breakEven() {230 let b = BreakEven.analyze(fixedCosts: 120_000, pricePerUnit: 50, variableCostPerUnit: 30, targetProfit: 40_000, actualUnits: 10_000)231 #expect(b.contributionMargin == 20 && b.contributionMarginRatio == 0.4)232 #expect(b.breakEvenUnits == 6000 && b.breakEvenRevenue == 300_000)233 #expect(b.unitsForTargetProfit == 8000)234 #expect(b.marginOfSafety == 0.4)235 #expect(b.operatingLeverage == 2.5) // 200,000 contribution / 80,000 profit236 #expect(b.table().count == 10)237 let chart = b.chartData(maxUnits: 12_000, steps: 12)238 #expect(chart.count == 13 && chart[6].profit == 0 && chart[0].profit == -120_000 && chart[12].revenue == 600_000)239 let none = BreakEven.analyze(fixedCosts: 1000, pricePerUnit: 10, variableCostPerUnit: 12)240 #expect(none.breakEvenUnits == nil && none.breakEvenRevenue == nil && none.unitsForTargetProfit == nil && none.marginOfSafety == nil)241 // sales mix 3:1, margins 10 and 30 → weighted margin 15; 90,000 / 15 = 6,000 units242 let mix = BreakEven.salesMix(fixedCosts: 90_000, products: [.init(name: "Std", price: 40, variableCost: 30, mixWeight: 3), .init(name: "Pro", price: 100, variableCost: 70, mixWeight: 1)])243 #expect(mix?.totalUnits == 6000 && mix?.unitsByProduct == [4500, 1500] && mix?.revenue == 330_000)244 #expect(BreakEven.salesMix(fixedCosts: 1, products: [.init(name: "x", price: 1, variableCost: 2, mixWeight: 1)]) == nil)245 }246}247