SPB Git

Repository Public

SmoothingTool.swift 6.6 KB 90 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Exponential smoothing: simple, Holt, damped Holt, Holt–Winters.7enum ExponentialSmoothingTool {8    static let models: [FieldOption] = [9        FieldOption("simple", L("Simple (level only)")), FieldOption("holt", L("Holt (linear trend)")), FieldOption("damped", L("Damped Holt")),10        FieldOption("hwAdditive", L("Holt–Winters, additive seasonality")), FieldOption("hwMultiplicative", L("Holt–Winters, multiplicative seasonality")),11    ]1213    static let descriptor: ToolDescriptor = {14        var t = ToolDescriptor(15            id: "timeseries.smoothing", title: L("Exponential Smoothing"), group: L("Time series"), systemImage: "chart.line.flattrend.xyaxis",16            summary: L("Fits an exponential-smoothing model with optimised parameters and forecasts the next periods."),17            fields: [18                .range("data", L("Data range")),19                .column("series", L("Series")),20                .column("time", L("Dates or x values"), optional: true, help: L("Optional increasing dates or numbers for the chart axis.")),21                .choice("model", L("Model"), models, default: "hwAdditive"),22                .integer("period", L("Season length"), 12, min: 2, max: 366, visible: { $0.choice("model").hasPrefix("hw") }),23                .toggle("dampedSeasonal", L("Damped trend"), false, visible: { $0.choice("model").hasPrefix("hw") }),24                .integer("horizon", L("Forecast horizon"), 12, min: 1, max: 500),25                .percent("level", L("Prediction level"), 0.95, min: 0.5, max: 0.9999),26            ],27            info: [28                L("Parameters minimise the sum of squared one-step errors (bounded Nelder–Mead, 5 starts); the damping parameter φ is searched in [0.8, 0.995]. Initial states are heuristic and are not optimised."),29                L("At fixed parameters the recursions match statsmodels ExponentialSmoothing to 1e-10. At horizons that are multiples of the season length statsmodels reuses an older seasonal state; this implementation uses the latest one (textbook formula)."),30                L("Prediction intervals are available for the additive (linear) models only; none is shipped for multiplicative seasonality."),31                L("Multiplicative trend and multiplicative-error (ETS) models are not shipped."),32            ],33            run: run)34        t.demo = { _, v in v.set("data", range: "Series!A1:B85"); v.set("series", column: 1); v.set("time", column: 0) }35        return t36    }()3738    static func configuration(_ input: ToolInput) -> (trend: ExponentialSmoothing.Trend, seasonal: ExponentialSmoothing.Seasonal, period: Int) {39        let damped = input.values.bool("dampedSeasonal")40        switch input.values.choice("model") {41        case "simple": return (.none, .none, 1)42        case "holt": return (.additive, .none, 1)43        case "damped": return (.dampedAdditive, .none, 1)44        case "hwMultiplicative": return (damped ? .dampedAdditive : .additive, .multiplicative, max(input.values.int("period"), 2))45        default: return (damped ? .dampedAdditive : .additive, .additive, max(input.values.int("period"), 2))46        }47    }4849    static func run(_ input: ToolInput) throws -> ToolResult {50        let s = try Sup.series(input, minimum: 4)51        let cfg = configuration(input)52        if cfg.seasonal != .none, s.values.count < 2 * cfg.period {53            throw ToolError(L("A seasonal model needs at least two full seasons (%d observations); the series has %d.", 2 * cfg.period, s.values.count))54        }55        let fit = try ExponentialSmoothing.fit(s.values, trend: cfg.trend, seasonal: cfg.seasonal, period: cfg.period)56        let h = max(input.values.int("horizon"), 1), level = Sup.level(input), loc = input.locale57        let interval = fit.forecastInterval(h, confidence: level)58        let f = ForecastSupport.Forecast(mean: fit.forecast(h), lower: interval?.lower, upper: interval?.upper, standardError: interval?.standardError)59        let axis = Sup.axis(input, "time", rows: s.rows)60        let modelName = models.first { $0.id == input.values.choice("model") }?.label ?? ""6162        var params: [(String, Value, CellFormat)] = [(L("Level smoothing α"), .finite(fit.parameters.alpha), .fixed(4))]63        if let b = fit.parameters.beta { params.append((L("Trend smoothing β"), .finite(b), .fixed(4))) }64        if let g = fit.parameters.gamma { params.append((L("Seasonal smoothing γ"), .finite(g), .fixed(4))) }65        if let p = fit.parameters.phi { params.append((L("Damping φ"), .finite(p), .fixed(4))) }66        params.append((L("Initial level"), .finite(fit.initialLevel), .auto))67        if let t = fit.initialTrend { params.append((L("Initial trend"), .finite(t), .auto)) }68        let accuracy: [(String, Value, CellFormat)] = [69            (L("Observations"), .finite(Double(fit.n)), .integer), (L("Sum of squared errors"), .finite(fit.sse), .auto),70            (L("Root mean squared error"), .finite(fit.rmse), .auto), (L("Mean absolute error"), .finite(fit.mae), .auto),71            (L("Mean absolute percentage error"), .finite(fit.mape / 100), .percent(2)), ("AIC", .finite(fit.aic), .fixed(3)), ("BIC", .finite(fit.bic), .fixed(3)),72        ]73        var notes = [String]()74        if interval == nil { notes.append(L("No prediction interval is available for multiplicative seasonality; only point forecasts are shown.")) }75        if !fit.converged { notes.append(L("The parameter optimisation did not report convergence; the best parameters found are shown.")) }76        if let n = Sup.droppedNote(s) { notes.append(n) }77        notes.append(L("Errors are one-step-ahead, in-sample."))78        let blocks: [ResultBlock] = [79            .metrics([Metric(L("RMSE"), fit.rmse), Metric(L("MAE"), fit.mae), Metric(L("MAPE"), fit.mape / 100, .percent(2)), Metric(L("α"), fit.parameters.alpha, .fixed(4))]),80            .chart(ForecastSupport.chart(title: L("%@ — fitted values and forecast", s.name), series: s, axis: axis, fitted: fit.fitted, forecast: f, level: level, locale: loc)),81            .table(ReportTable.keyValue(title: L("Parameters"), header: (L("Parameter"), L("Value")), params)),82            .table(ReportTable.keyValue(title: L("Accuracy"), header: (L("Measure"), L("Value")), accuracy)),83            .table(ForecastSupport.table(axis: axis, forecast: f, level: level, locale: loc)),84            .note(notes),85        ]86        return ToolResult(title: L("Exponential Smoothing"), subtitle: L("%@ — %@", s.frame.label, modelName), blocks: blocks,87                          actions: [ForecastSupport.writeAction(series: s, column: try input.column("series"), forecast: f)], sheetName: L("Smoothing"))88    }89}90
Files main
Menu

Theme