SPB Git

Repository Public MIT

RateConventionTests.swift 10.7 KB 206 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Calc9// File             : Packages/ORIXUnits/Tests/ORIXUnitsTests/RateConventionTests.swift10// Description      : Financial rate conventions against closed forms and the11//                    50-digit Python reference.12// Module           : ORIXUnitsTests13// Repository       : https://git.spboucher.ai/orix-calc14// Created          : 2026-11-2015// Last Modified    : 2026-11-2016//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : Proprietary, all rights reserved (see license file)82// License File     : LICENSE83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import Foundation91import Testing9293@testable import ORIXUnits9495@Suite("Rate conventions")96struct RateConventionTests {97    private func convention(_ kind: String, _ periods: Int) -> RateConvention {98        switch kind {99        case "effective": .effectiveAnnual100        case "nominal": .nominal(periodsPerYear: periods)101        case "periodic": .periodic(periodsPerYear: periods)102        case "continuous": .continuous103        case "discount": .effectiveDiscount104        case "nominalDiscount": .nominalDiscount(periodsPerYear: periods)105        default: fatalError("unknown convention \(kind)")106        }107    }108109    @Test("Closed forms")110    func closedForms() throws {111        // 6 % nominal semi-annual = (1.03)² − 1 = 6.09 % effective.112        let effective = try RateConverter.convertRate(0.06, from: .semiannual, to: .effectiveAnnual)113        #expect(isClose(effective, 0.0609, relative: 1e-15))114        // … = 12 × (1.0609^(1/12) − 1) nominal monthly = 5.926346437436374… %.115        let monthly = try RateConverter.convertRate(0.06, from: .semiannual, to: .monthly)116        #expect(isClose(monthly, 0.05926346437436374, relative: 1e-14))117        #expect(isClose(monthly, 12 * (pow(1.0609, 1.0 / 12.0) - 1), relative: 1e-13))118        // Continuous: e^0.05 − 1.119        #expect(isClose(try RateConverter.convertRate(0.05, from: .continuous, to: .effectiveAnnual), exp(0.05) - 1, relative: 1e-14))120        #expect(isClose(try RateConverter.convertRate(0.10, from: .effectiveAnnual, to: .continuous), log(1.10), relative: 1e-15))121        // Discount: d = i / (1 + i); i = 25 % ⇔ d = 20 %.122        #expect(isClose(try RateConverter.convertRate(0.25, from: .effectiveAnnual, to: .effectiveDiscount), 0.2, relative: 1e-15))123        #expect(isClose(try RateConverter.convertRate(0.2, from: .effectiveDiscount, to: .effectiveAnnual), 0.25, relative: 1e-15))124        // Periodic: 1 % a month = 12 % nominal monthly = 1.01¹² − 1 effective.125        #expect(isClose(try RateConverter.convertRate(0.01, from: .periodic(periodsPerYear: 12), to: .monthly), 0.12, relative: 1e-15))126        #expect(isClose(try RateConverter.convertRate(0.01, from: .periodic(periodsPerYear: 12), to: .effectiveAnnual), pow(1.01, 12) - 1, relative: 1e-14))127        // Nominal annual with one period is the effective rate.128        #expect(isClose(try RateConverter.convertRate(0.07, from: .annual, to: .effectiveAnnual), 0.07, relative: 1e-15))129        // Canadian fixed mortgage: 5 % semi-annual → monthly periodic rate 1.025^(1/6) − 1.130        let mortgage = try RateConverter.convertRate(0.05, from: .semiannual, to: .periodic(periodsPerYear: 12))131        #expect(isClose(mortgage, pow(1.025, 1.0 / 6.0) - 1, relative: 1e-13))132        // Daily compounding approaches continuous compounding from below.133        let daily = try RateConverter.effectiveAnnualRate(0.06, in: .daily)134        let continuous = try RateConverter.effectiveAnnualRate(0.06, in: .continuous)135        let weekly = try RateConverter.effectiveAnnualRate(0.06, in: .weekly)136        #expect(weekly < daily && daily < continuous)137        #expect(isClose(daily, 0.06183131067785370, relative: 1e-12))138        // Zero stays zero everywhere.139        for target in RateConvention.common {140            #expect(try RateConverter.convertRate(0, from: .monthly, to: target) == 0)141        }142        #expect(isClose(try RateConverter.accumulationFactor(0.06, in: .semiannual, years: 10), pow(1.03, 20), relative: 1e-14))143    }144145    @Test("Reference table (Python decimal, 50 digits)")146    func referenceTable() throws {147        var checked = 0148        for line in referenceRatesTSV.split(separator: "\n") {149            let fields = line.split(separator: "\t").map(String.init)150            try #require(fields.count == 6)151            let rate = try #require(Double(fields[0]))152            let from = convention(fields[1], try #require(Int(fields[2])))153            let to = convention(fields[3], try #require(Int(fields[4])))154            let expected = try #require(Double(fields[5]))155            let result = try RateConverter.convertRate(rate, from: from, to: to)156            #expect(isClose(result, expected, relative: 2e-13), "\(line): got \(result)")157            checked += 1158        }159        #expect(checked >= 900)160    }161162    @Test("Tiny rates keep their relative precision (log1p / expm1)")163    func tinyRates() throws {164        // i = (1 + j/12)^12 − 1 = j + (11/24) j² + O(j³).165        let j = 1e-9166        let effective = try RateConverter.convertRate(j, from: .monthly, to: .effectiveAnnual)167        #expect(isClose(effective, j + 11.0 / 24.0 * j * j, relative: 1e-15))168        let force = try RateConverter.convertRate(1e-12, from: .effectiveAnnual, to: .continuous)169        #expect(isClose(force, 1e-12 - 0.5e-24, relative: 1e-15))170    }171172    @Test("Round trips and identity")173    func roundTrips() throws {174        let conventions = RateConvention.common + [.periodic(periodsPerYear: 12), .nominalDiscount(periodsPerYear: 4)]175        for from in conventions {176            for to in conventions {177                for rate in [0.0001, 0.035, 0.08, -0.02] {178                    let there = try RateConverter.convertRate(rate, from: from, to: to)179                    let back = try RateConverter.convertRate(there, from: to, to: from)180                    #expect(isClose(back, rate, relative: 1e-12), "\(rate) \(from) → \(to) → \(back)")181                }182            }183            #expect(try RateConverter.convertRate(0.0437, from: from, to: from) == 0.0437)184            #expect(!from.name.isEmpty)185        }186        #expect(RateConvention.semiannual == .nominal(periodsPerYear: 2))187        #expect(RateConvention.daily == .nominal(periodsPerYear: 365))188        #expect(RateConvention.nominal(periodsPerYear: 7).name.contains("7"))189    }190191    @Test("Domain errors")192    func domain() {193        #expect(throws: UnitError.self) { try RateConverter.convertRate(-1, from: .effectiveAnnual, to: .monthly) }194        #expect(throws: UnitError.self) { try RateConverter.convertRate(-12, from: .monthly, to: .effectiveAnnual) }195        #expect(throws: UnitError.self) { try RateConverter.convertRate(1, from: .effectiveDiscount, to: .effectiveAnnual) }196        #expect(throws: UnitError.self) { try RateConverter.convertRate(4, from: .nominalDiscount(periodsPerYear: 4), to: .continuous) }197        #expect(throws: UnitError.self) { try RateConverter.convertRate(-1, from: .periodic(periodsPerYear: 12), to: .continuous) }198        #expect(throws: UnitError.self) { try RateConverter.convertRate(0.05, from: .nominal(periodsPerYear: 0), to: .continuous) }199        #expect(throws: UnitError.self) { try RateConverter.convertRate(0.05, from: .continuous, to: .periodic(periodsPerYear: -1)) }200        #expect(throws: UnitError.self) { try RateConverter.convertRate(.nan, from: .continuous, to: .monthly) }201        #expect(throws: UnitError.self) { try RateConverter.convertRate(.infinity, from: .continuous, to: .monthly) }202        #expect(throws: UnitError.self) { try RateConverter.convertRate(-2, from: .effectiveAnnual, to: .effectiveAnnual) }203        #expect(throws: UnitError.self) { try RateConverter.accumulationFactor(.nan, in: .monthly, years: 1) }204    }205}206
Files main
Menu

Theme