SPB Git

Repository Public

ARIMAKalman.swift 9.9 KB 241 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAnalytics/Sources/Statistics/TimeSeries/ARIMAKalman.swift10// Module           : Statistics11// 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 Foundation8889extension ARIMA {90    /// Exact Gaussian likelihood of a stationary ARMA(p, q) process by the Kalman filter91    /// (Harvey's state-space form, stationary initial covariance from the discrete Lyapunov equation).92    struct ARMAKalman {93        let ar: [Double]94        let ma: [Double]95        let r: Int96        /// Transition matrix T (r×r, row-major) and R Rᵀ.97        private let t: [Double]98        private let rrt: [Double]99100        struct Output {101            /// Innovations v_t and their variances divided by σ² (f_t).102            var innovations: [Double]103            var scaledVariances: [Double]104            /// Predicted state a_{n+1|n} and its covariance / σ².105            var state: [Double]106            var covariance: [Double]107            /// Σ v²/f and Σ ln f.108            var sumSquares: Double109            var sumLogF: Double110        }111112        init(ar: [Double], ma: [Double]) {113            self.ar = ar; self.ma = ma114            let r = max(ar.count, ma.count + 1)115            self.r = r116            var t = [Double](repeating: 0, count: r * r)117            for i in 0..<r {118                if i < ar.count { t[i * r] = ar[i] }119                if i + 1 < r { t[i * r + i + 1] = 1 }120            }121            self.t = t122            var rv = [Double](repeating: 0, count: r)123            rv[0] = 1124            for (i, th) in ma.enumerated() { rv[i + 1] = th }125            var rrt = [Double](repeating: 0, count: r * r)126            for i in 0..<r { for j in 0..<r { rrt[i * r + j] = rv[i] * rv[j] } }127            self.rrt = rrt128        }129130        /// T x.131        func transition(_ x: [Double]) -> [Double] {132            var out = [Double](repeating: 0, count: r)133            for i in 0..<r { out[i] = (i < ar.count ? ar[i] * x[0] : 0) + (i + 1 < r ? x[i + 1] : 0) }134            return out135        }136137        /// T P Tᵀ + R Rᵀ.138        func propagate(_ p: [Double]) -> [Double] {139            // M = T P: row i of M = φ_i · row 0 of P + row i+1 of P140            var m = [Double](repeating: 0, count: r * r)141            for i in 0..<r {142                let phi = i < ar.count ? ar[i] : 0143                for j in 0..<r { m[i * r + j] = phi * p[j] + (i + 1 < r ? p[(i + 1) * r + j] : 0) }144            }145            // N = M Tᵀ: column j of N = φ_j · column 0 of M + column j+1 of M146            var out = rrt147            for j in 0..<r {148                let phi = j < ar.count ? ar[j] : 0149                for i in 0..<r { out[i * r + j] += phi * m[i * r] + (j + 1 < r ? m[i * r + j + 1] : 0) }150            }151            return out152        }153154        /// Stationary state covariance (σ² = 1): solves P = T P Tᵀ + R Rᵀ. Nil when the AR part is not stationary.155        func stationaryCovariance() -> [Double]? {156            let n = r * r157            if r == 1 {158                let phi = ar.first ?? 0159                let d = 1 - phi * phi160                return d > 0 ? [1 / d] : nil161            }162            // (I − T⊗T) vec(P) = vec(R Rᵀ)163            var a = Matrix.identity(n)164            for i in 0..<r { for j in 0..<r { for k in 0..<r { for l in 0..<r {165                let v = t[i * r + k] * t[j * r + l]166                if v != 0 { a[i * r + j, k * r + l] -= v }167            } } } }168            guard let sol = try? LinearAlgebra.solve(a, rrt), sol.allSatisfy(\.isFinite) else { return nil }169            for i in 0..<r where !(sol[i * r + i] > 0) { return nil }170            return sol171        }172173        /// Runs the filter over the (mean-adjusted) series.174        func filter(_ w: [Double]) -> Output? {175            guard var p = stationaryCovariance() else { return nil }176            var a = [Double](repeating: 0, count: r)177            var innov = [Double](), fs = [Double]()178            innov.reserveCapacity(w.count); fs.reserveCapacity(w.count)179            var ss = 0.0, slf = 0.0180            var k = [Double](repeating: 0, count: r)181            for y in w {182                let f = p[0]183                guard f > 0, f.isFinite else { return nil }184                let v = y - a[0]185                innov.append(v); fs.append(f)186                ss += v * v / f187                slf += log(f)188                for i in 0..<r { k[i] = p[i * r] / f }189                for i in 0..<r { a[i] += k[i] * v }190                for i in 0..<r { for j in 0..<r { p[i * r + j] -= k[i] * k[j] * f } }191                a = transition(a)192                p = propagate(p)193            }194            return Output(innovations: innov, scaledVariances: fs, state: a, covariance: p, sumSquares: ss, sumLogF: slf)195        }196197        /// Maps unconstrained reals to the coefficients of a stationary AR polynomial through partial198        /// autocorrelations r_k = tanh(u_k) and the Levinson recursion (Monahan 1984).199        static func stationaryCoefficients(_ u: [Double]) -> [Double] {200            var phi = [Double]()201            for (k, x) in u.enumerated() {202                let rk = tanh(x)203                var next = [Double](repeating: 0, count: k + 1)204                for j in 0..<k { next[j] = phi[j] - rk * phi[k - 1 - j] }205                next[k] = rk206                phi = next207            }208            return phi209        }210211        /// Inverse of `stationaryCoefficients` (nil when the coefficients are not strictly stationary).212        static func unconstrained(_ coefficients: [Double]) -> [Double]? {213            var phi = coefficients214            var u = [Double](repeating: 0, count: phi.count)215            for k in stride(from: phi.count - 1, through: 0, by: -1) {216                let rk = phi[k]217                guard abs(rk) < 1 else { return nil }218                u[k] = atanh(rk)219                if k > 0 {220                    var prev = [Double](repeating: 0, count: k)221                    for j in 0..<k { prev[j] = (phi[j] + rk * phi[k - 1 - j]) / (1 - rk * rk) }222                    phi = prev223                }224            }225            return u226        }227228        /// ψ-weights (MA(∞) coefficients, ψ_0 = 1) of φ(B) x = θ(B) ε for an arbitrary AR polynomial.229        static func psiWeights(ar: [Double], ma: [Double], count: Int) -> [Double] {230            var psi = [Double](repeating: 0, count: max(count, 1))231            psi[0] = 1232            for j in 1..<max(count, 1) {233                var v = j <= ma.count ? ma[j - 1] : 0234                for i in 1...max(1, min(j, ar.count)) where i <= ar.count { v += ar[i - 1] * psi[j - i] }235                psi[j] = v236            }237            return Array(psi.prefix(count))238        }239    }240}241
Files main
Menu

Theme