SPB Git

Repository Public MIT

CurrencyTests.swift 17.0 KB 326 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/CurrencyTests.swift10// Description      : Currency cross rates, staleness, manual rates,11//                    persistence, ISO 4217 list and the ECB XML parser.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/// The structure of the ECB `eurofxref-daily.xml` document; the rates are illustrative values.96private let sampleECB = """97    <?xml version="1.0" encoding="UTF-8"?>98    <gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">99    	<gesmes:subject>Reference rates</gesmes:subject>100    	<gesmes:Sender>101    		<gesmes:name>European Central Bank</gesmes:name>102    	</gesmes:Sender>103    	<Cube>104    		<Cube time='2026-11-19'>105    			<Cube currency='USD' rate='1.0543'/>106    			<Cube currency='JPY' rate='163.25'/>107    			<Cube currency='CZK' rate='25.305'/>108    			<Cube currency='GBP' rate='0.83268'/>109    			<Cube currency='CHF' rate='0.9328'/>110    			<Cube currency='CAD' rate='1.4712'/>111    			<Cube currency='AUD' rate='1.6212'/>112    			<Cube currency='MXN' rate='21.4335'/>113    			<Cube currency='IDR' rate='16785.64'/>114    		</Cube>115    	</Cube>116    </gesmes:Envelope>117    """118119@Suite("Currency")120struct CurrencyTests {121    private let published = Date(timeIntervalSince1970: 1_795_100_400)122123    private func table() throws -> CurrencyRates {124        try CurrencyRates(125            base: "EUR", rates: ["USD": dec("1.0543"), "CAD": dec("1.4712"), "JPY": dec("163.25")],126            source: "Test source", timestamp: published)127    }128129    @Test("Cross rates in Decimal")130    func crossRates() throws {131        let rates = try table()132        #expect(try rates.convert(100, from: "EUR", to: "USD") == dec("105.43"))133        #expect(try rates.convert(dec("105.43"), from: "USD", to: "EUR") == 100)134        // 100 × 1.4712 / 1.0543, to 38 digits (Python fractions).135        #expect(try rates.convert(100, from: "USD", to: "CAD") == dec("139.54282462297258844731101204590723703"))136        #expect(try rates.convert(dec("1054.3"), from: "USD", to: "CAD") == dec("1471.2"))137        #expect(try rates.convert(dec("12.34"), from: "CAD", to: "CAD") == dec("12.34"))138        #expect(try rates.convert(0, from: "CAD", to: "JPY") == 0)139        #expect(try rates.convert(-50, from: "EUR", to: "JPY") == dec("-8162.5"))140        #expect(try rates.convert(100, from: "usd", to: "eur") == rates.convert(100, from: "USD", to: "EUR"))141        #expect(try rates.crossRate(from: "EUR", to: "CAD") == dec("1.4712"))142        #expect(try rates.crossRate(from: "JPY", to: "JPY") == 1)143        let usdcad = try rates.crossRate(from: "USD", to: "CAD")144        let cadusd = try rates.crossRate(from: "CAD", to: "USD")145        #expect(isClose(usdcad * cadusd, 1, relative: dec("1e-36")))146        #expect(rates.codes == ["CAD", "EUR", "JPY", "USD"])147        #expect(rates.rate(for: "EUR") == CurrencyRates.Rate(value: 1, isManual: false))148        #expect(rates.rate(for: "XXX") == nil)149    }150151    @Test("Unknown currencies and invalid rates are typed errors")152    func errors() throws {153        let rates = try table()154        #expect(throws: UnitError.unknownCurrency("GBP")) { try rates.convert(1, from: "GBP", to: "USD") }155        #expect(throws: UnitError.unknownCurrency("GBP")) { try rates.convert(1, from: "USD", to: "gbp") }156        #expect(throws: UnitError.unknownCurrency("GBP")) { try rates.crossRate(from: "USD", to: "GBP") }157        #expect(throws: UnitError.notRepresentable) { try rates.convert(Decimal.nan, from: "USD", to: "CAD") }158        #expect(throws: UnitError.invalidRate(code: "USD")) {159            try CurrencyRates(base: "EUR", rates: ["USD": 0], source: "s", timestamp: published)160        }161        #expect(throws: UnitError.invalidRate(code: "USD")) {162            try CurrencyRates(base: "EUR", rates: ["USD": -1], source: "s", timestamp: published)163        }164        #expect(throws: UnitError.invalidRate(code: "USD")) {165            try CurrencyRates(base: "EUR", rates: ["USD": Decimal.nan], source: "s", timestamp: published)166        }167        #expect(throws: UnitError.invalidRate(code: "EUR")) {168            try CurrencyRates(base: "EUR", rates: ["EUR": 2], source: "s", timestamp: published)169        }170        var mutable = rates171        #expect(throws: UnitError.invalidRate(code: "CAD")) { try mutable.setManualRate(0, for: "CAD") }172        #expect(mutable == rates)173    }174175    @Test("Staleness: fresh, stale, threshold, clock skew")176    func staleness() throws {177        let rates = try table()178        #expect(rates.staleness(now: published) == .fresh(age: 0))179        #expect(rates.staleness(now: published.addingTimeInterval(3600)) == .fresh(age: 3600))180        #expect(rates.staleness(now: published.addingTimeInterval(86_400)) == .fresh(age: 86_400))181        #expect(rates.staleness(now: published.addingTimeInterval(86_401)) == .stale(age: 86_401))182        #expect(rates.staleness(now: published.addingTimeInterval(3 * 86_400)) == .stale(age: 259_200))183        #expect(rates.staleness(now: published.addingTimeInterval(3600), threshold: 600) == .stale(age: 3600))184        #expect(rates.staleness(now: published.addingTimeInterval(3 * 86_400), threshold: 4 * 86_400) == .fresh(age: 259_200))185        // A device clock behind the publication time never yields a negative age.186        #expect(rates.staleness(now: published.addingTimeInterval(-500)) == .fresh(age: 0))187        #expect(rates.age(now: published.addingTimeInterval(42)) == 42)188        #expect(CurrencyRates.defaultStalenessThreshold == 86_400)189        #expect(rates.staleness(from: "USD", to: "CAD", now: published.addingTimeInterval(90_000)) == .stale(age: 90_000))190    }191192    @Test("Manual rates are never reported fresh")193    func manualRates() throws {194        var rates = try table()195        #expect(!rates.usesManualRate(from: "USD", to: "CAD"))196        try rates.setManualRate(dec("1.50"), for: "cad")197        #expect(rates.rate(for: "CAD") == CurrencyRates.Rate(value: dec("1.50"), isManual: true))198        #expect(rates.usesManualRate(from: "USD", to: "CAD"))199        #expect(rates.usesManualRate(from: "CAD", to: "EUR"))200        #expect(!rates.usesManualRate(from: "USD", to: "JPY"))201        #expect(rates.staleness(now: published) == .manual)202        #expect(rates.staleness(from: "USD", to: "CAD", now: published) == .manual)203        #expect(rates.staleness(from: "USD", to: "JPY", now: published) == .fresh(age: 0))204        #expect(try rates.convert(100, from: "EUR", to: "CAD") == 150)205        // A new currency typed by hand.206        try rates.setManualRate(dec("4.2"), for: "PLN")207        #expect(try rates.convert(10, from: "EUR", to: "PLN") == 42)208        #expect(rates.staleness(from: "PLN", to: "USD", now: published) == .manual)209210        let manual = try CurrencyRates.manual(base: "cad", rates: ["USD": dec("0.72")], enteredAt: published)211        #expect(manual.base == "CAD")212        #expect(manual.staleness(now: published) == .manual)213        #expect(manual.staleness(now: published.addingTimeInterval(1e9)) == .manual)214        #expect(manual.staleness(from: "CAD", to: "USD", now: published) == .manual)215        #expect(try manual.convert(100, from: "CAD", to: "USD") == 72)216        #expect(manual.source == "Manual entry")217    }218219    @Test("Codable round trip keeps every digit, the flags and the timestamp")220    func persistence() throws {221        var rates = try CurrencyRates(222            base: "EUR", rates: ["USD": dec("1.0543"), "XAU": dec("0.000312345678901234567890123456789")],223            source: "Test source", timestamp: published)224        try rates.setManualRate(dec("1.4999"), for: "CAD")225        let data = try JSONEncoder().encode(rates)226        let decoded = try JSONDecoder().decode(CurrencyRates.self, from: data)227        #expect(decoded == rates)228        #expect(decoded.rate(for: "XAU")?.value == dec("0.000312345678901234567890123456789"))229        #expect(decoded.rate(for: "CAD")?.isManual == true)230        #expect(decoded.rate(for: "USD")?.isManual == false)231        #expect(decoded.timestamp == published)232        #expect(decoded.source == "Test source")233        #expect(decoded.staleness(now: published) == .manual)234        let json = try #require(String(data: data, encoding: .utf8))235        #expect(json.contains("\"1.0543\""))236237        let corrupted = Data(#"{"base":"EUR","source":"s","timestamp":0,"rates":{"USD":{"rate":"abc","manual":false}}}"#.utf8)238        #expect(throws: DecodingError.self) { try JSONDecoder().decode(CurrencyRates.self, from: corrupted) }239        let negative = Data(#"{"base":"EUR","source":"s","timestamp":0,"rates":{"USD":{"rate":"0","manual":false}}}"#.utf8)240        #expect(throws: DecodingError.self) { try JSONDecoder().decode(CurrencyRates.self, from: negative) }241    }242243    @Test("ISO 4217 list")244    func isoList() throws {245        let list = CurrencyInfo.common246        #expect(list.count >= 40)247        #expect(Set(list.map(\.code)).count == list.count)248        for currency in list {249            #expect(currency.code.count == 3 && currency.code == currency.code.uppercased())250            #expect(!currency.name.isEmpty)251            #expect((0...3).contains(currency.minorUnits))252            #expect(currency.id == currency.code)253        }254        #expect(CurrencyInfo.info(for: "CAD") == CurrencyInfo(code: "CAD", name: "Canadian Dollar", minorUnits: 2))255        #expect(CurrencyInfo.info(for: "jpy")?.minorUnits == 0)256        #expect(CurrencyInfo.info(for: "KRW")?.minorUnits == 0)257        #expect(CurrencyInfo.info(for: "KWD")?.minorUnits == 3)258        #expect(CurrencyInfo.info(for: "EUR")?.minorUnits == 2)259        #expect(CurrencyInfo.info(for: "ZZZ") == nil)260        for code in ["CAD", "USD", "EUR", "GBP", "JPY", "CHF", "AUD", "CNY", "MXN"] {261            #expect(CurrencyInfo.info(for: code) != nil, "\(code)")262        }263    }264265    @Test("ECB daily XML")266    func ecbParser() throws {267        let rates = try CurrencyRates.parseECB(xml: Data(sampleECB.utf8))268        #expect(rates.base == "EUR")269        #expect(rates.rates.count == 9)270        #expect(rates.rate(for: "USD")?.value == dec("1.0543"))271        #expect(rates.rate(for: "JPY")?.value == dec("163.25"))272        #expect(rates.rate(for: "IDR")?.value == dec("16785.64"))273        #expect(rates.rate(for: "GBP")?.value == dec("0.83268"))274        #expect(rates.rates.values.allSatisfy { !$0.isManual })275        #expect(rates.source == CurrencyRates.ecbSourceName)276        // 2026-11-19 16:00 CET (UTC+1) = 15:00 UTC.277        var utc = Calendar(identifier: .gregorian)278        utc.timeZone = try #require(TimeZone(identifier: "UTC"))279        let expected = try #require(utc.date(from: DateComponents(year: 2026, month: 11, day: 19, hour: 15)))280        #expect(rates.timestamp == expected)281        #expect(try rates.convert(100, from: "USD", to: "CAD") == dec("139.54282462297258844731101204590723703"))282        #expect(rates.staleness(now: expected.addingTimeInterval(7200)) == .fresh(age: 7200))283        #expect(rates.staleness(now: expected.addingTimeInterval(4 * 86_400)) == .stale(age: 345_600))284285        // Summer time: 16:00 CEST (UTC+2) = 14:00 UTC. Double-quoted attributes are accepted too.286        let summer = #"<Cube><Cube time="2026-07-01"><Cube currency="USD" rate="1.1"/></Cube></Cube>"#287        let summerRates = try CurrencyRates.parseECB(xml: Data(summer.utf8))288        #expect(summerRates.timestamp == utc.date(from: DateComponents(year: 2026, month: 7, day: 1, hour: 14)))289        #expect(summerRates.rate(for: "USD")?.value == dec("1.1"))290    }291292    @Test("Malformed ECB documents are rejected")293    func ecbMalformed() {294        func parse(_ text: String) throws -> CurrencyRates { try CurrencyRates.parseECB(xml: Data(text.utf8)) }295        let cases = [296            "",297            "not xml at all",298            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='1.05'/></Cube>",299            "<Cube><Cube><Cube currency='USD' rate='1.05'/></Cube></Cube>",300            "<Cube><Cube time='2026-11-19'></Cube></Cube>",301            "<Cube><Cube time='2026-13-19'><Cube currency='USD' rate='1.05'/></Cube></Cube>",302            "<Cube><Cube time='2026-02-30'><Cube currency='USD' rate='1.05'/></Cube></Cube>",303            "<Cube><Cube time='19/11/2026'><Cube currency='USD' rate='1.05'/></Cube></Cube>",304            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='abc'/></Cube></Cube>",305            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='1,05'/></Cube></Cube>",306            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='-1.05'/></Cube></Cube>",307            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='0'/></Cube></Cube>",308            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='1e5'/></Cube></Cube>",309            "<Cube><Cube time='2026-11-19'><Cube currency='USD'/></Cube></Cube>",310            "<Cube><Cube time='2026-11-19'><Cube currency='usd' rate='1.05'/></Cube></Cube>",311            "<Cube><Cube time='2026-11-19'><Cube currency='USDX' rate='1.05'/></Cube></Cube>",312            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='1.05'/><Cube currency='USD' rate='1.06'/></Cube></Cube>",313            // The 90-day history document has several dates: it is not a daily table.314            "<Cube><Cube time='2026-11-19'><Cube currency='USD' rate='1.05'/></Cube><Cube time='2026-11-18'><Cube currency='USD' rate='1.04'/></Cube></Cube>",315        ]316        for text in cases {317            #expect(throws: UnitError.self, "should reject: \(text)") { try parse(text) }318        }319        #expect(CurrencyRates.strictDecimal("1.25") == dec("1.25"))320        #expect(CurrencyRates.strictDecimal(".5") == nil)321        #expect(CurrencyRates.strictDecimal("5.") == nil)322        #expect(CurrencyRates.strictDecimal("1.2.3") == nil)323        #expect(CurrencyRates.strictDecimal("") == nil)324    }325}326
Files main
Menu

Theme