SPB Git

Repository Public

ExponentialSmoothing.swift 17.9 KB 381 lines swift

1import Foundation2import SheetCore34/// Exponential smoothing in the Holt–Winters family (simple, Holt, damped Holt, additive and5/// multiplicative seasonality).6///7/// Recursions (Hyndman & Athanasopoulos, *Forecasting: Principles and Practice*; identical to8/// `statsmodels.tsa.holtwinters.ExponentialSmoothing`), with m = season length, φ = damping (1 when undamped):9///10///     additive seasonality        l_t = α(y_t − s_{t−m}) + (1−α)(l_{t−1} + φ b_{t−1})11///     multiplicative seasonality  l_t = α(y_t / s_{t−m}) + (1−α)(l_{t−1} + φ b_{t−1})12///     trend                       b_t = β(l_t − l_{t−1}) + (1−β) φ b_{t−1}13///     additive seasonality        s_t = γ(y_t − l_{t−1} − φ b_{t−1}) + (1−γ) s_{t−m}14///     multiplicative seasonality  s_t = γ y_t / (l_{t−1} + φ b_{t−1}) + (1−γ) s_{t−m}15///16/// One-step fitted value ŷ_t = (l_{t−1} + φ b_{t−1}) ⊕ s_{t−m}; h-step forecast17/// ŷ_{n+h} = (l_n + (φ + … + φ^h) b_n) ⊕ s_{n−m+1+((h−1) mod m)}.18public enum ExponentialSmoothing {19    public enum Trend: String, Sendable, Codable, CaseIterable {20        case none21        /// Holt's linear trend.22        case additive23        /// Additive trend damped by φ (Gardner & McKenzie).24        case dampedAdditive25    }2627    public enum Seasonal: String, Sendable, Codable, CaseIterable { case none, additive, multiplicative }2829    /// Smoothing parameters. `beta` is the trend parameter of the recursion above (often written β*),30    /// `gamma` the seasonal one; `phi` is used only by a damped trend.31    public struct Parameters: Sendable, Hashable, Codable {32        public var alpha: Double33        public var beta: Double?34        public var gamma: Double?35        public var phi: Double?36        public init(alpha: Double, beta: Double? = nil, gamma: Double? = nil, phi: Double? = nil) {37            self.alpha = alpha; self.beta = beta; self.gamma = gamma; self.phi = phi38        }39    }4041    /// Initial states l_0, b_0, s_{1−m}…s_0.42    public enum Initialization: Sendable, Hashable, Codable {43        /// The simple rules of statsmodels' "legacy-heuristic":44        /// no season: l_0 = y_1, b_0 = y_2 − y_1;45        /// with a season: l_0 = mean of y at positions 1, m+1, 2m+1, …; b_0 = mean((y_{m+i} − y_i)/m, i = 1…m);46        /// s_i = y_i − l_0 (additive) or y_i / l_0 (multiplicative) for the first m observations.47        case heuristic48        /// Explicit states (`trend` ignored without a trend; `seasonal` must have m entries, oldest first).49        case known(level: Double, trend: Double, seasonal: [Double])50    }5152    /// Fits an exponential smoothing model.53    /// - Parameters:54    ///   - parameters: fixed smoothing parameters; nil = minimise the sum of squared one-step errors over55    ///     α, β, γ ∈ [0, 1] (and φ ∈ [0.8, 0.995] for a damped trend, the range statsmodels uses) with bounded Nelder–Mead from several starts.56    ///   - period: season length m (required ≥ 2 with a seasonal component; the series must cover two full seasons).57    public static func fit(_ y: [Double], trend: Trend = .none, seasonal: Seasonal = .none, period: Int = 1,58                           parameters: Parameters? = nil, initialization: Initialization = .heuristic) throws -> ExponentialSmoothingFit {59        let n = y.count60        guard y.allSatisfy(\.isFinite) else { throw StatError.invalidInput("series contains non-finite values") }61        let hasTrend = trend != .none, hasSeason = seasonal != .none62        let m = hasSeason ? period : 163        if hasSeason {64            guard period >= 2 else { throw StatError.invalidInput("a seasonal model needs period ≥ 2") }65            guard n >= 2 * period else { throw StatError.insufficientData("a seasonal model needs at least two full seasons") }66            if seasonal == .multiplicative, y.contains(where: { $0 <= 0 }) {67                throw StatError.invalidInput("multiplicative seasonality needs strictly positive data")68            }69        }70        guard n >= (hasTrend ? 3 : 2) else { throw StatError.insufficientData("too few observations") }7172        // initial states73        var l0: Double, b0 = 0.0, s0 = [Double]()74        switch initialization {75        case .known(let level, let tr, let seas):76            l0 = level; b0 = hasTrend ? tr : 077            if hasSeason {78                guard seas.count == m else { throw StatError.invalidInput("initial seasonal states must have `period` entries") }79                s0 = seas80            }81        case .heuristic:82            if hasSeason {83                var sum = 0.0, cnt = 084                for i in stride(from: 0, to: n, by: m) { sum += y[i]; cnt += 1 }85                l0 = sum / Double(cnt)86                if hasTrend { b0 = (0..<m).reduce(0.0) { $0 + (y[m + $1] - y[$1]) / Double(m) } / Double(m) }87                s0 = (0..<m).map { seasonal == .multiplicative ? y[$0] / l0 : y[$0] - l0 }88            } else {89                l0 = y[0]90                if hasTrend { b0 = y[1] - y[0] }91            }92        }93        let config = Config(trend: trend, seasonal: seasonal, m: m, l0: l0, b0: b0, s0: s0)9495        if let p = parameters {96            try validate(p, config)97            return config.run(y, p, optimized: false, converged: true)98        }99100        // optimise SSE101        var names = ["alpha"]102        if hasTrend { names.append("beta") }103        if hasSeason { names.append("gamma") }104        if trend == .dampedAdditive { names.append("phi") }105        let bounds: [ClosedRange<Double>] = names.map { $0 == "phi" ? 0.8...0.995 : 0.0...1.0 }106        func unpack(_ v: [Double]) -> Parameters {107            var p = Parameters(alpha: v[0])108            var i = 1109            if hasTrend { p.beta = v[i]; i += 1 }110            if hasSeason { p.gamma = v[i]; i += 1 }111            if trend == .dampedAdditive { p.phi = v[i] }112            return p113        }114        let objective: ([Double]) -> Double = { v in115            let sse = config.sse(y, unpack(v))116            return sse.isFinite ? sse : .greatestFiniteMagnitude117        }118        var opt = Minimizer.NelderMeadOptions()119        opt.xtol = 1e-9; opt.ftol = 1e-12 * max(1, Descriptive.sumSquaredDeviations(y))120        opt.maxIterations = 4000; opt.maxEvaluations = 8000121        let starts: [[Double]] = [[0.3, 0.1, 0.1], [0.8, 0.2, 0.05], [0.1, 0.05, 0.3], [0.5, 0.5, 0.5], [0.95, 0.01, 0.6]]122        var best: MinimizeResult?123        for s in starts {124            let start = names.enumerated().map { i, name in name == "phi" ? 0.9 : s[min(i, 2)] }125            let r = try Minimizer.nelderMead(objective, start: start, bounds: bounds, options: opt)126            if best == nil || r.value < best!.value { best = r }127        }128        return config.run(y, unpack(best!.x), optimized: true, converged: best!.converged)129    }130131    private static func validate(_ p: Parameters, _ c: Config) throws {132        func unit(_ v: Double?, _ name: String, required: Bool) throws {133            guard let v else {134                if required { throw StatError.invalidInput("\(name) is required for this model") }135                return136            }137            guard v >= 0, v <= 1 else { throw StatError.invalidInput("\(name) must be in [0, 1]") }138        }139        try unit(p.alpha, "alpha", required: true)140        try unit(p.beta, "beta", required: c.trend != .none)141        try unit(p.gamma, "gamma", required: c.seasonal != .none)142        if c.trend == .dampedAdditive {143            guard let phi = p.phi, phi > 0, phi <= 1 else { throw StatError.invalidInput("phi must be in (0, 1] for a damped trend") }144        }145    }146147    /// Model structure and initial states; runs the recursions.148    struct Config {149        var trend: Trend150        var seasonal: Seasonal151        var m: Int152        var l0: Double153        var b0: Double154        var s0: [Double]155156        func sse(_ y: [Double], _ p: Parameters) -> Double {157            var total = 0.0158            var t = 0159            recurse(y, p) { _, fitted, _, _, _ in160                let e = y[t] - fitted161                total += e * e162                t += 1163            }164            return total165        }166167        /// Calls `visit(t, fitted_t, level_t, trend_t, season_t)` for each observation.168        func recurse(_ y: [Double], _ p: Parameters, _ visit: (Int, Double, Double, Double, Double) -> Void) {169            let alpha = p.alpha, beta = p.beta ?? 0, gamma = p.gamma ?? 0170            let phi = trend == .dampedAdditive ? (p.phi ?? 1) : 1171            let hasTrend = trend != .none172            var l = l0, b = hasTrend ? b0 : 0173            var s = s0                      // ring buffer: s[t % m] holds s_{t−m} before the update at t174            for t in 0..<y.count {175                let base = l + phi * b176                var fitted = base177                var newL: Double178                var season = 0.0179                switch seasonal {180                case .none:181                    newL = alpha * y[t] + (1 - alpha) * base182                case .additive:183                    let sOld = s[t % m]184                    fitted = base + sOld185                    newL = alpha * (y[t] - sOld) + (1 - alpha) * base186                    season = gamma * (y[t] - base) + (1 - gamma) * sOld187                    s[t % m] = season188                case .multiplicative:189                    let sOld = s[t % m]190                    fitted = base * sOld191                    newL = alpha * (y[t] / sOld) + (1 - alpha) * base192                    season = gamma * y[t] / base + (1 - gamma) * sOld193                    s[t % m] = season194                }195                if hasTrend { b = beta * (newL - l) + (1 - beta) * phi * b }196                l = newL197                visit(t, fitted, l, b, season)198            }199        }200201        func run(_ y: [Double], _ p: Parameters, optimized: Bool, converged: Bool) -> ExponentialSmoothingFit {202            let n = y.count203            var fitted = [Double](), level = [Double](), tr = [Double](), seas = [Double]()204            fitted.reserveCapacity(n); level.reserveCapacity(n)205            recurse(y, p) { _, f, l, b, s in206                fitted.append(f); level.append(l)207                if trend != .none { tr.append(b) }208                if seasonal != .none { seas.append(s) }209            }210            let resid = zip(y, fitted).map { $0 - $1 }211            let sse = resid.reduce(0) { $0 + $1 * $1 }212            var clean = Parameters(alpha: p.alpha)213            if trend != .none { clean.beta = p.beta }214            if seasonal != .none { clean.gamma = p.gamma }215            if trend == .dampedAdditive { clean.phi = p.phi }216            return ExponentialSmoothingFit(trend: trend, seasonal: seasonal, period: m, parameters: clean,217                                           initialLevel: l0, initialTrend: trend != .none ? b0 : nil, initialSeasonal: s0,218                                           level: level, trendComponent: tr, seasonalComponent: seas,219                                           fitted: fitted, residuals: resid, sse: sse, n: n,220                                           optimized: optimized, converged: converged)221        }222    }223}224225/// Point forecasts with a symmetric prediction interval.226public struct ForecastInterval: Sendable, Hashable, Codable, TableReport {227    /// Horizons 1…h.228    public var horizon: [Int]229    public var mean: [Double]230    /// Standard error of the forecast at each horizon.231    public var standardError: [Double]232    public var lower: [Double]233    public var upper: [Double]234    public var confidence: Double235236    public func table() -> [[Value]] {237        let pct = Int((confidence * 100).rounded())238        var out: [[Value]] = [[.text("Horizon"), .text("Forecast"), .text("Std. error"), .text("Lower \(pct)%"), .text("Upper \(pct)%")]]239        for i in horizon.indices {240            out.append([Report.int(horizon[i]), Report.num(mean[i]), Report.num(standardError[i]), Report.num(lower[i]), Report.num(upper[i])])241        }242        return out243    }244}245246/// A fitted exponential smoothing model.247public struct ExponentialSmoothingFit: Sendable, Hashable, Codable, TableReport {248    public var trend: ExponentialSmoothing.Trend249    public var seasonal: ExponentialSmoothing.Seasonal250    /// Season length (1 without a seasonal component).251    public var period: Int252    public var parameters: ExponentialSmoothing.Parameters253    public var initialLevel: Double254    public var initialTrend: Double?255    public var initialSeasonal: [Double]256    /// l_1…l_n.257    public var level: [Double]258    /// b_1…b_n (empty without a trend).259    public var trendComponent: [Double]260    /// s_1…s_n (empty without a season).261    public var seasonalComponent: [Double]262    /// One-step-ahead fitted values.263    public var fitted: [Double]264    public var residuals: [Double]265    /// Sum of squared one-step errors.266    public var sse: Double267    public var n: Int268    /// True when the smoothing parameters were estimated.269    public var optimized: Bool270    public var converged: Bool271272    public var mse: Double { sse / Double(n) }273    public var rmse: Double { mse.squareRoot() }274    public var mae: Double { residuals.reduce(0) { $0 + abs($1) } / Double(n) }275    /// Mean absolute percentage error in percent (NaN when an observation is 0).276    public var mape: Double {277        var s = 0.0278        for (e, f) in zip(residuals, fitted) {279            let y = e + f280            if y == 0 { return .nan }281            s += abs(e / y)282        }283        return 100 * s / Double(n)284    }285    /// Parameter count used by AIC/BIC, counted as statsmodels' Holt–Winters does:286    /// 2 (α, l_0) + 2 with a trend (β, b_0) + 1 if damped (φ) + m with a season.287    public var parameterCount: Int {288        var k = 2289        if trend != .none { k += 2 }290        if trend == .dampedAdditive { k += 1 }291        if seasonal != .none { k += period }292        return k293    }294    /// n·ln(SSE/n) + 2k.295    public var aic: Double { Double(n) * log(sse / Double(n)) + 2 * Double(parameterCount) }296    /// n·ln(SSE/n) + k·ln(n).297    public var bic: Double { Double(n) * log(sse / Double(n)) + Double(parameterCount) * log(Double(n)) }298    /// Residual variance used by the prediction intervals: SSE / n.299    public var residualVariance: Double { sse / Double(n) }300301    private var phi: Double { trend == .dampedAdditive ? (parameters.phi ?? 1) : 1 }302303    /// Point forecasts for horizons 1…h.304    public func forecast(_ h: Int) -> [Double] {305        guard h > 0, let l = level.last else { return [] }306        let b = trendComponent.last ?? 0307        var out = [Double]()308        var phiSum = 0.0, phiPow = 1.0309        for k in 1...h {310            phiPow *= phi311            phiSum += phiPow312            let base = l + (trend == .none ? 0 : phiSum * b)313            switch seasonal {314            case .none: out.append(base)315            case .additive, .multiplicative:316                let s = seasonalComponent[n - period + (k - 1) % period]317                out.append(seasonal == .additive ? base + s : base * s)318            }319        }320        return out321    }322323    /// Forecast variance divided by the residual variance at horizons 1…h, for the linear ("class 1")324    /// models with additive errors: 1 + Σ_{j=1}^{h−1} c_j², c_j = α + αβ(φ + … + φ^j) + γ·[j mod m = 0]325    /// (Hyndman, Koehler, Ord & Snyder 2008, ch. 6). Nil for multiplicative seasonality, for which no326    /// closed form exists.327    public func relativeForecastVariance(_ h: Int) -> [Double]? {328        guard seasonal != .multiplicative, h > 0 else { return nil }329        let alpha = parameters.alpha330        let betaSS = trend == .none ? 0 : alpha * (parameters.beta ?? 0)331        let gamma = seasonal == .none ? 0 : (parameters.gamma ?? 0)332        var out = [1.0]333        var acc = 1.0, phiSum = 0.0, phiPow = 1.0334        if h > 1 {335            for j in 1..<h {336                phiPow *= phi337                phiSum += phiPow338                let c = alpha + betaSS * phiSum + (seasonal != .none && j % period == 0 ? gamma : 0)339                acc += c * c340                out.append(acc)341            }342        }343        return out344    }345346    /// Forecasts with normal-theory prediction intervals ŷ ± z·σ·√(relative variance), σ² = SSE/n.347    /// Available for models without multiplicative seasonality (returns nil otherwise).348    public func forecastInterval(_ h: Int, confidence: Double = 0.95) -> ForecastInterval? {349        guard let rel = relativeForecastVariance(h), confidence > 0, confidence < 1 else { return nil }350        let mean = forecast(h)351        let z = SpecialFunctions.normalQuantile(upper: (1 - confidence) / 2)352        let se = rel.map { (residualVariance * $0).squareRoot() }353        return ForecastInterval(horizon: Array(1...h), mean: mean, standardError: se,354                                lower: zip(mean, se).map { $0 - z * $1 }, upper: zip(mean, se).map { $0 + z * $1 },355                                confidence: confidence)356    }357358    public func table() -> [[Value]] {359        var out: [[Value]] = [360            Report.row("Model", "Exponential smoothing (trend: \(trend.rawValue), seasonal: \(seasonal.rawValue))"),361            Report.row("Observations", n),362            Report.row("Alpha (level)", parameters.alpha),363        ]364        if let b = parameters.beta { out.append(Report.row("Beta (trend)", b)) }365        if let g = parameters.gamma { out.append(Report.row("Gamma (seasonal)", g)) }366        if let p = parameters.phi { out.append(Report.row("Phi (damping)", p)) }367        if seasonal != .none { out.append(Report.row("Season length", period)) }368        out.append(Report.row("Parameters", optimized ? "estimated (least squares)" : "fixed"))369        out.append(Report.row("Initial level", initialLevel))370        if let b0 = initialTrend { out.append(Report.row("Initial trend", b0)) }371        out.append(Report.row("SSE", sse))372        out.append(Report.row("RMSE", rmse))373        out.append(Report.row("MAE", mae))374        out.append(Report.row("AIC", aic))375        out.append(Report.row("BIC", bic))376        out.append([.text("Final level"), Report.num(level.last ?? .nan)])377        if let b = trendComponent.last { out.append(Report.row("Final trend", b)) }378        return Report.rectangular(out)379    }380}381
Files main
Menu

Theme