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/TVMLoanTests.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 FinanceModels9293let financeFixture = Fixture.load("finance", .module)9495func dec(_ s: String) -> Decimal { Decimal(string: s, locale: Locale(identifier: "en_US_POSIX"))! }96func date(_ j: JSON) -> CalendarDate { CalendarDate(j[0].i, j[1].i, j[2].i) }9798@Suite struct TVMTests {99 func inputs(_ c: JSON) -> TVMInputs {100 let comp: Compounding = c["cpy"].s == "cont" ? .continuous : .perYear(c["cpy"].d)101 return TVMInputs(periods: c["n"].d, annualRate: c["rate"].d, presentValue: c["pv"].d, payment: c["pmt"].d, futureValue: c["fv"].d,102 paymentsPerYear: c["ppy"].d, compounding: comp, timing: c["begin"].b ? .begin : .end)103 }104105 @Test func solvesEveryVariable() throws {106 for c in financeFixture["tvm"].list {107 let inp = inputs(c)108 let fv = try TVM.solve(inp, for: .futureValue)109 #expect(isClose(fv.futureValue, c["fv"].d, rel: 1e-11, abs: 1e-7), "FV \(c["n"].d)")110 #expect(isClose(fv.periodicRate, c["periodic"].d, rel: 1e-12, abs: 1e-18))111 #expect(isClose(fv.effectiveAnnualRate, c["ear"].d, rel: 1e-11, abs: 1e-16))112 let pv = try TVM.solve(inp, for: .presentValue)113 #expect(isClose(pv.presentValue, c["pv_solved"].d, rel: 1e-11, abs: 1e-7))114 #expect(isClose(pv.presentValue, c["pv"].d, rel: 1e-11, abs: 1e-7))115 let pmt = try TVM.solve(inp, for: .payment)116 #expect(isClose(pmt.payment, c["pmt_solved"].d, rel: 1e-10, abs: 1e-8))117 if !c["n_solved"].isNull {118 let n = try TVM.solve(inp, for: .periods)119 #expect(isClose(n.periods, c["n_solved"].d, rel: 1e-9), "N \(n.periods) vs \(c["n_solved"].d)")120 #expect(isClose(n.periods, c["n"].d, rel: 1e-9))121 }122 var noRate = inp123 noRate.annualRate = nil124 let r = try TVM.solve(noRate, for: .rate)125 #expect(isClose(r.periodicRate, c["i_solved"].d, rel: 1e-9, abs: 1e-13), "rate \(r.periodicRate) vs \(c["i_solved"].d)")126 #expect(isClose(r.annualRate, c["rate"].d, rel: 1e-9, abs: 1e-12), "nominal \(r.annualRate) vs \(c["rate"].d)")127 #expect(r.solvedFor == .rate && r.table().count == 10)128 }129 }130131 @Test func textbookValues() throws {132 // $200,000 at 6 % for 30 years, monthly: payment 1,199.10 (standard mortgage table value)133 let pmt = TVM.payment(rate: 0.06 / 12, periods: 360, presentValue: 200_000)134 #expect(isClose(pmt, -1199.1010503, rel: 1e-9))135 // 1,000 for 10 years at 5 % annual → 1,628.894627136 #expect(isClose(TVM.futureValue(rate: 0.05, periods: 10, payment: 0, presentValue: -1000), 1000 * pow(1.05, 10), rel: 1e-14))137 // annuity due is worth (1+i) times the ordinary annuity138 let ord = TVM.presentValue(rate: 0.04, periods: 15, payment: -100, futureValue: 0)139 let due = TVM.presentValue(rate: 0.04, periods: 15, payment: -100, futureValue: 0, timing: .begin)140 #expect(isClose(due, ord * 1.04, rel: 1e-14))141 // rule of 72 sanity: doubling at 8 % takes ln2/ln1.08 periods142 #expect(isClose(try TVM.periods(rate: 0.08, payment: 0, presentValue: -1, futureValue: 2), log(2) / log(1.08), rel: 1e-14))143 // zero-rate limits144 #expect(TVM.payment(rate: 0, periods: 10, presentValue: 1000) == -100)145 #expect(TVM.futureValue(rate: 0, periods: 10, payment: -50, presentValue: 0) == 500)146 }147148 @Test func rateConversions() {149 let f = financeFixture["rates"]150 #expect(isClose(TVM.effectiveAnnualRate(nominal: 0.06, compounding: .perYear(2)), f["ear_6_semi"].d, rel: 1e-13))151 #expect(isClose(TVM.effectiveAnnualRate(nominal: 0.06, compounding: .perYear(12)), f["ear_6_monthly"].d, rel: 1e-13))152 #expect(isClose(TVM.effectiveAnnualRate(nominal: 0.06, compounding: .continuous), f["ear_6_cont"].d, rel: 1e-13))153 #expect(isClose(TVM.nominalRate(effective: 0.08, compounding: .perYear(12)), f["nominal_monthly_from_ear_8"].d, rel: 1e-13))154 #expect(isClose(TVM.nominalRate(effective: 0.08, compounding: .continuous), f["nominal_cont_from_ear_8"].d, rel: 1e-13))155 // round trip periodic ↔ nominal with compounding ≠ payment frequency156 let i = TVM.periodicRate(nominal: 0.0725, compounding: .perYear(2), paymentsPerYear: 26)157 #expect(isClose(TVM.nominalRate(periodic: i, compounding: .perYear(2), paymentsPerYear: 26), 0.0725, rel: 1e-13))158 #expect(isClose(pow(1 + i, 26), pow(1 + 0.0725 / 2, 2), rel: 1e-13))159 #expect(TVM.periodicRate(nominal: 0.06, compounding: .perYear(12), paymentsPerYear: 12) == 0.005)160 }161162 @Test func errorsAndEdgeCases() {163 #expect(throws: StatError.self) { try TVM.solve(TVMInputs(periods: 10, presentValue: 100, payment: 10, futureValue: 0), for: .rate) } // same signs164 #expect(throws: StatError.self) { try TVM.solve(TVMInputs(periods: 10, annualRate: 0.05, payment: 10), for: .futureValue) } // PV missing165 #expect(throws: StatError.self) { try TVM.solve(TVMInputs(annualRate: 0.12, presentValue: 100_000, payment: -500, futureValue: 0), for: .periods) } // payment < interest166 #expect(throws: StatError.self) { try TVM.solve(TVMInputs(periods: 10, annualRate: 0.05, presentValue: 1, payment: 0, futureValue: 0, paymentsPerYear: 0), for: .payment) }167 #expect(throws: StatError.self) { try TVM.periods(rate: 0, payment: 0, presentValue: 100) }168 }169170 @Test func rateSolverPrefersGuessAndConverges() throws {171 // lease-style flows: receive 10,000, pay 1,000 × 12, a known rate of 2.9228541 % per period172 let s = try TVM.rate(periods: 12, payment: -1000, presentValue: 10_000)173 #expect(s.converged && abs(s.residual) < 1e-6)174 #expect(isClose(TVM.presentValue(rate: s.rate, periods: 12, payment: -1000, futureValue: 0), 10_000, rel: 1e-12))175 // negative rate: pay 1,000 and get 90 back × 10176 let neg = try TVM.rate(periods: 10, payment: 90, presentValue: -1000)177 #expect(neg.rate < 0 && isClose(TVM.presentValue(rate: neg.rate, periods: 10, payment: 90, futureValue: 0), -1000, rel: 1e-12))178 }179}180181@Suite struct AmortizationTests {182 let am = financeFixture["amort"]183184 func compare(_ s: AmortizationSchedule, _ f: JSON, _ name: String, rows: [Int]? = nil) {185 let expected = f["rows"].list186 let idx = rows ?? Array(s.rows.indices)187 #expect(idx.count == expected.count, "\(name) row count")188 for (k, i) in idx.enumerated() where k < expected.count {189 let e = expected[k].list, r = s.rows[i]190 #expect(r.period == e[0].i, "\(name) period")191 #expect(r.payment == dec(e[1].s), "\(name) #\(r.period) payment \(r.payment) vs \(e[1].s)")192 #expect(r.interest == dec(e[2].s), "\(name) #\(r.period) interest \(r.interest) vs \(e[2].s)")193 #expect(r.principal == dec(e[3].s), "\(name) #\(r.period) principal")194 #expect(r.extra == dec(e[4].s), "\(name) #\(r.period) extra")195 #expect(r.balance == dec(e[5].s), "\(name) #\(r.period) balance \(r.balance) vs \(e[5].s)")196 }197 #expect(s.totalInterest == dec(f["total_interest"].s), "\(name) total interest \(s.totalInterest)")198 #expect(s.totalExtra == dec(f["total_extra"].s), "\(name) total extra")199 #expect(s.balloonPayment == dec(f["balloon"].s), "\(name) balloon")200 #expect(s.numberOfPayments == f["count"].i, "\(name) count")201 #expect(s.rows.last?.balance == 0, "\(name) ends at zero")202 }203204 @Test func fixedPayment() throws {205 let s = try Amortization.schedule(LoanTerms(principal: 10_000, annualRate: 0.075, periods: 12))206 compare(s, am["fixed_12"], "fixed_12")207 #expect(s.scheduledPayment == dec(am["fixed_12"]["payment"].s))208 #expect(s.totalPrincipal == 10_000)209 #expect(s.totalPaid == s.totalInterest + 10_000)210 // every regular payment equals the scheduled one; only the last absorbs the rounding residue211 #expect(s.rows.dropLast().allSatisfy { $0.payment == s.scheduledPayment })212 #expect(s.rows.last!.payment - s.scheduledPayment == s.finalPaymentAdjustment)213 #expect(abs(Money.double(s.finalPaymentAdjustment)) < 0.12)214 #expect(s.table().count == 14 && s.table()[0].count == 6)215 }216217 @Test func thirtyYearMortgage() throws {218 let s = try Amortization.schedule(LoanTerms(principal: 200_000, annualRate: 0.06, periods: 360))219 #expect(s.scheduledPayment == dec("1199.10"))220 compare(s, am["fixed_360"], "fixed_360", rows: [0, 1, 2, 357, 358, 359])221 #expect(s.rows[0].interest == dec("1000.00") && s.rows[0].principal == dec("199.10"))222 #expect(s.rows.reduce(Decimal(0)) { $0 + $1.principal } == 200_000)223 }224225 @Test func otherStructures() throws {226 let fp = try Amortization.schedule(LoanTerms(principal: 25_000, annualRate: 0.09, periods: 8, paymentsPerYear: 4, type: .fixedPrincipal))227 compare(fp, am["fixed_principal_8"], "fixed_principal")228 #expect(fp.rows.allSatisfy { $0.principal == dec("3125.00") })229 #expect(fp.rows[0].payment > fp.rows[7].payment)230231 let io = try Amortization.schedule(LoanTerms(principal: 50_000, annualRate: 0.048, periods: 6, type: .interestOnly))232 compare(io, am["interest_only_6"], "interest_only")233 #expect(io.rows.dropLast().allSatisfy { $0.principal == 0 && $0.payment == dec("200.00") })234 #expect(io.rows.last!.payment == dec("50200.00"))235236 let bl = try Amortization.schedule(LoanTerms(principal: 80_000, annualRate: 0.0625, periods: 24, type: .balloon(60_000)))237 compare(bl, am["balloon_24"], "balloon")238 #expect(bl.scheduledPayment == dec(am["balloon_24"]["payment"].s))239 #expect(abs(Money.double(bl.balloonPayment) - 60_000) < 0.5) // the balloon absorbs the cents240 #expect(bl.rows.last!.payment == bl.scheduledPayment + bl.balloonPayment + bl.finalPaymentAdjustment)241242 let zero = try Amortization.schedule(LoanTerms(principal: 1000, annualRate: 0, periods: 5))243 compare(zero, am["zero_rate_5"], "zero rate")244 #expect(zero.totalInterest == 0 && zero.rows.allSatisfy { $0.payment == 200 })245 }246247 @Test func extraPaymentsShortenTheLoan() throws {248 let terms = LoanTerms(principal: dec("15000.55"), annualRate: 0.0899, periods: 36, extraPayments: [3: 500, 10: dec("1250.25")], recurringExtraPayment: 50)249 let s = try Amortization.schedule(terms)250 compare(s, am["extra_36"], "extra")251 #expect(s.numberOfPayments < 36)252 let plain = try Amortization.schedule(LoanTerms(principal: dec("15000.55"), annualRate: 0.0899, periods: 36))253 #expect(s.totalInterest < plain.totalInterest)254 #expect(s.totalPrincipal == dec("15000.55"))255 #expect(s.rows[2].extra == 550 && s.rows[9].extra == dec("1300.25"))256 }257258 @Test func roundingModesAndCompounding() throws {259 let b = try Amortization.schedule(LoanTerms(principal: dec("1234.56"), annualRate: 0.2, periods: 10, rounding: MoneyRounding(mode: .halfEven)))260 compare(b, am["bankers_10"], "bankers")261 let sa = try Amortization.schedule(LoanTerms(principal: 42_000, annualRate: 0.0725, periods: 18, compounding: .perYear(2)))262 compare(sa, am["semiannual_comp_18"], "semi-annual compounding")263 #expect(isClose(sa.periodicRate, am["semiannual_comp_18"]["periodic"].d, rel: 1e-13))264 // rounding primitives265 #expect(MoneyRounding.cents.round(dec("0.125")) == dec("0.13"))266 #expect(MoneyRounding.cents.round(dec("-0.125")) == dec("-0.13"))267 #expect(MoneyRounding(mode: .halfEven).round(dec("0.125")) == dec("0.12"))268 #expect(MoneyRounding(mode: .halfEven).round(dec("0.135")) == dec("0.14"))269 #expect(MoneyRounding(mode: .down).round(dec("-1.239")) == dec("-1.23"))270 #expect(MoneyRounding(mode: .up).round(dec("1.231")) == dec("1.24"))271 #expect(MoneyRounding(mode: .halfUp, scale: 0).round(dec("2.5")) == 3)272 #expect(MoneyRounding.cents.round(0.1 + 0.2) == dec("0.30"))273 #expect(MoneyRounding.cents.round(1.005) == dec("1.01")) // decimal, not binary, tie-breaking274 #expect(Money.decimal(0.1) == dec("0.1"))275 #expect(Money.decimal(5e-05) == dec("0.00005") && Money.decimal(1.5e21) == dec("1500000000000000000000") && Money.decimal(-2.5) == dec("-2.5"))276 #expect(Money.double(dec("1234.56")) == 1234.56)277 }278279 @Test func invalidLoans() {280 #expect(throws: StatError.self) { try Amortization.schedule(LoanTerms(principal: 0, annualRate: 0.05, periods: 12)) }281 #expect(throws: StatError.self) { try Amortization.schedule(LoanTerms(principal: 1000, annualRate: 0.05, periods: 0)) }282 #expect(throws: StatError.self) { try Amortization.schedule(LoanTerms(principal: 1000, annualRate: -0.05, periods: 12)) }283 #expect(throws: StatError.self) { try Amortization.schedule(LoanTerms(principal: 1000, annualRate: 0.05, periods: 12, type: .balloon(2000))) }284 #expect(throws: StatError.self) { try Amortization.schedule(LoanTerms(principal: 100_000, annualRate: 0.12, periods: 12, paymentOverride: 500)) } // below interest285 #expect(throws: StatError.self) { try Amortization.schedule(LoanTerms(principal: 1000, annualRate: 0.05, periods: 12, recurringExtraPayment: -1)) }286 }287}288289@Suite struct CanadianMortgageTests {290 @Test func matchesReferenceForEveryFrequency() throws {291 for c in financeFixture["canadian"].list {292 for freq in CanadianPaymentFrequency.allCases {293 let f = c["freq"][freq.rawValue]294 let m = CanadianMortgage(principal: dec(c["principal"].s), annualRate: c["rate"].d, amortizationMonths: c["months"].i,295 termMonths: c["term"].i, frequency: freq)296 let r = try m.solve()297 let tag = "\(c["principal"].s) \(freq.rawValue)"298 #expect(r.payment == dec(f["payment"].s), "\(tag) payment \(r.payment) vs \(f["payment"].s)")299 #expect(r.monthlyPayment == dec(c["monthly"].s), "\(tag) monthly")300 #expect(isClose(r.periodicRate, f["periodic"].d, rel: 1e-12), "\(tag) rate")301 #expect(isClose(r.effectiveAnnualRate, c["ear"].d, rel: 1e-13))302 #expect(r.scheduledPayments == f["scheduled"].i && r.actualPayments == f["actual"].i, "\(tag) counts \(r.actualPayments)")303 #expect(r.totalInterest == dec(f["total_interest"].s), "\(tag) interest \(r.totalInterest)")304 #expect(r.balanceAtTermEnd == dec(f["balance_at_term"].s), "\(tag) balance at term")305 #expect(r.interestPaidDuringTerm == dec(f["interest_in_term"].s), "\(tag) term interest")306 #expect(r.principalPaidDuringTerm == dec(f["principal_in_term"].s), "\(tag) term principal")307 #expect(r.table().count == 13)308 }309 }310 }311312 @Test func textbookExample() throws {313 // $100,000 at 6 % compounded semi-annually over 25 years: the classic $639.81 a month314 let r = try CanadianMortgage(principal: 100_000, annualRate: 0.06, amortizationMonths: 300).solve()315 #expect(r.payment == dec("639.81"))316 #expect(isClose(r.periodicRate, pow(1.03, 1.0 / 6) - 1, rel: 1e-13))317 #expect(isClose(r.effectiveAnnualRate, 0.0609, rel: 1e-12))318 #expect(r.balanceAtTermEnd == nil)319 // US-style monthly compounding gives a higher payment for the same quoted rate320 let us = try CanadianMortgage(principal: 100_000, annualRate: 0.06, amortizationMonths: 300, compounding: .perYear(12)).solve()321 #expect(us.payment == dec("644.30"))322 }323324 @Test func acceleratedPaymentsRetireTheLoanSooner() throws {325 let base = CanadianMortgage(principal: 400_000, annualRate: 0.0525, amortizationMonths: 300, termMonths: 60)326 var m = base327 let monthly = try m.solve()328 m.frequency = .biWeekly329 let biweekly = try m.solve()330 m.frequency = .acceleratedBiWeekly331 let accelerated = try m.solve()332 #expect(accelerated.payment == MoneyRounding.cents.round(monthly.payment / 2))333 #expect(accelerated.payment > biweekly.payment)334 #expect(biweekly.actualPayments == 650)335 #expect(accelerated.actualAmortizationYears < 22.5 && accelerated.actualAmortizationYears > 20)336 #expect(accelerated.totalInterest < biweekly.totalInterest && biweekly.totalInterest < monthly.totalInterest)337 #expect(accelerated.balanceAtTermEnd! < biweekly.balanceAtTermEnd!)338 #expect(throws: StatError.self) { try CanadianMortgage(principal: 1000, annualRate: 0.05, amortizationMonths: 0).solve() }339 }340}341