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/FixedIncomeTests.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 DayCountTests {94 /// The Python reference (`gen_finance.py`) implements the SIA 30U/360 rule text; Excel's variant95 /// is pinned by `ExcelCompatibilityTests`.96 @Test func matchesReferenceImplementation() throws {97 for c in financeFixture["daycount"].list {98 let a = date(c["a"]), b = date(c["b"])99 let tag = "\(a) → \(b)"100 #expect(DayCount.days(from: a, to: b, convention: .thirty360SIA) == c["d30u"].i, "\(tag) 30U")101 #expect(DayCount.days(from: a, to: b, convention: .thirtyE360) == c["d30e"].i, "\(tag) 30E")102 #expect(DayCount.days(from: a, to: b, convention: .actual360) == c["act"].i, "\(tag) act")103 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .thirty360SIA), c["yf_30u"].d, rel: 1e-15))104 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .thirtyE360), c["yf_30e"].d, rel: 1e-15))105 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .actual360), c["yf_a360"].d, rel: 1e-15))106 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .actual365Fixed), c["yf_a365"].d, rel: 1e-15))107 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .actualActualISDA), c["yf_isda"].d, rel: 1e-14), "\(tag) ISDA")108 // antisymmetry109 #expect(isClose(try DayCount.yearFraction(from: b, to: a, convention: .actualActualISDA), -c["yf_isda"].d, rel: 1e-14))110 }111 }112113 @Test func publishedExamples() throws {114 // ISDA's "ACT/ACT" memo (1998), first example: 1 Nov 2003 → 1 May 2004115 let a = CalendarDate(2003, 11, 1), b = CalendarDate(2004, 5, 1)116 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .actualActualISDA), 61.0 / 365 + 121.0 / 366, rel: 1e-15))117 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .actualActualISDA), 0.497724380567, rel: 1e-11))118 #expect(isClose(try DayCount.yearFraction(from: a, to: b, convention: .actualActualICMA, referenceStart: a, referenceEnd: b, frequency: 2), 0.5, rel: 1e-15))119 // a full semi-annual coupon period is exactly half a year under ICMA whatever its length in days120 let s = CalendarDate(2024, 2, 29), e = CalendarDate(2024, 8, 31)121 #expect(try DayCount.yearFraction(from: s, to: e, convention: .actualActualICMA, referenceStart: s, referenceEnd: e, frequency: 2) == 0.5)122 #expect(isClose(try DayCount.yearFraction(from: s, to: CalendarDate(2024, 5, 31), convention: .actualActualICMA, referenceStart: s, referenceEnd: e, frequency: 2), 92.0 / (2 * 184), rel: 1e-15))123 #expect(throws: StatError.self) { try DayCount.yearFraction(from: a, to: b, convention: .actualActualICMA) }124 // 30/360: a full year is always 360 days, 31sts fold into the 30th125 #expect(DayCount.days(from: CalendarDate(2023, 1, 31), to: CalendarDate(2024, 1, 31), convention: .thirty360US) == 360)126 #expect(DayCount.days(from: CalendarDate(2023, 1, 30), to: CalendarDate(2023, 1, 31), convention: .thirty360US) == 0)127 #expect(DayCount.days(from: CalendarDate(2023, 1, 29), to: CalendarDate(2023, 1, 31), convention: .thirty360US) == 2) // D1 < 30 keeps D2 = 31128 #expect(DayCount.days(from: CalendarDate(2023, 1, 29), to: CalendarDate(2023, 1, 31), convention: .thirtyE360) == 1)129 // a start on the last day of February separates the three US rules and 30E130 #expect(DayCount.days(from: CalendarDate(2023, 2, 28), to: CalendarDate(2023, 3, 31), convention: .thirty360US) == 31) // Excel131 #expect(DayCount.days(from: CalendarDate(2023, 2, 28), to: CalendarDate(2023, 3, 31), convention: .thirty360SIA) == 30)132 #expect(DayCount.days(from: CalendarDate(2023, 2, 28), to: CalendarDate(2023, 3, 31), convention: .thirty360ISDA) == 33)133 #expect(DayCount.days(from: CalendarDate(2023, 2, 28), to: CalendarDate(2023, 3, 31), convention: .thirtyE360) == 32)134 }135136 @Test func calendarDates() {137 let d = CalendarDate(2024, 1, 31)138 #expect(d.addingMonths(1) == CalendarDate(2024, 2, 29))139 #expect(d.addingMonths(-2) == CalendarDate(2023, 11, 30))140 #expect(d.addingMonths(13) == CalendarDate(2025, 2, 28))141 #expect(CalendarDate(2024, 2, 29).addingMonths(6, endOfMonth: true) == CalendarDate(2024, 8, 31))142 #expect(CalendarDate(2024, 2, 29).addingMonths(6) == CalendarDate(2024, 8, 29))143 #expect(d.days(to: CalendarDate(2024, 3, 1)) == 30)144 #expect(d.addingDays(366) == CalendarDate(2025, 1, 31))145 #expect(CalendarDate(dayNumber: d.dayNumber) == d)146 #expect(CalendarDate(serial: 39448) == CalendarDate(2008, 1, 1)) // Excel serial of 1 Jan 2008147 #expect(CalendarDate(2008, 1, 1).serial() == 39448)148 #expect(d.description == "2024-01-31" && d < CalendarDate(2024, 2, 1))149 #expect(CalendarDate(2023, 2, 28).isLastDayOfFebruary && !CalendarDate(2024, 2, 28).isLastDayOfFebruary)150 }151}152153@Suite struct BondTests {154 func convention(_ s: String) -> DayCountConvention {155 switch s {156 case "30u": .thirty360SIA157 case "30e": .thirtyE360158 case "a360": .actual360159 case "a365": .actual365Fixed160 default: .actualActualICMA161 }162 }163164 /// The Python reference discounts with w = DSC/E (actual DSC) and counts 30U/360 by the SIA text:165 /// the `.streetActual` convention.166 @Test func matchesReferenceImplementation() throws {167 for c in financeFixture["bonds"].list {168 let bond = Bond(maturity: date(c["maturity"]), couponRate: c["coupon"].d, frequency: c["freq"].i,169 redemption: c["redemption"].d, dayCount: convention(c["basis"].s), convention: .streetActual)170 let settle = date(c["settle"]), y = c["yield"].d171 let tag = "bond \(bond.maturity) \(c["basis"].s)"172 let cp = try bond.couponPeriod(settlement: settle)173 #expect(cp.previousCoupon == date(c["prev"]) && cp.nextCoupon == date(c["next"]), "\(tag) coupon dates")174 #expect(cp.remainingCoupons == c["n"].i, "\(tag) N")175 #expect(isClose(cp.accruedDays, c["A"].d, rel: 1e-14) && isClose(cp.periodDays, c["E"].d, rel: 1e-14) && isClose(cp.daysToNextCoupon, c["DSC"].d, rel: 1e-13), "\(tag) A/E/DSC")176 let a = try bond.analytics(settlement: settle, yield: y)177 #expect(isClose(a.accruedInterest, c["accrued"].d, rel: 1e-13, abs: 1e-15), "\(tag) accrued")178 #expect(isClose(a.dirtyPrice, c["dirty"].d, rel: 1e-12), "\(tag) dirty \(a.dirtyPrice) vs \(c["dirty"].d)")179 #expect(isClose(a.cleanPrice, c["clean"].d, rel: 1e-12), "\(tag) clean")180 #expect(isClose(try bond.cleanPrice(settlement: settle, yield: y), c["clean"].d, rel: 1e-12))181 #expect(isClose(a.macaulayDuration, c["macaulay"].d, rel: 1e-12), "\(tag) Macaulay")182 #expect(isClose(a.modifiedDuration, c["modified"].d, rel: 1e-12), "\(tag) modified")183 #expect(isClose(a.modifiedDuration, c["modified_fd"].d, rel: 1e-7), "\(tag) modified vs finite difference")184 #expect(isClose(a.convexity, c["convexity_fd"].d, rel: 2e-5), "\(tag) convexity \(a.convexity) vs FD \(c["convexity_fd"].d)")185 #expect(isClose(a.dv01, c["dv01"].d, rel: 1e-12), "\(tag) DV01")186 if c["coupon"].d > 0 { #expect(isClose(a.currentYield, c["current_yield"].d, rel: 1e-12), "\(tag) current yield") }187 let back = try bond.yieldToMaturity(settlement: settle, cleanPrice: a.cleanPrice)188 #expect(isClose(back, y, rel: 1e-10, abs: 1e-13), "\(tag) yield round trip \(back)")189 #expect(isClose(back, c["yield_back"].d, rel: 1e-9, abs: 1e-12))190 let flows = try bond.cashFlows(settlement: settle)191 #expect(flows.count == c["n"].i && flows.last?.date == bond.maturity)192 }193 }194195 @Test func excelDocumentedExamples() throws {196 // PRICE("2008-02-15","2017-11-15",5.75%,6.5%,100,2,0) = 94.63436197 let b = Bond(maturity: CalendarDate(2017, 11, 15), couponRate: 0.0575, frequency: 2, dayCount: .thirty360US)198 #expect(isClose(try b.cleanPrice(settlement: CalendarDate(2008, 2, 15), yield: 0.065), 94.63436, abs: 5e-6))199 // YIELD("2008-02-15","2016-11-15",5.75%,95.04287,100,2,0) = 6.5 %200 let b2 = Bond(maturity: CalendarDate(2016, 11, 15), couponRate: 0.0575, frequency: 2, dayCount: .thirty360US)201 #expect(isClose(try b2.yieldToMaturity(settlement: CalendarDate(2008, 2, 15), cleanPrice: 95.04287), 0.065, abs: 5e-7)) // price quoted to 5 decimals202 // DURATION("2018-07-01","2048-01-01",8%,9%,2,1) = 10.9191453203 let b3 = Bond(maturity: CalendarDate(2048, 1, 1), couponRate: 0.08, frequency: 2, dayCount: .actualActualICMA)204 #expect(isClose(try b3.analytics(settlement: CalendarDate(2018, 7, 1), yield: 0.09).macaulayDuration, 10.9191453, abs: 5e-8))205 // MDURATION("2008-01-01","2016-01-01",8%,9%,2,1) = 5.736206 let b4 = Bond(maturity: CalendarDate(2016, 1, 1), couponRate: 0.08, frequency: 2, dayCount: .actualActualICMA)207 #expect(isClose(try b4.analytics(settlement: CalendarDate(2008, 1, 1), yield: 0.09).modifiedDuration, 5.73567, abs: 5e-6))208 }209210 @Test func closedForms() throws {211 // at a coupon date, a par bond prices at exactly 100 when yield = coupon212 let par = Bond(maturity: CalendarDate(2034, 6, 15), couponRate: 0.045, frequency: 2)213 let s = CalendarDate(2024, 6, 15)214 #expect(isClose(try par.cleanPrice(settlement: s, yield: 0.045), 100, rel: 1e-13))215 #expect(try par.accruedInterest(settlement: s) == 0)216 // annuity closed form: P = c/y·(1 − v^n)·100 + 100·v^n217 let y = 0.06, v = 1 / (1 + y / 2), n = 20.0218 #expect(isClose(try par.cleanPrice(settlement: s, yield: y), 100 * 0.045 / y * (1 - pow(v, n)) + 100 * pow(v, n), rel: 1e-13))219 // price falls when yield rises; convexity is positive220 let a = try par.analytics(settlement: s, yield: y)221 #expect(a.convexity > 0 && a.modifiedDuration < a.macaulayDuration)222 let up = try par.dirtyPrice(settlement: s, yield: y + 0.0001), down = try par.dirtyPrice(settlement: s, yield: y - 0.0001)223 #expect(up < a.dirtyPrice && a.dirtyPrice < down)224 #expect(isClose((down - up) / 2, a.dv01, rel: 1e-6)) // DV01 ≈ central difference for 1 bp225 // second-order Taylor estimate of a 100 bp move is accurate to a few cents226 let dy = 0.01227 let est = a.dirtyPrice * (1 - a.modifiedDuration * dy + 0.5 * a.convexity * dy * dy)228 #expect(abs(est - (try par.dirtyPrice(settlement: s, yield: y + dy))) < 0.02)229 // zero-coupon: Macaulay duration = time to maturity; price matches the closed form230 let zero = Bond(maturity: CalendarDate(2034, 6, 15), couponRate: 0, frequency: 2)231 let za = try zero.analytics(settlement: s, yield: 0.05)232 #expect(isClose(za.macaulayDuration, 10, rel: 1e-13))233 #expect(isClose(za.cleanPrice, Bond.zeroCouponPrice(yield: 0.05, years: 10), rel: 1e-13))234 #expect(isClose(Bond.zeroCouponPrice(yield: 0.05, years: 10), 100 / pow(1.025, 20), rel: 1e-14))235 #expect(isClose(Bond.zeroCouponYield(price: Bond.zeroCouponPrice(yield: 0.0375, years: 7.25, compoundingPerYear: 1), years: 7.25, compoundingPerYear: 1), 0.0375, rel: 1e-12))236 #expect(isClose(za.convexity, 10 * 10.5 / (1.025 * 1.025), rel: 1e-12))237 }238239 @Test func curveAndValidation() throws {240 let b = Bond(maturity: CalendarDate(2030, 3, 31), couponRate: 0.03, frequency: 2, dayCount: .actualActualICMA)241 let s = CalendarDate(2024, 5, 10)242 let curve = try b.priceYieldCurve(settlement: s, from: 0, to: 0.1, steps: 20)243 #expect(curve.count == 21 && curve[0].yield == 0 && isClose(curve[20].yield, 0.1, rel: 1e-14))244 #expect(zip(curve, curve.dropFirst()).allSatisfy { $0.cleanPrice > $1.cleanPrice }) // monotone decreasing245 #expect(isClose(curve[6].cleanPrice, try b.cleanPrice(settlement: s, yield: 0.03), rel: 1e-12))246 // month-end sticky schedule247 let cp = try b.couponPeriod(settlement: s)248 #expect(cp.previousCoupon == CalendarDate(2024, 3, 31) && cp.nextCoupon == CalendarDate(2024, 9, 30))249 #expect(isClose(curve[0].dirtyPrice, 100 + 1.5 * Double(cp.remainingCoupons), rel: 1e-13)) // zero yield: undiscounted sum250 let fromPrice = try b.analytics(settlement: s, cleanPrice: 97.25)251 #expect(isClose(fromPrice.cleanPrice, 97.25, rel: 1e-11) && fromPrice.table().count == 14)252 #expect(isClose(b.currentYield(cleanPrice: 96), 3.0 / 96, rel: 1e-15))253 #expect(throws: StatError.self) { try b.cleanPrice(settlement: CalendarDate(2031, 1, 1), yield: 0.03) }254 #expect(throws: StatError.self) { try Bond(maturity: b.maturity, couponRate: 0.03, frequency: 3).cleanPrice(settlement: s, yield: 0.03) }255 #expect(throws: StatError.self) { try b.yieldToMaturity(settlement: s, cleanPrice: -5) }256 #expect(throws: StatError.self) { try b.dirtyPrice(settlement: s, yield: -2.5) }257 }258}259