Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/FeatureAnalysis/Sources/FinanceStudio/FixedIncome/BondTool.swift10// Module : FinanceStudio11// 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 SheetCore89import SheetCharts90import FinanceModels91import AnalysisKit9293/// Fixed-coupon bond analytics.94enum BondTool {95 static let dayCounts: [(DayCountConvention, String)] = [96 (.thirty360US, "30/360 US (Excel)"), (.thirty360SIA, "30/360 US (SIA)"), (.thirty360ISDA, "30/360 ISDA"), (.thirtyE360, "30E/360"),97 (.actual360, "ACT/360"), (.actual365Fixed, "ACT/365 Fixed"), (.actualActualISDA, "ACT/ACT ISDA"), (.actualActualICMA, "ACT/ACT ICMA"),98 ]99100 /// Label of a pricing convention; `.excel` is the default and matches the PRICE/YIELD/DURATION worksheet functions.101 static func label(_ c: BondPricingConvention) -> String {102 switch c {103 case .excel: L("Excel: w = (E − A)/E")104 case .streetActual: L("Street: w = DSC/E, actual days")105 }106 }107108 static let descriptor: ToolDescriptor = {109 var t = ToolDescriptor(110 id: "finance.bond", title: L("Bond Analytics"), group: FinGroup.fixedIncome, systemImage: "doc.text.magnifyingglass",111 summary: L("Price or yield of a fixed-coupon bond with accrued interest, duration, convexity and DV01, and its price–yield curve."),112 fields: [113 .date("settlement", L("Settlement date"), Fin.date(2026, 3, 15)),114 .date("maturity", L("Maturity date"), Fin.date(2034, 6, 1)),115 .percent("coupon", L("Annual coupon rate"), 0.0425, min: 0),116 .choice("frequency", L("Coupons per year"), [FieldOption("1", L("Annual")), FieldOption("2", L("Semi-annual")), FieldOption("4", L("Quarterly")),117 FieldOption("12", L("Monthly"))], default: "2"),118 .number("redemption", L("Redemption value"), 100, min: 0.01, unit: L("per 100 of face value")),119 .choice("daycount", L("Day-count basis"), dayCounts.map { FieldOption($0.0.rawValue, $0.1) }),120 .choice("convention", L("Time to the next coupon"), BondPricingConvention.allCases.map { FieldOption($0.rawValue, label($0)) },121 default: BondPricingConvention.excel.rawValue),122 .choice("mode", L("Compute"), [FieldOption("price", L("Price from yield")), FieldOption("yield", L("Yield from clean price"))]),123 .percent("yield", L("Yield to maturity"), 0.0465, min: -0.5, visible: { $0.choice("mode") != "yield" }),124 .number("price", L("Clean price"), 97.25, min: 0.01, unit: L("per 100 of face value"), visible: { $0.choice("mode") == "yield" }),125 ],126 conventions: [127 L("Quotes are per 100 of face value. The yield is an annual rate compounded as often as the coupons are paid."),128 L("Coupon dates are stepped back from maturity in 12/f-month steps; when maturity is a month end, all coupon dates are month ends (Excel behaviour)."),129 L("Accrued interest = (100·c/f)·A/E, with A the accrued days and E the days in the coupon period under the chosen day count (30/360 and ACT/360: E = 360/f; ACT/365F: 365/f; ACT/ACT: actual days)."),130 L("Day counts: 30/360 US (Excel) is Excel's basis 0 and gives the same result as the YEARFRAC and PRICE worksheet functions; 30/360 US (SIA) and 30/360 ISDA are the published SIA and ISDA rules, which differ from it only when a period starts on the last day of February."),131 L("Dirty price = Σ (100·c/f)/(1+y/f)^(k−1+w) + R/(1+y/f)^(N−1+w), where w is the fraction of a coupon period until the next coupon; with one coupon left, simple interest is used as in Excel PRICE. Clean price = dirty − accrued."),132 L("Time to the next coupon: with the Excel convention (default) w = (E − A)/E in every day count, so the results equal the PRICE, YIELD, DURATION and MDURATION worksheet functions. With the street convention w = DSC/E, DSC being the actual days from settlement to the next coupon. The two differ only for ACT/360 and ACT/365 Fixed."),133 L("Macaulay duration = Σ t·PV / Σ PV (years); modified duration = Macaulay / (1 + y/f); convexity = Σ PV·n(n+1) / (P·f²·(1+y/f)²); DV01 = modified duration × dirty price × 0.0001 per 100 of face value."),134 L("The yield inverts the clean price by Brent's method. Current yield = 100·c / clean price."),135 L("Not modelled: odd first or last coupons, ex-dividend periods, settlement-day conventions, callable, amortizing, floating-rate and inflation-linked bonds."),136 ],137 runTitle: L("Compute"),138 run: run)139 t.demo = { _, _ in }140 return t141 }()142143 static func bond(_ v: FormValues) -> Bond {144 Bond(maturity: Fin.calendarDate(v.date("maturity")), couponRate: v.number("coupon"), frequency: Int(v.choice("frequency")) ?? 2,145 redemption: v.number("redemption"), dayCount: DayCountConvention(rawValue: v.choice("daycount")) ?? .thirty360US,146 convention: BondPricingConvention(rawValue: v.choice("convention")) ?? .excel)147 }148149 static func run(_ input: ToolInput) throws -> ToolResult {150 let v = input.values, loc = input.locale151 let b = bond(v)152 let settlement = Fin.calendarDate(v.date("settlement"))153 try Fin.require(settlement < b.maturity, L("The settlement date must be before the maturity date."))154 let fromPrice = v.choice("mode") == "yield"155 let a = fromPrice ? try b.analytics(settlement: settlement, cleanPrice: v.number("price")) : try b.analytics(settlement: settlement, yield: v.number("yield"))156 let basis = dayCounts.first { $0.0 == b.dayCount }?.1 ?? ""157158 let metrics = [fromPrice ? Metric(L("Yield to maturity"), a.yield, .percent(4)) : Metric(L("Clean price"), a.cleanPrice, .fixed(4)),159 Metric(L("Dirty price"), a.dirtyPrice, .fixed(4)), Metric(L("Accrued interest"), a.accruedInterest, .fixed(4)),160 Metric(L("Modified duration"), a.modifiedDuration, .fixed(4), detail: L("years")), Metric("DV01", a.dv01, .fixed(5))]161 let d1904 = input.date1904162 let table = ReportTable.keyValue(title: L("Bond analytics"), header: (L("Quantity"), L("Value")), [163 (L("Settlement date"), .number(settlement.serial(date1904: d1904)), .date), (L("Maturity date"), .number(b.maturity.serial(date1904: d1904)), .date),164 (L("Annual coupon rate"), .number(b.couponRate), .percent(3)), (L("Coupons per year"), .number(Double(b.frequency)), .integer),165 (L("Day-count basis"), .text(basis), .auto), (L("Time to the next coupon"), .text(label(b.convention)), .auto),166 (L("Yield to maturity"), .number(a.yield), .percent(4)), (L("Clean price"), .number(a.cleanPrice), .fixed(5)),167 (L("Accrued interest"), .number(a.accruedInterest), .fixed(5)), (L("Dirty price"), .number(a.dirtyPrice), .fixed(5)),168 (L("Current yield"), .number(a.currentYield), .percent(4)),169 (L("Macaulay duration (years)"), .number(a.macaulayDuration), .fixed(5)), (L("Modified duration (years)"), .number(a.modifiedDuration), .fixed(5)),170 (L("Convexity (years²)"), .number(a.convexity), .fixed(4)), (L("DV01 (per 100 of face value)"), .number(a.dv01), .fixed(6)),171 (L("Previous coupon date"), .number(a.previousCoupon.serial(date1904: d1904)), .date), (L("Next coupon date"), .number(a.nextCoupon.serial(date1904: d1904)), .date),172 (L("Remaining coupons"), .number(Double(a.remainingCoupons)), .integer),173 ], note: L("Prices per 100 of face value."))174175 let flows = try b.cashFlows(settlement: settlement)176 var flowRows: [[Value]] = [[.text(L("Payment date")), .text(L("Cash flow")), .text(L("Time (years)")), .text(L("Present value"))]]177 for f in flows { flowRows.append([.number(f.date.serial(date1904: d1904)), .number(f.amount), .number(f.years), .number(f.amount / pow(1 + a.yield / Double(b.frequency), f.periods))]) }178 let flowTable = ReportTable(title: L("Remaining cash flows"), rows: flowRows, headerColumn: false, columnFormats: [0: .date, 1: .fixed(4), 2: .fixed(4), 3: .fixed(4)])179180 let lo = max(a.yield - 0.03, -0.005), hi = a.yield + 0.03181 let curve = try b.priceYieldCurve(settlement: settlement, from: lo, to: hi, steps: 60)182 var spec = ChartKit.lines([.init(L("Clean price"), curve.map(\.cleanPrice), x: curve.map { $0.yield * 100 })],183 xTitle: L("Yield to maturity (%)"), yTitle: L("Clean price (per 100)"))184 Fin.mark(&spec, vertical: a.yield * 100, horizontal: a.cleanPrice)185 let chart = ChartBlock(title: L("Price–yield curve"), spec: spec,186 summary: L("Clean price falling from %@ at a yield of %@ to %@ at %@; the bond is at %@ for a yield of %@.",187 Fmt.fixed(curve.first?.cleanPrice ?? 0, 2, locale: loc), Fmt.percent(lo, 2, locale: loc),188 Fmt.fixed(curve.last?.cleanPrice ?? 0, 2, locale: loc), Fmt.percent(hi, 2, locale: loc),189 Fmt.fixed(a.cleanPrice, 2, locale: loc), Fmt.percent(a.yield, 2, locale: loc)), height: 240)190 let est = -a.modifiedDuration * a.dirtyPrice * 0.01 + 0.5 * a.convexity * a.dirtyPrice * 0.0001191 let note = L("For a 1 percentage point rise in yield, duration and convexity together estimate a price change of %@ per 100 of face value.", Fmt.fixed(est, 3, locale: loc))192 return ToolResult(title: L("Bond Analytics"),193 subtitle: L("%@ coupon due %@, settlement %@, %@", Fmt.percent(b.couponRate, 3, locale: loc), b.maturity.description, settlement.description, basis),194 blocks: [.metrics(metrics), .table(table), .chart(chart), .table(flowTable), .note([note])], sheetName: L("Bond"))195 }196}197