SPB Git

Repository Public

VolatilityTools.swift 10.5 KB 137 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// GARCH(1,1) conditional volatility.7enum GARCHTool {8    static let descriptor: ToolDescriptor = {9        var t = ToolDescriptor(10            id: "timeseries.garch", title: L("GARCH(1,1)"), group: L("Time series"), systemImage: "waveform",11            summary: L("Fits a GARCH(1,1) model to a series of returns by Gaussian maximum likelihood and shows the conditional volatility."),12            fields: [13                .range("data", L("Data range")),14                .column("series", L("Returns")),15                .toggle("percent", L("Returns are decimals: estimate on percent returns (×100)"), true,16                        help: L("Very small numbers make ω hard to optimise; volatility is then reported in percent.")),17                .choice("mean", L("Mean model"), [FieldOption("constant", L("Constant mean")), FieldOption("zero", L("Zero mean"))]),18                .integer("horizon", L("Variance forecast horizon"), 10, min: 1, max: 250),19            ],20            info: [21                L("Model: r = μ + ε, σ²(t) = ω + α·ε²(t−1) + β·σ²(t−1), Gaussian innovations, recursion started by the backcast of the arch package."),22                L("At fixed parameters the log-likelihood and variance path match arch 8 to 1e-10. Optimised parameters agree with arch to about 5e-3 (relative), the log-likelihood to 1e-4."),23                L("Standard errors of the parameters are NOT shipped (no validated robust standard errors), so no significance tests are shown."),24                L("Other orders and Student-t or skewed innovations are not shipped."),25            ],26            run: run)27        t.demo = { _, v in v.set("data", range: "Returns!A1:B501"); v.set("series", column: 1) }28        return t29    }()3031    static func run(_ input: ToolInput) throws -> ToolResult {32        let s = try Sup.series(input, minimum: 30)33        let scale = input.values.bool("percent") ? 100.0 : 1.034        let r = s.values.map { $0 * scale }35        let meanModel: GARCH.MeanModel = input.values.choice("mean") == "zero" ? .zero : .constant36        let fit = try GARCH.fit(r, mean: meanModel)37        let h = max(input.values.int("horizon"), 1), loc = input.locale38        let unit = scale == 100 ? L("percent per period") : L("return units per period")39        let vol = fit.conditionalVolatility40        let fv = fit.forecastVariance(h)41        var items: [(String, Value, CellFormat)] = []42        if meanModel == .constant { items.append((L("Mean μ"), .finite(fit.parameters.mu), .fixed(6))) }43        items += [44            ("ω", .finite(fit.parameters.omega), .fixed(6)), (L("α (reaction to shocks)"), .finite(fit.parameters.alpha), .fixed(6)),45            (L("β (variance persistence)"), .finite(fit.parameters.beta), .fixed(6)), (L("Persistence α + β"), .finite(fit.persistence), .fixed(6)),46            (L("Half-life of a variance shock (periods)"), .finite(fit.halfLife), .fixed(2)),47            (L("Unconditional volatility"), .finite(fit.unconditionalVariance.map { $0.squareRoot() }), .fixed(4)),48            (L("Log-likelihood"), .finite(fit.logLikelihood), .fixed(4)), ("AIC", .finite(fit.aic), .fixed(4)), ("BIC", .finite(fit.bic), .fixed(4)),49            (L("Observations"), .finite(Double(fit.n)), .integer),50        ]51        var rows: [[Value]] = [[.text(L("Horizon")), .text(L("Variance forecast")), .text(L("Volatility forecast"))]]52        for (i, v) in fv.enumerated() { rows.append([.number(Double(i + 1)), .finite(v), .finite(v.squareRoot())]) }53        var notes = [L("Volatility is the conditional standard deviation, in %@.", unit),54                     L("No standard errors are shipped for GARCH parameters; estimates are approximate to the documented tolerance (5e-3 against arch).")]55        if fit.unconditionalVariance == nil { notes.append(L("α + β ≥ 1: the unconditional variance does not exist.")) }56        if !fit.converged { notes.append(L("The likelihood optimisation did not report convergence; the best parameters found are shown.")) }57        if let n = Sup.droppedNote(s) { notes.append(n) }58        let x = (0..<vol.count).map { Double($0 + 1) }59        let blocks: [ResultBlock] = [60            .metrics([Metric("α", fit.parameters.alpha, .fixed(4)), Metric("β", fit.parameters.beta, .fixed(4)), Metric(L("Persistence α + β"), fit.persistence, .fixed(4)),61                      Metric(L("Unconditional volatility"), fit.unconditionalVariance.map { $0.squareRoot() } ?? .nan, .fixed(4))]),62            .chart(ChartBlock(title: L("Conditional volatility"), spec: ChartKit.lines([.init(L("Conditional volatility"), vol, x: x)], xTitle: L("Observation"), yTitle: L("Volatility (%@)", unit)),63                              summary: L("Conditional volatility over %d observations, between %@ and %@; last value %@.", vol.count, Fmt.number(vol.min() ?? .nan, locale: loc),64                                         Fmt.number(vol.max() ?? .nan, locale: loc), Fmt.number(vol.last ?? .nan, locale: loc)), height: 260)),65            .table(ReportTable.keyValue(title: L("Estimates"), header: (L("Quantity"), L("Value")), items)),66            .table(ReportTable(title: L("Variance forecasts"), rows: rows, headerColumn: false, columnFormats: [0: .integer, 1: .fixed(6), 2: .fixed(4)])),67            .note(notes),68        ]69        let action = Sup.writeColumns(id: "write-volatility", title: L("Write Conditional Volatility"), label: L("Write Conditional Volatility"), frame: s.frame,70                                      names: [L("Conditional volatility")], columns: [s.frame.expand(vol, rows: s.rows)])71        return ToolResult(title: "GARCH(1,1)", subtitle: L("%@ — series: %@", s.frame.label, s.name), blocks: blocks, actions: [action], sheetName: "GARCH")72    }73}7475/// Augmented Dickey–Fuller unit-root test.76enum ADFTool {77    static let descriptor: ToolDescriptor = {78        var t = ToolDescriptor(79            id: "timeseries.adf", title: L("Augmented Dickey–Fuller Test"), group: L("Time series"), systemImage: "arrow.triangle.turn.up.right.diamond",80            summary: L("Tests whether a series has a unit root (is non-stationary)."),81            fields: [82                .range("data", L("Data range")),83                .column("series", L("Series")),84                .choice("regression", L("Deterministic terms"), [FieldOption("c", L("Constant")), FieldOption("ct", L("Constant and trend")), FieldOption("n", L("None"))]),85                .choice("lagRule", L("Lag selection"), [FieldOption("aic", "AIC"), FieldOption("bic", "BIC"), FieldOption("fixed", L("Fixed"))]),86                .integer("lags", L("Lags"), 0, min: 0, max: 100, help: L("Fixed: the number of lagged differences. AIC / BIC: the maximum lag (0 = automatic, 12·(n/100)^¼).")),87                .alpha(L("Significance level α")),88            ],89            info: [90                L("The statistic, the selected lag and the number of observations match statsmodels adfuller (validated on 72 cases)."),91                L("p-values use MacKinnon's (1994) response surfaces; critical values use MacKinnon (2010)."),92                L("The test rejects for large negative statistics (lower tail). Failing to reject does not prove that a unit root is present."),93                L("The “ctt” regression, t-statistic lag selection, KPSS and Phillips–Perron tests are not shipped."),94            ],95            run: run)96        t.demo = { _, v in v.set("data", range: "Series!A1:B85"); v.set("series", column: 1); v.set("regression", choice: "ct") }97        return t98    }()99100    static func run(_ input: ToolInput) throws -> ToolResult {101        let s = try Sup.series(input, minimum: 12)102        let regression = UnitRootTest.Regression(rawValue: input.values.choice("regression")) ?? .constant103        let n = input.values.int("lags")104        let selection: UnitRootTest.LagSelection105        switch input.values.choice("lagRule") {106        case "fixed": selection = .fixed(n)107        case "bic": selection = .bic(maxLag: n > 0 ? n : nil)108        default: selection = .aic(maxLag: n > 0 ? n : nil)109        }110        let r = try UnitRootTest.augmentedDickeyFuller(s.values, regression: regression, lags: selection)111        let alpha = Sup.alpha(input), loc = input.locale112        let terms: String = { switch regression { case .none: L("none"); case .constant: L("constant"); case .constantTrend: L("constant and trend") } }()113        var items: [(String, Value, CellFormat)] = [114            (L("ADF statistic (τ)"), .finite(r.statistic), .fixed(4)), (L("p-value (MacKinnon, lower tail)"), .finite(r.pValue), .pValue),115            (L("Lags used"), .finite(Double(r.usedLag)), .integer), (L("Observations used"), .finite(Double(r.nobs)), .integer),116            (L("Deterministic terms"), .text(terms), .auto),117            (L("Critical value 1 %"), .finite(r.critical1), .fixed(4)), (L("Critical value 5 %"), .finite(r.critical5), .fixed(4)),118            (L("Critical value 10 %"), .finite(r.critical10), .fixed(4)),119        ]120        if let ic = r.informationCriterion { items.append((L("Information criterion at the selected lag"), .finite(ic), .fixed(4))) }121        var notes = [L("The alternative hypothesis is stationarity (around the chosen deterministic terms); the p-value is a lower-tail probability.")]122        if let d = Sup.droppedNote(s) { notes.append(d) }123        let blocks: [ResultBlock] = [124            .metrics([Metric(L("ADF statistic (τ)"), r.statistic, .fixed(4)), Metric(L("p-value"), r.pValue, .pValue, detail: L("(lower tail)")),125                      Metric(L("Lags used"), Double(r.usedLag), .integer), Metric(L("Critical value 5 %"), r.critical5, .fixed(4))]),126            .table(ReportTable.keyValue(title: L("Augmented Dickey–Fuller test"), header: (L("Quantity"), L("Value")), items)),127            .interpretation(Interpret.decision(p: r.pValue, alpha: alpha, null: L("the series has a unit root (it is non-stationary)"), locale: loc)),128            .chart(ChartBlock(title: s.name, spec: ChartKit.lines([.init(s.name, s.values)], xTitle: L("Observation"), yTitle: s.name),129                              summary: L("Line chart of %d observations of %@.", s.values.count, s.name), height: 210)),130            .assumptions([L("Equally spaced observations in time order."), L("The lagged differences capture the serial correlation of the errors."),131                          L("The chosen deterministic terms match the data (a trending series needs “constant and trend”).")], title: L("Assumptions")),132            .note(notes),133        ]134        return ToolResult(title: L("Augmented Dickey–Fuller Test"), subtitle: L("%@ — series: %@", s.frame.label, s.name), blocks: blocks, sheetName: L("Unit root"))135    }136}137
Files main
Menu

Theme