Repository Public MIT
1// ORIX Calc2// File: Packages/ORIXFinancial/Tests/ORIXFinancialTests/LoanBondTests.swift3// Description: Tests for loans/mortgages (payments, schedules, refinancing, affordability) and bonds against independent references.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXNumerics10@testable import ORIXFinancial1112@Suite struct LoanTests {13 static func terms(_ c: JSON, rounding: MoneyRounding = .nearestCent) -> LoanTerms {14 LoanTerms(principal: c.num("P"), annualRate: c.num("rate"), amortizationYears: c.num("years"),15 frequency: PaymentFrequency(rawValue: c.str("freq"))!, compounding: compounding(c.str("comp")), rounding: rounding)16 }1718 @Test func paymentsForEveryFrequencyAndConvention() throws {19 let cases = Ref.list("loan_payments")20 #expect(cases.count >= 10)21 #expect(Set(cases.map { $0.str("freq") }).count == PaymentFrequency.allCases.count)22 for c in cases {23 let r = try Loan.payment(Self.terms(c))24 #expect(close(r.unroundedPayment, c.num("payment_unrounded"), 1e-12), "\(c.str("name"))")25 #expect(r.payment == c.num("payment"), "\(c.str("name")): \(r.payment)")26 #expect(close(r.periodicRate, c.num("periodic_rate"), 1e-14))27 #expect(r.verification.isVerified, "\(c.str("name")): \(r.verification.warnings)")28 #expect(try Loan.payment(Self.terms(c, rounding: .none)).payment == r.unroundedPayment)29 }30 }3132 @Test func canadianMortgageTextbookCase() throws {33 // 300 000 at 5% compounded semi-annually, 25 years, monthly: 1 744.81.34 let t = LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .canadianFixed)35 let r = try Loan.payment(t)36 #expect(r.payment == 1744.81)37 #expect(abs(r.periodicRate - (pow(1.025, 1.0 / 6) - 1)) < 1e-16)38 #expect(abs(r.effectiveAnnualRate - 0.050625) < 1e-14)39 // the same loan compounded monthly (US style) costs more: 1 753.7740 #expect(try Loan.payment(LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .usMonthly)).payment == 1753.77)41 #expect(r.explanation.plainText.contains("semi-annually"))42 }4344 @Test func acceleratedPaymentsRepayFaster() throws {45 let base = LoanTerms(principal: 400_000, annualRate: 0.0479, amortizationYears: 25, frequency: .monthly, compounding: .canadianFixed)46 var acc = base; acc.frequency = .acceleratedBiweekly47 var reg = base; reg.frequency = .biweekly48 let monthly = try Loan.payment(LoanTerms(principal: base.principal, annualRate: base.annualRate, amortizationYears: 25,49 compounding: .canadianFixed, rounding: .none)).payment50 let a = try Loan.payment(acc), r = try Loan.payment(reg)51 #expect(abs(a.unroundedPayment - monthly / 2) < 1e-10)52 #expect(a.payment > r.payment)53 #expect(a.numberOfPayments < 650 && r.numberOfPayments == 650)54 let schedule = try Loan.schedule(acc)55 #expect(schedule.rows.count == Int(a.numberOfPayments.rounded(.up)))56 var weekly = base; weekly.frequency = .acceleratedWeekly57 #expect(try abs(Loan.payment(weekly).unroundedPayment - monthly / 4) < 1e-10)58 }5960 static func options(_ a: JSON) -> ScheduleOptions {61 var o = ScheduleOptions()62 for l in a["lumps"] as? [[NSNumber]] ?? [] { o.prepayments.append(Prepayment(amount: l[1].doubleValue, schedule: .lumpSum(period: l[0].intValue))) }63 for r in a["recurring"] as? [[NSNumber]] ?? [] {64 o.prepayments.append(Prepayment(amount: r[3].doubleValue,65 schedule: .recurring(start: r[0].intValue, end: r[1].intValue < 0 ? nil : r[1].intValue, every: r[2].intValue)))66 }67 for ch in a["changes"] as? [[Any]] ?? [] {68 o.rateChanges.append(RateChange(period: (ch[0] as! NSNumber).intValue, annualRate: (ch[1] as! NSNumber).doubleValue,69 policy: (ch[2] as! String) == "recalc" ? .recalculatePayment : .keepPayment))70 }71 if a["override"] != nil { o.paymentOverride = a.num("override") }72 if let stop = a.optionalNum("stop") { o.stopAfterPeriods = Int(stop) }73 return o74 }7576 /// Full schedules (plain, accelerated, weekly, prepayments, rate changes, override, term) against Python's decimal simulation, to the cent.77 @Test func schedulesMatchDecimalReferenceToTheCent() throws {78 let cases = Ref.list("loan_schedules")79 #expect(cases.count >= 11)80 for c in cases {81 let name = c.str("name")82 let a = c["args"] as! JSON83 let s = try Loan.schedule(Self.terms(a), options: Self.options(a))84 #expect(s.rows.count == c.int("payments"), "\(name) number of payments")85 #expect(s.payment == c.num("payment"), "\(name) payment")86 for (got, key) in [(s.finalPayment, "final_payment"), (s.totalInterest, "total_interest"), (s.totalPrincipal, "total_principal"),87 (s.totalPrepayments, "total_prepayments"), (s.totalPaid, "total_paid"), (s.endingBalance, "ending_balance")] {88 #expect(abs(got - c.num(key)) < 0.005, "\(name) \(key): \(got) vs \(c.num(key))")89 }90 for p in c["probes"] as! [JSON] {91 let row = s.rows[p.int("period") - 1]92 #expect(abs(row.interest - p.num("interest")) < 0.005 && abs(row.principal - p.num("principal")) < 0.00593 && abs(row.balance - p.num("balance")) < 0.005, "\(name) row \(row.period): \(row)")94 #expect(s.balance(after: row.period) == row.balance)95 }96 #expect(s.verification.isVerified, "\(name): \(s.verification.warnings)")97 // every amount is a whole number of cents98 for row in s.rows { #expect(abs((row.balance * 100).rounded() - row.balance * 100) < 1e-6 && abs((row.interest * 100).rounded() - row.interest * 100) < 1e-6) }99 }100 }101102 @Test func finalPaymentAdjustment() throws {103 let t = LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .canadianFixed)104 let s = try Loan.schedule(t)105 #expect(s.rows.count == 300 && s.endingBalance == 0 && s.isPaidOff)106 #expect(s.finalPayment != s.payment) // rounding leaves a residual …107 #expect(abs(s.finalPayment - s.payment) < 5) // … of a few dollars at most, absorbed by the last payment108 #expect(s.rows[298].payment == s.payment)109 #expect(abs(s.rows[299].payment - (s.rows[298].balance + s.rows[299].interest)) < 0.005)110 #expect(abs(s.totalPrincipal - 300_000) < 0.005)111 #expect(abs(s.totalPaid - (300_000 + s.totalInterest)) < 0.005)112 #expect(s.balance(after: 0) == 300_000 && s.balance(after: 999) == 0)113 }114115 @Test func unroundedScheduleMatchesClosedForm() throws {116 let t = LoanTerms(principal: 250_000, annualRate: 0.065, amortizationYears: 30, rounding: .none)117 let s = try Loan.schedule(t)118 #expect(s.rows.count == 360 && s.endingBalance == 0)119 #expect(abs(s.finalPayment - s.payment) < 1e-6)120 for k in [1, 77, 180, 359] { #expect(try close(s.balance(after: k), Loan.balance(t, afterPayments: k), 1e-10)) }121 #expect(close(s.totalInterest, s.payment * 360 - 250_000, 1e-10))122 // rounded schedule stays within rounding drift of the closed form123 var rounded = t; rounded.rounding = .nearestCent124 let sr = try Loan.schedule(rounded)125 #expect(try abs(sr.balance(after: 180) - (Loan.balance(rounded, afterPayments: 180))) < 1.5)126 #expect(try Loan.balance(t, afterPayments: 0) == 250_000)127 #expect(try Loan.balance(t, afterPayments: 400) == 0)128 }129130 @Test func termVersusAmortization() throws {131 let t = LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .canadianFixed)132 let term = try Loan.termSummary(t, termYears: 5)133 let ref = Ref.list("loan_schedules").first { $0.str("name") == "term_5y" }!134 #expect(term.paymentsInTerm == 60 && term.payment == 1744.81)135 #expect(abs(term.balanceAtEndOfTerm - ref.num("ending_balance")) < 0.005)136 #expect(abs(term.interestPaidInTerm - ref.num("total_interest")) < 0.005)137 #expect(abs(term.principalPaidInTerm + term.balanceAtEndOfTerm - 300_000) < 0.005)138 #expect(!term.schedule.isPaidOff && term.schedule.verification.isVerified)139 }140141 @Test func prepaymentsShortenTheLoanAndRateChangesApply() throws {142 let t = LoanTerms(principal: 250_000, annualRate: 0.065, amortizationYears: 30)143 let plain = try Loan.schedule(t)144 let pre = try Loan.schedule(t, options: ScheduleOptions(prepayments: [Prepayment(amount: 200, schedule: .recurring(start: 1, end: nil, every: 1))]))145 #expect(pre.rows.count < plain.rows.count && pre.totalInterest < plain.totalInterest)146 #expect(pre.rows[0].prepayment == 200 && abs(pre.totalPrincipal + pre.totalPrepayments - 250_000) < 0.005)147 // a lump sum larger than the balance is capped148 let big = try Loan.schedule(t, options: ScheduleOptions(prepayments: [Prepayment(amount: 1e9, schedule: .lumpSum(period: 3))]))149 #expect(big.rows.count == 3 && big.endingBalance == 0 && abs(big.rows[2].prepayment - (big.rows[1].balance - big.rows[2].principal)) < 0.005)150 // rate rise with recalculation keeps the original end date; keeping the payment extends it151 let up = RateChange(period: 61, annualRate: 0.08, policy: .recalculatePayment)152 let recalculated = try Loan.schedule(t, options: ScheduleOptions(rateChanges: [up]))153 #expect(recalculated.rows.count == 360 && recalculated.rows[60].payment > recalculated.rows[59].payment && recalculated.rows[60].annualRate == 0.08)154 let kept = try Loan.schedule(t, options: ScheduleOptions(rateChanges: [RateChange(period: 61, annualRate: 0.07, policy: .keepPayment)]))155 #expect(kept.rows.count > 360 && kept.rows[60].payment == kept.payment)156 }157158 @Test func paymentThatDoesNotCoverInterestIsRefused() {159 let t = LoanTerms(principal: 250_000, annualRate: 0.03, amortizationYears: 30)160 expectFinancialError({ _ = try Loan.schedule(t, options: ScheduleOptions(rateChanges: [RateChange(period: 13, annualRate: 0.12, policy: .keepPayment)])) }) {161 if case .invalidInput(let m) = $0 { m.contains("does not cover the interest") } else { false }162 }163 expectFinancialError({ _ = try Loan.schedule(t, options: ScheduleOptions(paymentOverride: 100)) }) { if case .invalidInput = $0 { true } else { false } }164 // a payment barely above the interest never repays within the supported horizon165 expectFinancialError({ _ = try Loan.schedule(LoanTerms(principal: 1_000_000, annualRate: 0.001, amortizationYears: 30),166 options: ScheduleOptions(paymentOverride: 83.34)) }) { if case .nonConvergence = $0 { true } else { false } }167 }168169 @Test func invalidLoanInputs() {170 expectFinancialError({ _ = try Loan.payment(LoanTerms(principal: 0, annualRate: 0.05, amortizationYears: 25)) }) { if case .invalidInput = $0 { true } else { false } }171 expectFinancialError({ _ = try Loan.payment(LoanTerms(principal: 1000, annualRate: -0.01, amortizationYears: 25)) }) { if case .invalidInput = $0 { true } else { false } }172 expectFinancialError({ _ = try Loan.payment(LoanTerms(principal: 1000, annualRate: 0.05, amortizationYears: 0.3)) }) { if case .invalidInput = $0 { true } else { false } }173 expectFinancialError({ _ = try Loan.payment(LoanTerms(principal: 1000, annualRate: 0.05, amortizationYears: 5, compounding: .periodic(perYear: 0))) }) { if case .invalidInput = $0 { true } else { false } }174 expectFinancialError({ _ = try Loan.balance(LoanTerms(principal: 1000, annualRate: 0.05, amortizationYears: 5), afterPayments: -1) }) { if case .invalidInput = $0 { true } else { false } }175 }176177 @Test func refinancingComparison() throws {178 for ref in Ref.list("refinance") {179 let r = try Loan.compareRefinance(RefinanceInputs(180 currentBalance: 240_000, currentAnnualRate: 0.065, currentRemainingYears: 25, currentCompounding: .usMonthly,181 newAnnualRate: 0.0525, newAmortizationYears: 25, newCompounding: .usMonthly,182 closingCosts: 3000, prepaymentPenalty: 1500, financeCosts: ref.bool("financed")))183 #expect(r.currentPayment == ref.num("current_payment") && r.newPayment == ref.num("new_payment"))184 #expect(abs(r.paymentSavingsPerPeriod - ref.num("savings")) < 1e-9)185 #expect(close(r.simpleBreakEvenPeriods!, ref.num("simple_break_even"), 1e-12))186 #expect(r.simpleBreakEvenMonths == r.simpleBreakEvenPeriods)187 #expect(r.netBreakEvenPeriod == ref.int("net_break_even"))188 #expect(abs(r.currentTotalInterest - ref.num("current_interest")) < 0.005 && abs(r.newTotalInterest - ref.num("new_interest")) < 0.005)189 #expect(abs(r.lifetimeSavings - ref.num("lifetime_savings")) < 0.005)190 #expect(r.upfrontCosts == 4500 && r.newPrincipal == (ref.bool("financed") ? 244_500 : 240_000))191 #expect(r.verification.isVerified, "\(r.verification.warnings)")192 }193 // refinancing at a higher rate never breaks even194 let worse = try Loan.compareRefinance(RefinanceInputs(currentBalance: 100_000, currentAnnualRate: 0.04, currentRemainingYears: 20, currentCompounding: .usMonthly,195 newAnnualRate: 0.06, newAmortizationYears: 20, newCompounding: .usMonthly, closingCosts: 1000))196 #expect(worse.simpleBreakEvenPeriods == nil && worse.netBreakEvenPeriod == nil && worse.lifetimeSavings < 0)197 #expect(worse.verification.status == .warning)198 }199200 @Test func affordability() throws {201 let ref = Ref.object("affordability")202 let a = AffordabilityInputs(grossAnnualIncome: 120_000, annualPropertyTax: 4200, annualHeating: 1500, monthlyCondoFees: 300, condoFeeShare: 0.5,203 otherMonthlyDebtPayments: 650, housingRatioLimit: 0.39, totalDebtRatioLimit: 0.44,204 annualRate: 0.0525, amortizationYears: 25, compounding: .canadianFixed, downPayment: 60_000)205 let r = try Loan.affordability(a)206 #expect(close(r.maxPaymentByHousingRatio, ref.num("by_housing"), 1e-12) && close(r.maxPaymentByTotalDebtRatio, ref.num("by_total"), 1e-12))207 #expect(close(r.maxMonthlyPayment, ref.num("max_payment"), 1e-12))208 #expect(close(r.maxLoan, ref.num("max_loan"), 1e-12))209 #expect(r.maxPurchasePrice == r.maxLoan + 60_000)210 #expect(r.bindingConstraint == .totalDebtRatio && abs(r.totalDebtRatio - 0.44) < 1e-12 && r.housingRatio < 0.39)211 #expect(r.verification.isVerified)212 // round trip: the payment on the maximum loan is the maximum payment213 let back = try Loan.payment(LoanTerms(principal: r.maxLoan, annualRate: 0.0525, amortizationYears: 25, compounding: .canadianFixed, rounding: .none)).payment214 #expect(close(back, r.maxMonthlyPayment, 1e-12))215 var noDebt = a; noDebt.otherMonthlyDebtPayments = 0216 #expect(try Loan.affordability(noDebt).bindingConstraint == .housingRatio)217 var broke = a; broke.otherMonthlyDebtPayments = 10_000218 expectFinancialError({ _ = try Loan.affordability(broke) }) { if case .noSolution = $0 { true } else { false } }219 }220221 @Test func centRoundingPolicy() {222 let r = MoneyRounding.nearestCent223 #expect(r.apply(1.005) == 1.01) // binary 1.00499999999999989… must still round up224 #expect(r.apply(2.675) == 2.68)225 #expect(r.apply(-1.005) == -1.01) // half away from zero226 #expect(r.apply(0.004999) == 0 && r.apply(1e-7) == 0)227 #expect(r.apply(1744.8149) == 1744.81 && r.apply(1744.815) == 1744.82)228 #expect(r.apply(1e15 + 0.25) == 1e15 + 0.25)229 #expect(r.apply(123_456_789.125) == 123_456_789.13)230 #expect(MoneyRounding.none.apply(1.005) == 1.005)231 // interest ties: 6%/12 = 0.5% on 1 001.00 is exactly 5.005 and 4.5%/12 = 0.375% on 100 004.00 is exactly 375.015 → both round up232 #expect(Loan.periodInterest(balance: 1001, i: 0.005, annualRate: 0.06, compounding: .usMonthly, paymentsPerYear: 12, rounding: .nearestCent) == 5.01)233 #expect(Loan.periodInterest(balance: 100_004, i: 0.00375, annualRate: 0.045, compounding: .canadianVariable, paymentsPerYear: 12, rounding: .nearestCent) == 375.02)234 #expect(Loan.periodInterest(balance: 100_001.20, i: 0.00375, annualRate: 0.045, compounding: .canadianVariable, paymentsPerYear: 12, rounding: .nearestCent) == 375.0)235 #expect(Loan.periodInterest(balance: 300_000, i: pow(1.025, 1.0 / 6) - 1, annualRate: 0.05, compounding: .canadianFixed, paymentsPerYear: 12, rounding: .nearestCent) == 1237.17)236 #expect(Loan.periodInterest(balance: 1234.56, i: 0.005, annualRate: 0.06, compounding: .usMonthly, paymentsPerYear: 12, rounding: .none) == 1234.56 * 0.005)237 }238}239240@Suite struct BondTests {241 static func spec(_ c: JSON) -> BondSpec {242 BondSpec(faceValue: c.num("face"), couponRate: c.num("coupon"), frequency: c.int("frequency"),243 redemption: c.optionalNum("redemption") ?? c.num("face"), dayCount: DayCountConvention(rawValue: c.str("convention")) ?? .thirty360US)244 }245246 /// Dated bonds under each day-count convention: price, accrued, durations, convexity and yield round trip.247 @Test func datedBondsMatchReference() throws {248 let cases = Ref.list("bonds")249 #expect(cases.count >= 10)250 #expect(Set(cases.map { $0.str("convention") }).count == DayCountConvention.allCases.count)251 for c in cases {252 let name = c.str("name")253 let b = Self.spec(c), s = date(c.str("settlement")), m = date(c.str("maturity"))254 let r = try Bond.analyze(b, settlement: s, maturity: m, quote: .yield(c.num("y")))255 #expect(r.accruedDays == c.num("accrued_days") && close(r.periodDays, c.num("period_days"), 1e-14), "\(name) days")256 #expect(close(r.fractionToNextCoupon, c.num("w"), 1e-14) && r.remainingCoupons == c.int("remaining"), "\(name) w")257 #expect(r.nextCouponDate == date(c.str("first_coupon")) && r.couponDates.last == m)258 #expect(close(r.accruedInterest, c.num("accrued"), 1e-13), "\(name) accrued")259 #expect(close(r.dirtyPrice, c.num("dirty"), 1e-12), "\(name) dirty")260 #expect(close(r.cleanPrice, c.num("clean"), 1e-12), "\(name) clean")261 #expect(close(r.macaulayDuration, c.num("macaulay"), 1e-11), "\(name) Macaulay")262 #expect(close(r.modifiedDuration, c.num("modified"), 1e-11), "\(name) modified")263 #expect(close(r.convexity, c.num("convexity"), 1e-11), "\(name) convexity")264 #expect(try abs(Bond.accruedInterest(b, settlement: s, maturity: m) - r.accruedInterest) == 0)265 #expect(r.verification.isVerified, "\(name): \(r.verification.warnings)")266 // yield from price (clean and dirty) recovers the yield267 let back = try Bond.analyze(b, settlement: s, maturity: m, quote: .cleanPrice(c.num("clean")))268 #expect(abs(back.yield - c.num("y")) < 1e-12 && abs(back.yield - c.num("ytm_from_clean")) < 1e-12, "\(name) YTM \(back.yield)")269 #expect(back.verification.isVerified)270 #expect(try abs(Bond.analyze(b, settlement: s, maturity: m, quote: .dirtyPrice(c.num("dirty"))).yield - c.num("y")) < 1e-12)271 }272 }273274 @Test func wholePeriodMode() throws {275 for c in Ref.list("bonds_simple") {276 let b = BondSpec(faceValue: c.num("face"), couponRate: c.num("coupon"), frequency: c.int("frequency"))277 let r = try Bond.analyze(b, periods: c.int("periods"), quote: .yield(c.num("y")))278 #expect(close(r.cleanPrice, c.num("clean"), 1e-12) && r.accruedInterest == 0 && r.dirtyPrice == r.cleanPrice)279 #expect(close(r.macaulayDuration, c.num("macaulay"), 1e-11) && close(r.modifiedDuration, c.num("modified"), 1e-11) && close(r.convexity, c.num("convexity"), 1e-11))280 #expect(try abs(Bond.analyze(b, periods: c.int("periods"), quote: .cleanPrice(c.num("clean"))).yield - c.num("y")) < 1e-12)281 #expect(r.couponDates.isEmpty && r.fractionToNextCoupon == 1)282 }283 // textbook: 10-year 8% semi-annual bond at a 10% yield is worth 87.5378; at 8% it is worth par284 let b = BondSpec(couponRate: 0.08, frequency: 2)285 #expect(try abs(Bond.analyze(b, periods: 20, quote: .yield(0.10)).cleanPrice - 87.53778968) < 1e-7)286 #expect(try abs(Bond.analyze(b, periods: 20, quote: .yield(0.08)).cleanPrice - 100) < 1e-12)287 #expect(try abs(Bond.analyze(b, periods: 20, quote: .cleanPrice(100)).yield - 0.08) < 1e-13)288 // zero-coupon: Macaulay duration equals maturity289 let z = try Bond.analyze(BondSpec(couponRate: 0, frequency: 1), periods: 7, quote: .yield(0.05))290 #expect(abs(z.macaulayDuration - 7) < 1e-12 && abs(z.cleanPrice - 100 / pow(1.05, 7)) < 1e-12)291 }292293 /// Values published in the Microsoft Excel documentation for PRICE, YIELD, DURATION and MDURATION.294 @Test func excelDocumentationExamples() throws {295 let b = BondSpec(couponRate: 0.0575, frequency: 2, dayCount: .thirty360US)296 let price = try Bond.analyze(b, settlement: date("2008-02-15"), maturity: date("2017-11-15"), quote: .yield(0.065))297 #expect(abs(price.cleanPrice - 94.63436) < 5e-6) // =PRICE(...) → 94.63436298 let y = try Bond.analyze(b, settlement: date("2008-02-15"), maturity: date("2016-11-15"), quote: .cleanPrice(95.04287))299 #expect(abs(y.yield - 0.065) < 5e-8) // =YIELD(...) → 6.5%300 let d = try Bond.analyze(BondSpec(couponRate: 0.08, frequency: 2, dayCount: .actualActualICMA),301 settlement: date("2018-07-01"), maturity: date("2048-01-01"), quote: .yield(0.09))302 #expect(abs(d.macaulayDuration - 10.9191453) < 5e-8) // =DURATION(...) → 10.9191453303 let md = try Bond.analyze(BondSpec(couponRate: 0.08, frequency: 2, dayCount: .actualActualICMA),304 settlement: date("2008-01-01"), maturity: date("2016-01-01"), quote: .yield(0.09))305 #expect(abs(md.modifiedDuration - 5.736) < 5e-4) // =MDURATION(...) → 5.736306 }307308 @Test func accruedInterestIsZeroOnCouponDate() throws {309 for conv in DayCountConvention.allCases {310 let b = BondSpec(couponRate: 0.06, frequency: 2, dayCount: conv)311 let r = try Bond.analyze(b, settlement: date("2025-06-15"), maturity: date("2030-06-15"), quote: .yield(0.05))312 #expect(r.accruedInterest == 0 && r.cleanPrice == r.dirtyPrice && r.previousCouponDate == date("2025-06-15"), "\(conv)")313 #expect(r.remainingCoupons == 10)314 if conv == .thirty360US || conv == .thirtyE360 || conv == .actualActualICMA {315 // on a coupon date these conventions give exactly the whole-period price316 #expect(try close(r.cleanPrice, Bond.analyze(b, periods: 10, quote: .yield(0.05)).cleanPrice, 1e-13))317 // priced at its coupon rate on a coupon date, the bond is at par318 #expect(try abs(Bond.analyze(b, settlement: date("2025-06-15"), maturity: date("2030-06-15"), quote: .yield(0.06)).cleanPrice - 100) < 1e-11)319 }320 // one day later one day of interest has accrued321 let next = try Bond.accruedInterest(b, settlement: date("2025-06-16"), maturity: date("2030-06-15"))322 #expect(next > 0 && next < 0.02)323 }324 }325326 @Test func accruedInterestByConvention() throws {327 // 6% semi-annual, last coupon 2025-01-31 (month-end schedule), settlement 2025-03-31328 let s = date("2025-03-31"), m = date("2030-07-31")329 func accrued(_ c: DayCountConvention) throws -> Double { try Bond.accruedInterest(BondSpec(couponRate: 0.06, frequency: 2, dayCount: c), settlement: s, maturity: m) }330 #expect(try abs(accrued(.thirty360US) - 3 * 60.0 / 180) < 1e-13)331 #expect(try abs(accrued(.thirtyE360) - 3 * 60.0 / 180) < 1e-13)332 #expect(try abs(accrued(.actual360) - 100 * 0.06 * 59 / 360) < 1e-13)333 #expect(try abs(accrued(.actual365Fixed) - 100 * 0.06 * 59 / 365) < 1e-13)334 #expect(try abs(accrued(.actualActualICMA) - 3 * 59.0 / 181) < 1e-13)335 }336337 @Test func couponScheduleBackwardsFromMaturity() throws {338 let s = try Bond.couponSchedule(settlement: date("2024-10-15"), maturity: date("2029-02-28"), frequency: 2)339 #expect(s.previous == date("2024-08-31") && s.remaining.first == date("2025-02-28") && s.remaining[1] == date("2025-08-31"))340 #expect(s.remaining.count == 9 && s.remaining.last == date("2029-02-28"))341 let noEOM = try Bond.couponSchedule(settlement: date("2024-10-15"), maturity: date("2029-02-28"), frequency: 2, endOfMonthRule: false)342 #expect(noEOM.previous == date("2024-08-28"))343 let q = try Bond.couponSchedule(settlement: date("2025-01-20"), maturity: date("2027-12-15"), frequency: 4)344 #expect(q.previous == date("2024-12-15") && q.remaining.first == date("2025-03-15") && q.remaining.count == 12)345 let monthly = try Bond.couponSchedule(settlement: date("2025-05-07"), maturity: date("2026-09-30"), frequency: 12)346 #expect(monthly.previous == date("2025-04-30") && monthly.remaining.first == date("2025-05-31") && monthly.remaining.count == 17)347 }348349 @Test func durationAndConvexityMatchNumericalDerivatives() throws {350 let b = BondSpec(couponRate: 0.045, frequency: 2, dayCount: .actualActualICMA)351 let s = date("2025-03-10"), m = date("2040-09-01"), y = 0.0525352 let r = try Bond.analyze(b, settlement: s, maturity: m, quote: .yield(y))353 let price: (Double) -> Double = { (try? Bond.analyze(b, settlement: s, maturity: m, quote: .yield($0)).dirtyPrice) ?? .nan }354 let d1 = Differentiation.derivative(price, at: y).value355 let d2 = Differentiation.secondDerivative(price, at: y).value356 #expect(close(-d1 / r.dirtyPrice, r.modifiedDuration, 1e-8))357 #expect(close(d2 / r.dirtyPrice, r.convexity, 1e-5))358 #expect(close(r.macaulayDuration, r.modifiedDuration * (1 + y / 2), 1e-14))359 // bump-and-reprice estimates agree with the analytic figures up to the O(Δy²) truncation360 #expect(abs(r.effectiveDuration - r.modifiedDuration) < 1e-5 && abs(r.effectiveConvexity - r.convexity) < 1e-3)361 #expect(r.bump == 0.0001)362 // second-order Taylor estimate of a 50 bp move (the remainder is the third-order term, about 0.004 on a price near 92)363 let moved = try Bond.analyze(b, settlement: s, maturity: m, quote: .yield(y + 0.005)).dirtyPrice364 let taylor = r.dirtyPrice * (1 - r.modifiedDuration * 0.005 + 0.5 * r.convexity * 0.005 * 0.005)365 #expect(abs(moved - taylor) < 1e-2 && abs(moved - r.dirtyPrice * (1 - r.modifiedDuration * 0.005)) > 0.05)366 #expect(close(r.currentYield, 4.5 / r.cleanPrice, 1e-14))367 }368369 @Test func yieldToCall() throws {370 let ref = Ref.object("yield_to_call")371 let b = BondSpec(couponRate: 0.08, frequency: 2, dayCount: .thirty360US)372 let r = try Bond.yieldToCall(b, settlement: date("2025-09-02"), callDate: date("2029-06-15"), callPrice: 104, cleanPrice: 106.5)373 #expect(abs(r.yield - ref.num("ytc")) < 1e-12 && close(r.accruedInterest, ref.num("accrued"), 1e-13))374 #expect(r.explanation.title.contains("Yield to call") && r.verification.isVerified)375 // premium bond called early at a lower price yields less than to maturity376 let ytm = try Bond.analyze(b, settlement: date("2025-09-02"), maturity: date("2035-06-15"), quote: .cleanPrice(106.5)).yield377 #expect(r.yield < ytm)378 }379380 @Test func invalidAndUnsolvableBonds() {381 let b = BondSpec(couponRate: 0.05, frequency: 2)382 expectFinancialError({ _ = try Bond.analyze(b, settlement: date("2030-01-01"), maturity: date("2029-01-01"), quote: .yield(0.05)) }) { if case .invalidInput = $0 { true } else { false } }383 expectFinancialError({ _ = try Bond.analyze(BondSpec(couponRate: 0.05, frequency: 3), periods: 4, quote: .yield(0.05)) }) { if case .invalidInput = $0 { true } else { false } }384 expectFinancialError({ _ = try Bond.analyze(b, periods: 10, quote: .cleanPrice(-5)) }) { if case .invalidInput = $0 { true } else { false } }385 expectFinancialError({ _ = try Bond.analyze(b, periods: 10, quote: .yield(-2.5)) }) { if case .invalidInput = $0 { true } else { false } }386 expectFinancialError({ _ = try Bond.analyze(b, periods: 2, quote: .cleanPrice(1e-30)) }) { if case .noSolution = $0 { true } else { false } }387 // non-convergence is reported, not hidden: one Brent iteration is not enough388 expectFinancialError({ _ = try Bond.analyze(b, periods: 20, quote: .cleanPrice(93.7), maxIterations: 1) }) { if case .nonConvergence = $0 { true } else { false } }389 }390}391