SPB Git

Repository Public

AutocorrelationTool.swift 7.7 KB 109 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Correlogram: ACF and PACF with confidence bands.7enum AutocorrelationTool {8    static let descriptor: ToolDescriptor = {9        var t = ToolDescriptor(10            id: "timeseries.acf", title: L("Autocorrelation (ACF / PACF)"), group: L("Time series"), systemImage: "waveform.path.ecg",11            summary: L("Autocorrelation and partial autocorrelation functions of an equally spaced series, with significance bounds."),12            fields: [13                .range("data", L("Data range")),14                .column("series", L("Series")),15                .integer("maxLag", L("Maximum lag"), 0, min: 0, max: 500, help: L("0 = automatic: 10·log10(n).")),16                .integer("diff", L("Difference the series first (order)"), 0, min: 0, max: 3),17                .percent("level", L("Confidence level"), 0.95, min: 0.5, max: 0.9999),18            ],19            info: [20                L("ACF uses divisor-n autocovariances with Bartlett standard errors; PACF uses the Durbin–Levinson recursion with standard error 1/√n (statsmodels acf / pacf, method “ldb”)."),21                L("The dashed bounds are ±z/√n: coefficients outside them differ from zero at the chosen level under the white-noise hypothesis."),22            ],23            run: run)24        t.demo = { _, v in v.set("data", range: "Series!A1:B85"); v.set("series", column: 1); v.set("maxLag", int: 24) }25        return t26    }()2728    static func run(_ input: ToolInput) throws -> ToolResult {29        let s = try Sup.series(input, minimum: 4)30        let d = input.values.int("diff")31        let x = d > 0 ? TimeSeries.difference(s.values, order: d) : s.values32        guard x.count >= 4 else { throw ToolError(L("Too few observations after differencing.")) }33        let level = Sup.level(input)34        let requested = input.values.int("maxLag")35        let maxLag = requested > 0 ? min(requested, x.count - 2) : nil36        let acf = try TimeSeries.acf(x, maxLag: maxLag, confidence: level)37        let pacf = try TimeSeries.pacf(x, maxLag: maxLag.map { min($0, x.count / 2 - 1) } ?? min(TimeSeries.defaultLags(x.count), x.count / 2 - 1), confidence: level)38        let loc = input.locale39        var rows: [[Value]] = [[.text(L("Lag")), .text("ACF"), .text(L("ACF std. error")), .text(L("ACF lower")), .text(L("ACF upper")), .text("PACF")]]40        for (i, lag) in acf.lags.enumerated() where lag >= 1 {41            let p: Value = i < pacf.values.count ? .finite(pacf.values[i]) : .blank42            rows.append([.number(Double(lag)), .finite(acf.values[i]), .finite(acf.standardErrors[i]), .finite(acf.lower[i]), .finite(acf.upper[i]), p])43        }44        let table = ReportTable(title: L("Autocorrelations"), rows: rows, headerColumn: false,45                                columnFormats: [0: .integer, 1: .fixed(4), 2: .fixed(4), 3: .fixed(4), 4: .fixed(4), 5: .fixed(4)])46        func chart(_ r: AutocorrelationResult, _ title: String, _ y: String) -> ChartBlock {47            let lags = r.lags.dropFirst(), values = r.values.dropFirst()48            let outside = values.filter { abs($0) > r.whiteNoiseBound }.count49            return ChartBlock(title: title, spec: ChartKit.columns(categories: lags.map(String.init), series: [(y, Array(values))], xTitle: L("Lag"), yTitle: y, bounds: r.whiteNoiseBound),50                              summary: L("%@ for lags 1 to %d; %d coefficients lie outside the ±%@ bounds.", y, r.lags.last ?? 0, outside, Fmt.fixed(r.whiteNoiseBound, 3, locale: loc)),51                              height: 220)52        }53        var notes = [L("Significance bound ±%@ (%@ level, n = %d).", Fmt.fixed(acf.whiteNoiseBound, 4, locale: loc), Fmt.percent(level, 0, locale: loc), acf.n)]54        if d > 0 { notes.append(L("The series was differenced %d time(s) before the analysis.", d)) }55        if let n = Sup.droppedNote(s) { notes.append(n) }56        return ToolResult(title: L("Autocorrelation of %@", s.name), subtitle: s.frame.label,57                          blocks: [.charts([chart(acf, L("Autocorrelation function (ACF)"), "ACF"), chart(pacf, L("Partial autocorrelation function (PACF)"), "PACF")]),58                                   .table(table), .note(notes)], sheetName: L("Autocorrelation"))59    }60}6162/// Regular / seasonal differencing.63enum DifferencingTool {64    static let descriptor: ToolDescriptor = {65        var t = ToolDescriptor(66            id: "timeseries.difference", title: L("Differencing"), group: L("Time series"), systemImage: "minus.forwardslash.plus",67            summary: L("Applies (1 − B^lag)^order to a series: lag 1 removes a trend, the season length removes a seasonal pattern."),68            fields: [69                .range("data", L("Data range")),70                .column("series", L("Series")),71                .integer("lag", L("Lag"), 1, min: 1, max: 366, help: L("1 = regular difference; season length (e.g. 12) = seasonal difference.")),72                .integer("order", L("Order"), 1, min: 1, max: 3),73            ],74            info: [L("Each pass shortens the series by “lag” observations (identical to numpy.diff for lag 1).")],75            run: run)76        t.demo = { _, v in v.set("data", range: "Series!A1:B85"); v.set("series", column: 1); v.set("lag", int: 12) }77        return t78    }()7980    static func run(_ input: ToolInput) throws -> ToolResult {81        let s = try Sup.series(input, minimum: 3)82        let lag = max(input.values.int("lag"), 1), order = max(input.values.int("order"), 1)83        guard s.values.count > lag * order + 1 else { throw ToolError(L("The series is too short for this lag and order.")) }84        let d = TimeSeries.difference(s.values, lag: lag, order: order)85        let lost = s.values.count - d.count86        let loc = input.locale87        let stats = { (x: [Double]) -> [Value] in [.number(Double(x.count)), .finite(Descriptive.mean(x)), .finite(Descriptive.standardDeviation(x)), .finite(x.min()), .finite(x.max())] }88        let table = ReportTable(title: L("Before and after"), rows: [89            [.text(L("Series")), .text(L("Observations")), .text(L("Mean")), .text(L("Standard deviation")), .text(L("Minimum")), .text(L("Maximum"))],90            [.text(s.name)] + stats(s.values), [.text(L("Differenced"))] + stats(d),91        ], columnFormats: [1: .integer])92        let x = (0..<s.values.count).map { Double($0 + 1) }93        let charts = [94            ChartBlock(title: L("Original series"), spec: ChartKit.lines([.init(s.name, s.values, x: x)], xTitle: L("Observation"), yTitle: s.name),95                       summary: L("Line chart of %d observations of %@.", s.values.count, s.name), height: 210),96            ChartBlock(title: L("Differenced series"), spec: ChartKit.lines([.init(L("Differenced"), d, x: Array(x.dropFirst(lost)))], xTitle: L("Observation"), yTitle: L("Difference")),97                       summary: L("Line chart of the %d differences; mean %@.", d.count, Fmt.number(Descriptive.mean(d), locale: loc)), height: 210),98        ]99        // differences are aligned with the later observation of each pair100        let name = order == 1 && lag == 1 ? L("Δ %@", s.name) : L("Δ(lag %d, order %d) %@", lag, order, s.name)101        let action = Sup.writeColumns(id: "write-differences", title: L("Write Differenced Series"), label: L("Write Differenced Series"), frame: s.frame,102                                      names: [name], columns: [s.frame.expand(d, rows: Array(s.rows.dropFirst(lost)))])103        var notes = [L("%d observations are lost at the start of the series.", lost)]104        if let n = Sup.droppedNote(s) { notes.append(n) }105        return ToolResult(title: L("Differencing of %@", s.name), subtitle: L("%@ — lag %d, order %d", s.frame.label, lag, order),106                          blocks: [.table(table), .charts(charts), .note(notes)], actions: [action], sheetName: L("Differencing"))107    }108}109
Files main
Menu

Theme