SPB Git

Repository Public

Bond.swift 18.2 KB 364 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAnalytics/Sources/FinanceModels/FixedIncome/Bond.swift10// Module           : FinanceModels11// 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 Statistics9091/// How a bond measures the fraction of a coupon period from settlement to the next coupon (w).92///93/// The two conventions give the same w for the 30/360 and ACT/ACT day counts; they differ for94/// ACT/360 and ACT/365 Fixed, where the nominal period length E (360/f or 365/f) is not the actual95/// number of days between the two coupon dates.96public enum BondPricingConvention: String, Sendable, Codable, CaseIterable {97    /// w = (E − A)/E in every day count: what Excel's PRICE, YIELD, DURATION and MDURATION compute.98    /// A bond at par on a coupon date prices at exactly 100 in all bases.99    case excel100    /// w = DSC/E with DSC the actual days from settlement to the next coupon date for the actual101    /// day counts (the formula printed in Excel's documentation, which Excel's results do not follow102    /// in ACT/360 and ACT/365).103    case streetActual104}105106/// A fixed-coupon bullet bond quoted per 100 of face value.107///108/// Coupon dates are stepped back from maturity in whole coupon periods (month-end sticky when maturity109/// is a month end), cash flows are discounted at y/f per period with a fractional first period w chosen110/// by `convention` (default `.excel`: w = (E − A)/E, identical to the PRICE/YIELD/DURATION worksheet111/// functions), and a bond in its last coupon period is priced with simple interest.112public struct Bond: Sendable, Hashable, Codable {113    public var maturity: CalendarDate114    /// Annual coupon rate as a decimal (0.0575 = 5.75 %). 0 = zero-coupon bond.115    public var couponRate: Double116    /// Coupons per year: 1, 2, 4 or 12. For a zero-coupon bond it is the compounding frequency of the yield.117    public var frequency: Int118    /// Redemption value per 100 face.119    public var redemption: Double120    public var dayCount: DayCountConvention121    /// How the time to the next coupon is measured (see `BondPricingConvention`).122    public var convention: BondPricingConvention123124    public init(maturity: CalendarDate, couponRate: Double, frequency: Int = 2, redemption: Double = 100, dayCount: DayCountConvention = .thirty360US,125                convention: BondPricingConvention = .excel) {126        self.maturity = maturity; self.couponRate = couponRate; self.frequency = frequency; self.redemption = redemption; self.dayCount = dayCount127        self.convention = convention128    }129130    private enum CodingKeys: String, CodingKey { case maturity, couponRate, frequency, redemption, dayCount, convention }131132    /// Decodes a bond; a value encoded before `convention` existed gets `.excel`.133    public init(from decoder: any Decoder) throws {134        let c = try decoder.container(keyedBy: CodingKeys.self)135        maturity = try c.decode(CalendarDate.self, forKey: .maturity)136        couponRate = try c.decode(Double.self, forKey: .couponRate)137        frequency = try c.decode(Int.self, forKey: .frequency)138        redemption = try c.decode(Double.self, forKey: .redemption)139        dayCount = try c.decode(DayCountConvention.self, forKey: .dayCount)140        convention = try c.decodeIfPresent(BondPricingConvention.self, forKey: .convention) ?? .excel141    }142143    /// Position of a settlement date in the coupon schedule.144    public struct CouponPeriod: Sendable, Hashable, Codable {145        public var previousCoupon: CalendarDate146        public var nextCoupon: CalendarDate147        /// Coupons still to be paid after settlement (N).148        public var remainingCoupons: Int149        /// Accrued days A (previous coupon → settlement) under the day count.150        public var accruedDays: Double151        /// Days in the coupon period E.152        public var periodDays: Double153        /// Days from settlement to the next coupon DSC: actual days for the actual day counts, E − A for the 30/360 family.154        public var daysToNextCoupon: Double155        /// w, the fraction of a period until the next coupon: (E − A)/E under `.excel`, DSC/E under `.streetActual`.156        public var fractionToNextCoupon: Double157    }158159    public struct CashFlow: Sendable, Hashable, Codable {160        public var date: CalendarDate161        public var amount: Double162        /// Time from settlement in coupon periods (k − 1 + w).163        public var periods: Double164        /// Time from settlement in years (periods / frequency).165        public var years: Double166    }167168    private func check(_ settlement: CalendarDate) throws {169        guard [1, 2, 4, 12].contains(frequency) else { throw StatError.invalidInput("coupon frequency must be 1, 2, 4 or 12") }170        guard settlement < maturity else { throw StatError.invalidInput("settlement must be before maturity") }171        guard couponRate >= 0, redemption > 0 else { throw StatError.invalidInput("coupon must be ≥ 0 and redemption > 0") }172    }173174    /// The coupon date k periods before maturity.175    private func couponDate(back k: Int) -> CalendarDate {176        maturity.addingMonths(-k * 12 / frequency, endOfMonth: maturity.isLastDayOfMonth)177    }178179    public func couponPeriod(settlement: CalendarDate) throws -> CouponPeriod {180        try check(settlement)181        // estimate the number of periods, then adjust182        var n = max(1, Int(Double(settlement.days(to: maturity)) / 365.25 * Double(frequency)))183        while couponDate(back: n) > settlement { n += 1 }184        while n > 1 && couponDate(back: n - 1) <= settlement { n -= 1 }185        let prev = couponDate(back: n), next = couponDate(back: n - 1)186        let f = Double(frequency)187        let a: Double, e: Double, dsc: Double188        switch dayCount {189        case .thirty360US, .thirty360SIA, .thirty360ISDA, .thirtyE360:190            a = Double(DayCount.days(from: prev, to: settlement, convention: dayCount)); e = 360 / f; dsc = e - a191        case .actual360:192            a = Double(prev.days(to: settlement)); e = 360 / f; dsc = Double(settlement.days(to: next))193        case .actual365Fixed:194            a = Double(prev.days(to: settlement)); e = 365 / f; dsc = Double(settlement.days(to: next))195        case .actualActualISDA, .actualActualICMA:196            a = Double(prev.days(to: settlement)); e = Double(prev.days(to: next)); dsc = Double(settlement.days(to: next))197        }198        let w = convention == .excel ? (e - a) / e : dsc / e199        return CouponPeriod(previousCoupon: prev, nextCoupon: next, remainingCoupons: n, accruedDays: a, periodDays: e, daysToNextCoupon: dsc,200                            fractionToNextCoupon: w)201    }202203    /// Coupon per period per 100 face.204    public var couponPayment: Double { 100 * couponRate / Double(frequency) }205206    /// Remaining cash flows (coupons and redemption) with their timing.207    public func cashFlows(settlement: CalendarDate) throws -> [CashFlow] {208        let cp = try couponPeriod(settlement: settlement)209        let w = cp.fractionToNextCoupon210        var out = [CashFlow]()211        for k in 1...cp.remainingCoupons {212            let t = Double(k - 1) + w213            let amount = couponPayment + (k == cp.remainingCoupons ? redemption : 0)214            out.append(CashFlow(date: couponDate(back: cp.remainingCoupons - k), amount: amount, periods: t, years: t / Double(frequency)))215        }216        return out217    }218219    /// Accrued interest per 100 face: coupon × A / E.220    public func accruedInterest(settlement: CalendarDate) throws -> Double {221        let cp = try couponPeriod(settlement: settlement)222        return couponPayment * cp.accruedDays / cp.periodDays223    }224225    /// Dirty (full, invoice) price per 100 face at an annual yield compounded `frequency` times a year.226    public func dirtyPrice(settlement: CalendarDate, yield y: Double) throws -> Double {227        let cp = try couponPeriod(settlement: settlement)228        let f = Double(frequency), w = cp.fractionToNextCoupon229        guard 1 + y / f > 0 else { throw StatError.invalidInput("yield per period must be greater than −100 %") }230        if cp.remainingCoupons == 1 {231            return (redemption + couponPayment) / (1 + w * y / f)232        }233        let lg = log1p(y / f)234        var pv = 0.0235        for k in 1...cp.remainingCoupons { pv += couponPayment * exp(-(Double(k - 1) + w) * lg) }236        return pv + redemption * exp(-(Double(cp.remainingCoupons - 1) + w) * lg)237    }238239    /// Clean (quoted) price = dirty price − accrued interest. With `convention == .excel` this is Excel's PRICE.240    public func cleanPrice(settlement: CalendarDate, yield: Double) throws -> Double {241        try dirtyPrice(settlement: settlement, yield: yield) - accruedInterest(settlement: settlement)242    }243244    /// Yield to maturity for a clean price (Excel YIELD under `.excel`), by Brent's method (closed form in the last coupon period).245    public func yieldToMaturity(settlement: CalendarDate, cleanPrice: Double) throws -> Double {246        guard cleanPrice > 0 else { throw StatError.invalidInput("price must be positive") }247        let cp = try couponPeriod(settlement: settlement)248        let f = Double(frequency)249        let dirty = cleanPrice + couponPayment * cp.accruedDays / cp.periodDays250        if cp.remainingCoupons == 1 {251            return ((redemption + couponPayment) / dirty - 1) * f / cp.fractionToNextCoupon252        }253        let g: (Double) throws -> Double = { try self.dirtyPrice(settlement: settlement, yield: $0) - dirty }254        var lo = -0.5 * f, hi = 1.0255        var expansions = 0256        while try g(hi) > 0, expansions < 60 { hi *= 2; expansions += 1 }257        while try g(lo) < 0, expansions < 120 { lo = -f + (lo + f) / 2; expansions += 1 }258        let r = try RootFinder.brent(g, lower: lo, upper: hi, xtol: 1e-15, maxIterations: 300)259        guard r.converged else { throw StatError.notConverged("yield solver") }260        return r.root261    }262263    /// Annual coupon divided by the clean price.264    public func currentYield(cleanPrice: Double) -> Double { 100 * couponRate / cleanPrice }265266    public struct Analytics: Sendable, Hashable, Codable, TableReport {267        public var settlement: CalendarDate268        public var yield: Double269        public var cleanPrice: Double270        public var dirtyPrice: Double271        public var accruedInterest: Double272        public var currentYield: Double273        /// Present-value-weighted average time to the cash flows, in years (Excel DURATION under `.excel` for a redemption of 100).274        public var macaulayDuration: Double275        /// Macaulay ÷ (1 + y/f) (Excel MDURATION): −(1/P)·dP/dy.276        public var modifiedDuration: Double277        /// (1/P)·d²P/dy², in years².278        public var convexity: Double279        /// Price change per 100 face for a one-basis-point fall in yield: modified duration × dirty price × 0.0001.280        public var dv01: Double281        public var remainingCoupons: Int282        public var previousCoupon: CalendarDate283        public var nextCoupon: CalendarDate284285        public func table() -> [[Value]] {286            [287                [.text("Bond analytics"), .text("per 100 face")],288                Report.row("Settlement", settlement.description),289                Report.row("Yield to maturity", yield),290                Report.row("Clean price", cleanPrice),291                Report.row("Accrued interest", accruedInterest),292                Report.row("Dirty price", dirtyPrice),293                Report.row("Current yield", currentYield),294                Report.row("Macaulay duration (years)", macaulayDuration),295                Report.row("Modified duration", modifiedDuration),296                Report.row("Convexity", convexity),297                Report.row("DV01", dv01),298                Report.row("Remaining coupons", remainingCoupons),299                Report.row("Previous coupon", previousCoupon.description),300                Report.row("Next coupon", nextCoupon.description),301            ]302        }303    }304305    /// Full analytics at a yield. Duration and convexity always use compound discounting of every flow306    /// (as Excel's DURATION does), including in the last coupon period.307    public func analytics(settlement: CalendarDate, yield y: Double) throws -> Analytics {308        let cp = try couponPeriod(settlement: settlement)309        let f = Double(frequency)310        guard 1 + y / f > 0 else { throw StatError.invalidInput("yield per period must be greater than −100 %") }311        let flows = try cashFlows(settlement: settlement)312        let lg = log1p(y / f)313        var pv = 0.0, weighted = 0.0, conv = 0.0314        for cf in flows {315            let v = cf.amount * exp(-cf.periods * lg)316            pv += v317            weighted += v * cf.periods318            conv += v * cf.periods * (cf.periods + 1)319        }320        let mac = weighted / pv / f321        let dirty = try dirtyPrice(settlement: settlement, yield: y)322        let accrued = couponPayment * cp.accruedDays / cp.periodDays323        let mod = mac / (1 + y / f)324        return Analytics(settlement: settlement, yield: y, cleanPrice: dirty - accrued, dirtyPrice: dirty, accruedInterest: accrued,325                         currentYield: 100 * couponRate / (dirty - accrued), macaulayDuration: mac, modifiedDuration: mod,326                         convexity: conv / pv / (f * f) / ((1 + y / f) * (1 + y / f)), dv01: mod * dirty * 1e-4,327                         remainingCoupons: cp.remainingCoupons, previousCoupon: cp.previousCoupon, nextCoupon: cp.nextCoupon)328    }329330    /// Analytics from a quoted clean price (solves the yield first).331    public func analytics(settlement: CalendarDate, cleanPrice: Double) throws -> Analytics {332        try analytics(settlement: settlement, yield: yieldToMaturity(settlement: settlement, cleanPrice: cleanPrice))333    }334335    public struct CurvePoint: Sendable, Hashable, Codable {336        public var yield: Double337        public var cleanPrice: Double338        public var dirtyPrice: Double339    }340341    /// Price–yield curve data on an evenly spaced grid of yields (for charting).342    public func priceYieldCurve(settlement: CalendarDate, from: Double, to: Double, steps: Int = 50) throws -> [CurvePoint] {343        guard steps >= 1, from < to else { throw StatError.invalidInput("need from < to and at least one step") }344        let accrued = try accruedInterest(settlement: settlement)345        return try (0...steps).map { k in346            let y = from + (to - from) * Double(k) / Double(steps)347            let d = try dirtyPrice(settlement: settlement, yield: y)348            return CurvePoint(yield: y, cleanPrice: d - accrued, dirtyPrice: d)349        }350    }351352    // MARK: Zero-coupon closed forms353354    /// Price per `redemption` of a zero-coupon bond: R / (1 + y/m)^(m·T), T in years.355    public static func zeroCouponPrice(yield y: Double, years: Double, compoundingPerYear m: Double = 2, redemption: Double = 100) -> Double {356        redemption * exp(-m * years * log1p(y / m))357    }358359    /// Yield of a zero-coupon bond from its price: m·((R/P)^(1/(m·T)) − 1).360    public static func zeroCouponYield(price: Double, years: Double, compoundingPerYear m: Double = 2, redemption: Double = 100) -> Double {361        m * expm1(log(redemption / price) / (m * years))362    }363}364
Files main
Menu

Theme