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/PortfolioTests.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 PortfolioTests {94 let f = financeFixture["portfolio"]95 var series: [[Double]] { f["R"].mat }96 var r0: [Double] { series[0] }97 var ppy: Double { f["ppy"].d }98 var rf: Double { f["rf"].d }99100 @Test func returnsAndAnnualisation() {101 let prices = f["prices"].arr102 #expect(allClose(PortfolioAnalytics.returns(prices: prices), f["simple"].arr, rel: 1e-12, abs: 1e-15))103 #expect(allClose(PortfolioAnalytics.returns(prices: prices, kind: .log), f["log"].arr, rel: 1e-12, abs: 1e-15))104 #expect(PortfolioAnalytics.returns(prices: [5]).isEmpty)105 #expect(isClose(PortfolioAnalytics.cumulativeReturn(r0), f["cumulative"].d, rel: 1e-12))106 #expect(isClose(PortfolioAnalytics.cumulativeReturn(PortfolioAnalytics.returns(prices: prices, kind: .log), kind: .log), prices.last! / prices[0] - 1, rel: 1e-12))107 #expect(isClose(PortfolioAnalytics.annualizedReturn(r0, periodsPerYear: ppy), f["ann_return"].d, rel: 1e-12))108 #expect(isClose(PortfolioAnalytics.annualizedMeanReturn(r0, periodsPerYear: ppy), f["ann_mean"].d, rel: 1e-12))109 #expect(isClose(PortfolioAnalytics.annualizedVolatility(r0, periodsPerYear: ppy), f["ann_vol"].d, rel: 1e-12))110 // 1 % a month for 12 months is 12.6825 % a year111 #expect(isClose(PortfolioAnalytics.annualizedReturn([Double](repeating: 0.01, count: 12), periodsPerYear: 12), pow(1.01, 12) - 1, rel: 1e-13))112 }113114 @Test func riskAdjustedMeasures() throws {115 #expect(isClose(PortfolioAnalytics.sharpeRatio(r0, riskFreePerPeriod: rf, periodsPerYear: ppy), f["sharpe"].d, rel: 1e-11))116 #expect(isClose(PortfolioAnalytics.downsideDeviation(r0, minimumAcceptableReturn: rf), f["downside_dev"].d, rel: 1e-12))117 #expect(isClose(PortfolioAnalytics.sortinoRatio(r0, minimumAcceptableReturn: rf, periodsPerYear: ppy), f["sortino"].d, rel: 1e-11))118 #expect(PortfolioAnalytics.sharpeRatio([0.01, 0.01, 0.01], periodsPerYear: 12).isNaN)119 #expect(PortfolioAnalytics.sortinoRatio([0.01, 0.02], periodsPerYear: 12).isNaN) // no downside120 // hand-computed: returns −2 %, +4 %, MAR 0 → DD = √(0.0004/2)121 #expect(isClose(PortfolioAnalytics.downsideDeviation([-0.02, 0.04]), (0.0004 / 2).squareRoot(), rel: 1e-14))122 let dd = PortfolioAnalytics.maxDrawdown(returns: r0)!123 #expect(isClose(dd.maxDrawdown, f["max_dd"].d, rel: 1e-12))124 #expect(dd.peakIndex == f["dd_peak"].i && dd.troughIndex == f["dd_trough"].i)125 #expect(dd.recoveryIndex == (f["dd_recovery"].isNull ? nil : f["dd_recovery"].i))126 let simple = PortfolioAnalytics.maxDrawdown(values: [100, 120, 90, 95, 130, 110])!127 #expect(simple.maxDrawdown == 0.25 && simple.peakIndex == 1 && simple.troughIndex == 2 && simple.recoveryIndex == 4)128 #expect(PortfolioAnalytics.maxDrawdown(values: [1, 2, 3])!.maxDrawdown == 0)129 #expect(PortfolioAnalytics.maxDrawdown(values: []) == nil)130 }131132 @Test func benchmarkStatistics() throws {133 let b = try PortfolioAnalytics.benchmarkStatistics(r0, benchmark: series[1], riskFreePerPeriod: rf, periodsPerYear: ppy)134 #expect(isClose(b.beta, f["beta"].d, rel: 1e-12) && isClose(b.beta, f["beta_ols"].d, rel: 1e-10))135 #expect(isClose(b.alphaPerPeriod, f["alpha"].d, rel: 1e-10) && isClose(b.alphaPerPeriod, f["alpha_ols"].d, rel: 1e-9))136 #expect(isClose(b.alphaAnnualized, f["alpha"].d * ppy, rel: 1e-10))137 #expect(isClose(b.rSquared, f["r2"].d, rel: 1e-11) && isClose(b.correlation, f["corr"].d, rel: 1e-12))138 #expect(isClose(b.trackingError, f["tracking_error"].d, rel: 1e-12))139 #expect(isClose(b.informationRatio, f["info_ratio"].d, rel: 1e-11))140 // an asset regressed on itself: beta 1, alpha 0141 let own = try PortfolioAnalytics.benchmarkStatistics(r0, benchmark: r0, periodsPerYear: ppy)142 #expect(isClose(own.beta, 1, rel: 1e-13) && abs(own.alphaPerPeriod) < 1e-17 && own.trackingError == 0 && own.informationRatio.isNaN)143 #expect(b.table().count == 7)144 #expect(throws: StatError.self) { try PortfolioAnalytics.benchmarkStatistics([0.1, 0.2], benchmark: [0.1, 0.2], periodsPerYear: 12) }145 #expect(throws: StatError.self) { try PortfolioAnalytics.benchmarkStatistics([0.1, 0.2, 0.3], benchmark: [0.1, 0.1, 0.1], periodsPerYear: 12) }146 }147148 @Test func valueAtRisk() throws {149 let h = try PortfolioAnalytics.valueAtRisk(r0, confidence: 0.95, method: .historical)150 #expect(isClose(h.valueAtRisk, f["var_hist"].d, rel: 1e-12) && isClose(h.conditionalVaR, f["cvar_hist"].d, rel: 1e-12))151 let h99 = try PortfolioAnalytics.valueAtRisk(r0, confidence: 0.99, method: .historical)152 #expect(isClose(h99.valueAtRisk, f["var_hist_99"].d, rel: 1e-12) && isClose(h99.conditionalVaR, f["cvar_hist_99"].d, rel: 1e-12))153 let p = try PortfolioAnalytics.valueAtRisk(r0, confidence: 0.95, method: .parametricNormal)154 #expect(isClose(p.valueAtRisk, f["var_norm"].d, rel: 1e-11) && isClose(p.conditionalVaR, f["cvar_norm"].d, rel: 1e-11))155 #expect(h.conditionalVaR >= h.valueAtRisk && p.conditionalVaR > p.valueAtRisk && h99.valueAtRisk > h.valueAtRisk)156 // 101 evenly spaced returns −0.50 … +0.50: the 5 % quantile is exactly −0.45157 let grid = (0...100).map { Double($0) / 100 - 0.5 }158 let g = try PortfolioAnalytics.valueAtRisk(grid, confidence: 0.95)159 #expect(isClose(g.valueAtRisk, 0.45, rel: 1e-13) && isClose(g.conditionalVaR, 0.475, rel: 1e-13))160 #expect(throws: StatError.self) { try PortfolioAnalytics.valueAtRisk([0.1], confidence: 0.95) }161 #expect(throws: StatError.self) { try PortfolioAnalytics.valueAtRisk(r0, confidence: 1.2) }162 let s = try PortfolioAnalytics.summary(r0, riskFreePerPeriod: rf, periodsPerYear: ppy)163 #expect(s.observations == r0.count && isClose(s.sharpeRatio, f["sharpe"].d, rel: 1e-11) && isClose(s.maxDrawdown, f["max_dd"].d, rel: 1e-12))164 #expect(s.historicalVaR95 == h.valueAtRisk && s.bestPeriod == r0.max() && s.table().count == 13)165 }166167 @Test func covarianceAndPortfolioMoments() throws {168 let cov = try PortfolioAnalytics.covarianceMatrix(series)169 #expect(allClose(cov.data, f["cov"].mat.flatMap { $0 }, rel: 1e-11, abs: 1e-18))170 let corr = try PortfolioAnalytics.correlationMatrix(series)171 #expect(allClose(corr.data, f["corrmat"].mat.flatMap { $0 }, rel: 1e-11, abs: 1e-15))172 let w = f["w"].arr, mu = series.map { Descriptive.mean($0) }173 #expect(allClose(mu, f["mu"].arr, rel: 1e-12))174 #expect(isClose(PortfolioAnalytics.portfolioVariance(weights: w, covariance: cov), f["port_var"].d, rel: 1e-11))175 #expect(isClose(PortfolioAnalytics.portfolioReturn(weights: w, expectedReturns: mu), f["port_ret"].d, rel: 1e-12))176 let pr = PortfolioAnalytics.portfolioReturns(weights: w, series: series)177 #expect(allClose(Array(pr.prefix(5)), f["port_returns_head"].arr, rel: 1e-12, abs: 1e-17))178 // the variance of the realised portfolio returns equals wᵀΣw179 #expect(isClose(Descriptive.variance(pr), f["port_var"].d, rel: 1e-10))180 #expect(throws: StatError.self) { try PortfolioAnalytics.covarianceMatrix([[1, 2, 3], [1, 2]]) }181 }182183 @Test func unconstrainedFrontierClosedForms() throws {184 let cov = Matrix(f["cov"].mat), mu = f["mu"].arr185 let gmv = try MeanVariance.minimumVariancePortfolio(expectedReturns: mu, covariance: cov)186 #expect(allClose(gmv.weights, f["gmv_w"].arr, rel: 1e-9, abs: 1e-12))187 #expect(isClose(gmv.variance, f["gmv_var"].d, rel: 1e-10))188 #expect(isClose(gmv.weights.reduce(0, +), 1, rel: 1e-12))189 for e in f["eff"].list {190 let p = try MeanVariance.efficientPortfolio(expectedReturns: mu, covariance: cov, targetReturn: e["target"].d)191 #expect(allClose(p.weights, e["w"].arr, rel: 1e-8, abs: 1e-10), "target \(e["target"].d)")192 #expect(isClose(p.variance, e["var"].d, rel: 1e-9))193 #expect(isClose(p.expectedReturn, e["target"].d, rel: 1e-10))194 #expect(p.variance > gmv.variance)195 }196 let tan = try MeanVariance.tangencyPortfolio(expectedReturns: mu, covariance: cov, riskFree: f["tangency_rf"].d)197 #expect(allClose(tan.weights, f["tangency_w"].arr, rel: 1e-9, abs: 1e-11))198 #expect(isClose((tan.expectedReturn - f["tangency_rf"].d) / tan.volatility, f["tangency_sharpe"].d, rel: 1e-10))199 // the tangency portfolio has the highest Sharpe ratio on the frontier200 let fr = try MeanVariance.frontier(expectedReturns: mu, covariance: cov, count: 15, maxReturn: tan.expectedReturn * 2)201 #expect(fr.points.count == 15 && !fr.longOnly && fr.table().count == 16)202 #expect(fr.points.allSatisfy { ($0.expectedReturn - f["tangency_rf"].d) / $0.volatility <= f["tangency_sharpe"].d + 1e-12 })203 #expect(zip(fr.points, fr.points.dropFirst()).allSatisfy { $0.volatility < $1.volatility })204 // two uncorrelated assets: analytic minimum-variance weights σ₂²/(σ₁²+σ₂²)205 let two = try MeanVariance.minimumVariancePortfolio(expectedReturns: [0.05, 0.1], covariance: Matrix([[0.04, 0], [0, 0.09]]))206 #expect(allClose(two.weights, [9.0 / 13, 4.0 / 13], rel: 1e-13) && isClose(two.variance, 0.36 / 13, rel: 1e-13))207 #expect(throws: StatError.self) { try MeanVariance.efficientPortfolio(expectedReturns: [0.05, 0.05], covariance: Matrix([[0.04, 0], [0, 0.09]]), targetReturn: 0.05) }208 #expect(throws: StatError.self) { try MeanVariance.minimumVariancePortfolio(expectedReturns: [0.05], covariance: Matrix([[0.04]])) }209 #expect(throws: StatError.self) { try MeanVariance.tangencyPortfolio(expectedReturns: mu, covariance: cov, riskFree: 1) }210 }211212 @Test func longOnlyFrontierMatchesSLSQP() throws {213 let lo = f["lo"]214 let mu = lo["mu"].arr, cov = Matrix(lo["cov"].mat)215 let gmv = try MeanVariance.longOnlyMinimumVariance(expectedReturns: mu, covariance: cov)216 #expect(allClose(gmv.weights, lo["gmv_w"].arr, rel: 1e-5, abs: 2e-6), "GMV \(gmv.weights)")217 #expect(gmv.variance <= lo["gmv_var"].d * (1 + 1e-9))218 #expect(isClose(gmv.variance, lo["gmv_var"].d, rel: 1e-8))219 #expect(gmv.weights.contains(0)) // bounds really bind220 for p in lo["points"].list {221 let s = try MeanVariance.longOnlyEfficientPortfolio(expectedReturns: mu, covariance: cov, targetReturn: p["target"].d)222 #expect(s.weights.allSatisfy { $0 >= 0 }, "non-negative")223 #expect(isClose(s.weights.reduce(0, +), 1, rel: 1e-12))224 #expect(isClose(s.expectedReturn, p["target"].d, rel: 1e-11))225 #expect(allClose(s.weights, p["w"].arr, rel: 1e-5, abs: 2e-6), "target \(p["target"].d): \(s.weights) vs \(p["w"].arr)")226 #expect(isClose(s.variance, p["var"].d, rel: 1e-8), "variance at \(p["target"].d)")227 #expect(s.variance <= p["var"].d * (1 + 1e-9)) // never worse than SLSQP228 // KKT optimality check independent of SciPy: for held assets the gradient 2Σw is an affine function of (1, μ)229 let grad = (cov * s.weights).map { 2 * $0 }230 let held = s.weights.indices.filter { s.weights[$0] > 1e-9 }231 if held.count >= 3 {232 let i = held[0], j = held[1]233 let l2 = (grad[i] - grad[j]) / (mu[i] - mu[j]), l1 = grad[i] - l2 * mu[i]234 for k in held { #expect(isClose(grad[k], l1 + l2 * mu[k], rel: 1e-8, abs: 1e-12)) }235 for k in s.weights.indices where s.weights[k] == 0 { #expect(grad[k] >= l1 + l2 * mu[k] - 1e-10) }236 }237 }238 let fr = try MeanVariance.longOnlyFrontier(expectedReturns: mu, covariance: cov, count: 12, assetNames: ["A", "B", "C", "D", "E", "F"])239 #expect(fr.longOnly && fr.points.count == 12 && fr.table()[0].count == 8)240 #expect(fr.points.last!.weights == [0, 0, 0, 1, 0, 0]) // top of the frontier = highest-return asset241 #expect(zip(fr.points, fr.points.dropFirst()).allSatisfy { $0.variance <= $1.variance + 1e-15 })242 #expect(fr.points.allSatisfy { $0.weights.allSatisfy { $0 >= 0 } })243 // when no bound binds, the long-only solution equals the closed form244 let c4 = Matrix(f["cov"].mat), m4 = f["mu"].arr245 let free = try MeanVariance.minimumVariancePortfolio(expectedReturns: m4, covariance: c4)246 if free.weights.allSatisfy({ $0 > 0 }) {247 #expect(allClose(try MeanVariance.longOnlyMinimumVariance(expectedReturns: m4, covariance: c4).weights, free.weights, rel: 1e-9))248 }249 #expect(throws: StatError.self) { try MeanVariance.longOnlyEfficientPortfolio(expectedReturns: mu, covariance: cov, targetReturn: 0.5) }250 #expect(try MeanVariance.longOnlyEfficientPortfolio(expectedReturns: mu, covariance: cov, targetReturn: mu.min()!).weights == [0, 0, 0, 0, 0, 1])251 }252}253254@Suite struct RatioAndForecastTests {255 let cur = StatementItems(revenue: 1_200, costOfGoodsSold: 720, operatingIncome: 180, interestExpense: 30, pretaxIncome: 150, netIncome: 105,256 depreciationAmortization: 60, cash: 90, marketableSecurities: 10, receivables: 150, inventory: 180, currentAssets: 450,257 totalAssets: 1_000, payables: 120, currentLiabilities: 250, totalDebt: 300, totalLiabilities: 600, equity: 400)258259 @Test func ratiosFromPeriodEndBalances() {260 let r = FinancialRatios.compute(cur)261 #expect(r["Current ratio"] == 1.8)262 #expect(r["Quick ratio"] == 1.0)263 #expect(r["Cash ratio"] == 0.4)264 #expect(r["Working capital"] == 200)265 #expect(r["Debt to equity"] == 0.75 && r["Debt to assets"] == 0.3 && r["Liabilities to assets"] == 0.6)266 #expect(r["Equity multiplier"] == 2.5 && r["Interest coverage"] == 6)267 #expect(isClose(r["Net debt to EBITDA"]!, 200.0 / 240, rel: 1e-15))268 #expect(r["Gross margin"] == 0.4 && r["Operating margin"] == 0.15 && r["EBITDA margin"] == 0.2)269 #expect(isClose(r["Net margin"]!, 0.0875, rel: 1e-15) && isClose(r["Return on assets"]!, 0.105, rel: 1e-15) && isClose(r["Return on equity"]!, 0.2625, rel: 1e-15))270 #expect(r["Asset turnover"] == 1.2 && r["Inventory turnover"] == 4 && r["Receivables turnover"] == 8 && r["Payables turnover"] == 6)271 #expect(isClose(r["Days inventory outstanding"]!, 91.25, rel: 1e-14) && isClose(r["Days sales outstanding"]!, 45.625, rel: 1e-14))272 #expect(isClose(r["Days payables outstanding"]!, 365.0 / 6, rel: 1e-14))273 #expect(isClose(r["Cash conversion cycle"]!, 91.25 + 45.625 - 365.0 / 6, rel: 1e-14))274 // DuPont identities: both decompositions reproduce ROE275 #expect(isClose(r["DuPont ROE (3-step)"]!, r["Return on equity"]!, rel: 1e-14))276 #expect(isClose(r["DuPont ROE (5-step)"]!, r["Return on equity"]!, rel: 1e-14))277 #expect(isClose(r["Tax burden"]!, 0.7, rel: 1e-15) && isClose(r["Interest burden"]!, 150.0 / 180, rel: 1e-15))278 #expect(!r.usesAverageBalances && r.table().count == r.ratios.count + 1 && r.ratios.allSatisfy { !$0.formula.isEmpty })279 #expect(Set(r.ratios.map(\.category)) == ["Liquidity", "Leverage", "Profitability", "Efficiency", "DuPont"])280 }281282 @Test func ratiosWithAveragesAndZeroDenominators() {283 var prior = cur284 prior.totalAssets = 800; prior.equity = 300; prior.inventory = 140; prior.receivables = 130; prior.payables = 100285 let r = FinancialRatios.compute(cur, prior: prior, daysInPeriod: 360)286 #expect(r.usesAverageBalances)287 #expect(isClose(r["Return on assets"]!, 105.0 / 900, rel: 1e-15) && isClose(r["Return on equity"]!, 0.3, rel: 1e-15))288 #expect(isClose(r["Asset turnover"]!, 1200.0 / 900, rel: 1e-15) && r["Inventory turnover"] == 4.5)289 #expect(isClose(r["Days inventory outstanding"]!, 80, rel: 1e-14))290 #expect(isClose(r["DuPont ROE (3-step)"]!, 0.3, rel: 1e-14) && isClose(r["DuPont ROE (5-step)"]!, 0.3, rel: 1e-14))291 #expect(r.ratios.first { $0.name == "Return on equity" }!.formula == "net income / average equity")292 var z = cur293 z.currentLiabilities = 0; z.interestExpense = 0; z.inventory = 0; z.revenue = 0294 let rz = FinancialRatios.compute(z)295 #expect(rz["Current ratio"] == nil && rz["Interest coverage"] == nil && rz["Inventory turnover"] == nil && rz["Net margin"] == nil)296 #expect(rz["DuPont ROE (3-step)"] == nil && rz["Days sales outstanding"] == nil && rz["Cash conversion cycle"] == nil)297 #expect(rz.table().contains { $0[1] == .text("Current ratio") && $0[2] == .blank })298 }299300 @Test func forecasting() throws {301 let f = financeFixture["forecast"]302 let y = f["y"].arr303 let t = try Forecasting.linearTrend(y)304 #expect(isClose(t.slope, f["slope"].d, rel: 1e-11) && isClose(t.intercept, f["intercept"].d, rel: 1e-11))305 #expect(isClose(t.rSquared, f["r2"].d, rel: 1e-10) && isClose(t.standardError, f["se"].d, rel: 1e-11))306 #expect(allClose(t.fitted, f["fitted"].arr, rel: 1e-11))307 #expect(allClose(t.forecasts(horizon: 6), f["forecast"].arr, rel: 1e-11))308 for h in 1...6 {309 let pi = t.predictionInterval(steps: h)310 #expect(isClose(pi.lower, f["pi_low"][h - 1].d, rel: 1e-9) && isClose(pi.upper, f["pi_high"][h - 1].d, rel: 1e-9), "PI h=\(h)")311 #expect(isClose(t.predictionInterval(steps: h, confidence: 0.8).lower, f["pi_low_80"][h - 1].d, rel: 1e-9))312 }313 #expect(t.table().count == 5 && t.forecasts(horizon: 0).isEmpty)314 // an exact line is recovered exactly315 let line = try Forecasting.linearTrend([3, 5, 7, 9])316 #expect(isClose(line.slope, 2, rel: 1e-14) && isClose(line.intercept, 1, rel: 1e-13) && isClose(line.rSquared, 1, rel: 1e-14) && isClose(line.forecast(steps: 2), 13, rel: 1e-14))317 #expect(throws: StatError.self) { try Forecasting.linearTrend([1]) }318 #expect(try Forecasting.seasonalNaive(y, seasonLength: 12, horizon: 18) == f["seasonal_naive_12_h18"].arr)319 #expect(try Forecasting.seasonalNaive([1, 2, 3, 4], seasonLength: 1, horizon: 3) == [4, 4, 4])320 #expect(try Forecasting.seasonalNaive([1, 2, 3, 4], seasonLength: 2, horizon: 0).isEmpty)321 #expect(throws: StatError.self) { try Forecasting.seasonalNaive([1, 2], seasonLength: 4, horizon: 2) }322 #expect(allClose(try Forecasting.drift(y, horizon: 4), f["drift_h4"].arr, rel: 1e-13))323 #expect(isClose(Forecasting.cagr(y)!, f["cagr"].d, rel: 1e-13))324 #expect(isClose(Forecasting.cagr(begin: 100, end: 200, periods: 5)!, pow(2, 0.2) - 1, rel: 1e-14))325 #expect(Forecasting.cagr(begin: -1, end: 2, periods: 3) == nil && Forecasting.cagr([5]) == nil)326 #expect(isClose(Forecasting.compoundGrowth(from: 100, rate: Forecasting.cagr(begin: 100, end: 250, periods: 7)!, periods: 7), 250, rel: 1e-13))327 }328329 @Test func resultsAreCodable() throws {330 func roundTrip<T: Codable & Equatable>(_ v: T) throws -> Bool { try JSONDecoder().decode(T.self, from: JSONEncoder().encode(v)) == v }331 #expect(try roundTrip(try Amortization.schedule(LoanTerms(principal: 5000, annualRate: 0.07, periods: 6, extraPayments: [2: 100]))))332 #expect(try roundTrip(try TVM.solve(TVMInputs(periods: 12, annualRate: 0.05, presentValue: 1000, futureValue: 0), for: .payment)))333 #expect(try roundTrip(try CanadianMortgage(principal: 250_000, annualRate: 0.05, amortizationMonths: 240, termMonths: 60, frequency: .acceleratedWeekly).solve()))334 #expect(try roundTrip(try Bond(maturity: CalendarDate(2030, 1, 15), couponRate: 0.04).analytics(settlement: CalendarDate(2025, 3, 3), yield: 0.05)))335 #expect(try roundTrip(try CashFlowAnalysis.irr(cashFlows: [-100, 60, 70])))336 #expect(try roundTrip(FinancialRatios.compute(cur)))337 #expect(try roundTrip(BreakEven.analyze(fixedCosts: 10, pricePerUnit: 3, variableCostPerUnit: 1)))338 #expect(try roundTrip(try PortfolioAnalytics.summary([0.01, -0.02, 0.03, 0.005], periodsPerYear: 12)))339 #expect(try roundTrip(try MeanVariance.frontier(expectedReturns: [0.05, 0.1], covariance: Matrix([[0.04, 0.01], [0.01, 0.09]]), count: 3)))340 #expect(try roundTrip(CapitalBudgeting.compare([Project(name: "P", cashFlows: [-10, 6, 7])], rate: 0.1)))341 }342}343