SPB Git

Repository Public

GARCH.swift 8.5 KB 178 lines swift

1import Foundation2import SheetCore34/// GARCH(1,1) volatility model estimated by Gaussian maximum likelihood.5///6///     r_t = μ + ε_t,   ε_t = σ_t z_t,   z_t ~ N(0, 1)7///     σ²_t = ω + α ε²_{t−1} + β σ²_{t−1}8///9/// The recursion is started as the `arch` package does ("backcasting"): ε²_0 and σ²_0 are both set10/// to an exponentially weighted average of the first min(75, n) squared residuals around the sample mean11/// (weights ∝ 0.94^i). Log-likelihood: −½ Σ [ln 2π + ln σ²_t + ε²_t/σ²_t].12/// Returns are best supplied in percent (×100): very small numbers make ω hard to optimise.13public enum GARCH {14    public enum MeanModel: String, Sendable, Codable, CaseIterable {15        /// μ fixed at 0.16        case zero17        /// μ estimated.18        case constant19    }2021    public struct Parameters: Sendable, Hashable, Codable {22        public var mu: Double23        public var omega: Double24        public var alpha: Double25        public var beta: Double26        public init(mu: Double = 0, omega: Double, alpha: Double, beta: Double) {27            self.mu = mu; self.omega = omega; self.alpha = alpha; self.beta = beta28        }29    }3031    /// The backcast value used for ε²_0 and σ²_0.32    public static func backcast(_ returns: [Double], mean: MeanModel) -> Double {33        let m = mean == .constant ? Descriptive.mean(returns) : 034        let tau = min(75, returns.count)35        var w = 1.0, sw = 0.0, s = 0.036        for i in 0..<tau {37            let e = returns[i] - m38            s += w * e * e39            sw += w40            w *= 0.9441        }42        return sw > 0 ? s / sw : .nan43    }4445    private static func run(_ r: [Double], _ p: Parameters, _ back: Double, keep: Bool) -> (ll: Double, sigma2: [Double]) {46        var ll = 0.047        var s2 = [Double]()48        if keep { s2.reserveCapacity(r.count) }49        var prevE2 = back, prevS2 = back50        let log2pi = log(2 * Double.pi)51        for x in r {52            let v = p.omega + p.alpha * prevE2 + p.beta * prevS253            guard v > 0, v.isFinite else { return (-.infinity, []) }54            let e = x - p.mu55            ll -= 0.5 * (log2pi + log(v) + e * e / v)56            if keep { s2.append(v) }57            prevE2 = e * e; prevS2 = v58        }59        return (ll, s2)60    }6162    /// Gaussian log-likelihood at the given parameters.63    public static func logLikelihood(_ returns: [Double], parameters: Parameters, mean: MeanModel = .constant) -> Double {64        run(returns, parameters, backcast(returns, mean: mean), keep: false).ll65    }6667    /// Fits the model (or, with `fixed`, evaluates it at given parameters).68    /// Constraints: ω > 0, α ≥ 0, β ≥ 0, α + β < 1. Optimiser: bounded Nelder–Mead from several69    /// (α, β) starting points with variance targeting for the initial ω.70    public static func fit(_ returns: [Double], mean: MeanModel = .constant, fixed: Parameters? = nil) throws -> GARCHFit {71        let n = returns.count72        guard returns.allSatisfy(\.isFinite) else { throw StatError.invalidInput("returns contain non-finite values") }73        guard n >= 20 else { throw StatError.insufficientData("GARCH(1,1) needs at least 20 observations") }74        let back = backcast(returns, mean: mean)75        let variance = Descriptive.variance(returns, sample: false)76        guard variance > 0 else { throw StatError.invalidInput("returns are constant") }77        var params: Parameters78        var converged = true79        if let fixed {80            guard fixed.omega > 0, fixed.alpha >= 0, fixed.beta >= 0 else { throw StatError.invalidInput("GARCH needs ω > 0, α ≥ 0, β ≥ 0") }81            params = fixed82            if mean == .zero { params.mu = 0 }83        } else {84            let mbar = Descriptive.mean(returns)85            let sd = variance.squareRoot()86            // variables: [ω/variance, α, β, (μ − mean)/sd]87            func unpack(_ v: [Double]) -> Parameters {88                Parameters(mu: mean == .constant ? mbar + v[3] * sd : 0, omega: v[0] * variance, alpha: v[1], beta: v[2])89            }90            let objective: ([Double]) -> Double = { v in91                if v[1] + v[2] >= 0.99999 { return 1e300 }92                let ll = run(returns, unpack(v), back, keep: false).ll93                return ll.isFinite ? -ll : 1e30094            }95            var bounds: [ClosedRange<Double>] = [1e-8...10, 0...1, 0...1]96            if mean == .constant { bounds.append(-5...5) }97            var opt = Minimizer.NelderMeadOptions()98            opt.xtol = 1e-10; opt.ftol = 1e-11; opt.maxIterations = 6000; opt.maxEvaluations = 12000; opt.restarts = 899            var best: MinimizeResult?100            for (a, b) in [(0.05, 0.90), (0.10, 0.80), (0.20, 0.60), (0.05, 0.50), (0.02, 0.96), (0.30, 0.30)] {101                var start = [1 - a - b, a, b]102                if mean == .constant { start.append(0.01) }103                let r = try Minimizer.nelderMead(objective, start: start, bounds: bounds, options: opt)104                if best == nil || r.value < best!.value { best = r }105            }106            guard let best, best.value < 1e299 else { throw StatError.notConverged("GARCH likelihood could not be maximised") }107            params = unpack(best.x)108            converged = best.converged109        }110        let (ll, s2) = run(returns, params, back, keep: true)111        guard ll.isFinite else { throw StatError.invalidInput("conditional variance became non-positive") }112        let k = Double(mean == .constant ? 4 : 3)113        let resid = returns.map { $0 - params.mu }114        return GARCHFit(meanModel: mean, parameters: params, logLikelihood: ll, aic: -2 * ll + 2 * k, bic: -2 * ll + k * log(Double(n)),115                        n: n, backcast: back, conditionalVariance: s2, residuals: resid,116                        standardizedResiduals: zip(resid, s2).map { $0 / $1.squareRoot() },117                        estimated: fixed == nil, converged: converged)118    }119}120121/// A fitted GARCH(1,1) model.122public struct GARCHFit: Sendable, Hashable, Codable, TableReport {123    public var meanModel: GARCH.MeanModel124    public var parameters: GARCH.Parameters125    public var logLikelihood: Double126    /// −2·lnL + 2k (k = 3, or 4 with an estimated mean).127    public var aic: Double128    public var bic: Double129    public var n: Int130    public var backcast: Double131    /// σ²_1…σ²_n.132    public var conditionalVariance: [Double]133    /// ε_t = r_t − μ.134    public var residuals: [Double]135    /// ε_t/σ_t.136    public var standardizedResiduals: [Double]137    public var estimated: Bool138    public var converged: Bool139140    /// α + β: the rate at which variance shocks persist.141    public var persistence: Double { parameters.alpha + parameters.beta }142    /// Long-run variance ω/(1 − α − β); nil when α + β ≥ 1 (integrated or explosive).143    public var unconditionalVariance: Double? {144        persistence < 1 ? parameters.omega / (1 - persistence) : nil145    }146    /// Periods for a variance shock to decay by half: ln(½)/ln(α + β); nil when undefined.147    public var halfLife: Double? { persistence > 0 && persistence < 1 ? log(0.5) / log(persistence) : nil }148    /// Conditional volatility σ_t.149    public var conditionalVolatility: [Double] { conditionalVariance.map { $0.squareRoot() } }150151    /// Variance forecasts σ²_{n+1}…σ²_{n+h}: σ²_{n+1} = ω + α ε²_n + β σ²_n, then152    /// σ²_{n+k} = ω + (α + β) σ²_{n+k−1}.153    public func forecastVariance(_ h: Int) -> [Double] {154        guard h > 0, let s2 = conditionalVariance.last, let e = residuals.last else { return [] }155        var out = [parameters.omega + parameters.alpha * e * e + parameters.beta * s2]156        while out.count < h { out.append(parameters.omega + persistence * out[out.count - 1]) }157        return out158    }159160    public func table() -> [[Value]] {161        var out: [[Value]] = [162            Report.row("Model", "GARCH(1,1), Gaussian maximum likelihood, \(meanModel.rawValue) mean"),163            Report.row("Observations", n),164        ]165        if meanModel == .constant { out.append(Report.row("mu", parameters.mu)) }166        out.append(Report.row("omega", parameters.omega))167        out.append(Report.row("alpha", parameters.alpha))168        out.append(Report.row("beta", parameters.beta))169        out.append(Report.row("Persistence (alpha + beta)", persistence))170        out.append([.text("Unconditional variance"), Report.num(unconditionalVariance)])171        out.append([.text("Half-life (periods)"), Report.num(halfLife)])172        out.append(Report.row("Log-likelihood", logLikelihood))173        out.append(Report.row("AIC", aic))174        out.append(Report.row("BIC", bic))175        return out176    }177}178
Files main
Menu

Theme