Repository Public
1import Foundation2import SheetCore3import Statistics45/// Least-squares linear trend y = intercept + slope·t fitted on t = 1…n.6public struct LinearTrend: Sendable, Hashable, Codable, TableReport {7 public var slope: Double8 public var intercept: Double9 public var rSquared: Double10 /// Residual standard error, √(SSE / (n − 2)).11 public var standardError: Double12 public var observations: Int13 public var fitted: [Double]1415 /// Point forecast for period n + h (h ≥ 1).16 public func forecast(steps h: Int) -> Double { intercept + slope * Double(observations + h) }1718 /// Point forecasts for the next `horizon` periods.19 public func forecasts(horizon: Int) -> [Double] { (1...max(1, horizon)).prefix(max(0, horizon)).map { forecast(steps: $0) } }2021 /// Prediction interval for a new observation at period n + h:22 /// ŷ ± t(1 − α/2; n − 2)·s·√(1 + 1/n + (t₀ − t̄)²/Sₜₜ). Assumes independent normal errors.23 public func predictionInterval(steps h: Int, confidence: Double = 0.95) -> (lower: Double, upper: Double) {24 let n = Double(observations)25 guard observations > 2 else { return (.nan, .nan) }26 let tBar = (n + 1) / 2, stt = n * (n * n - 1) / 1227 let t0 = n + Double(h)28 let half = StudentTDistribution(df: n - 2).quantile(1 - (1 - confidence) / 2) * standardError * (1 + 1 / n + (t0 - tBar) * (t0 - tBar) / stt).squareRoot()29 let y = forecast(steps: h)30 return (y - half, y + half)31 }3233 public func table() -> [[Value]] {34 [Report.row("Slope (per period)", slope), Report.row("Intercept", intercept), Report.row("R²", rSquared),35 Report.row("Residual standard error", standardError), Report.row("Observations", observations)]36 }37}3839public enum Forecasting {40 /// Compound annual growth rate: (end / begin)^(1 / periods) − 1. nil when it is undefined41 /// (non-positive values or periods).42 public static func cagr(begin: Double, end: Double, periods: Double) -> Double? {43 guard begin > 0, end > 0, periods > 0 else { return nil }44 return pow(end / begin, 1 / periods) - 145 }4647 /// CAGR of a series from its first to its last value over n − 1 periods.48 public static func cagr(_ series: [Double]) -> Double? {49 guard let first = series.first, let last = series.last, series.count > 1 else { return nil }50 return cagr(begin: first, end: last, periods: Double(series.count - 1))51 }5253 /// Value after `periods` of compound growth.54 public static func compoundGrowth(from value: Double, rate: Double, periods: Double) -> Double { value * pow(1 + rate, periods) }5556 /// Ordinary least-squares trend line on the time index t = 1…n.57 public static func linearTrend(_ y: [Double]) throws -> LinearTrend {58 let n = y.count59 guard n >= 2 else { throw StatError.insufficientData("a trend needs at least two observations") }60 let t = (1...n).map(Double.init)61 let tBar = Descriptive.mean(t), yBar = Descriptive.mean(y)62 var sty = 0.0, stt = 0.063 for i in 0..<n { sty += (t[i] - tBar) * (y[i] - yBar); stt += (t[i] - tBar) * (t[i] - tBar) }64 let slope = sty / stt, intercept = yBar - slope * tBar65 let fitted = t.map { intercept + slope * $0 }66 let sse = zip(y, fitted).reduce(0) { $0 + ($1.0 - $1.1) * ($1.0 - $1.1) }67 let sst = y.reduce(0) { $0 + ($1 - yBar) * ($1 - yBar) }68 return LinearTrend(slope: slope, intercept: intercept, rSquared: sst > 0 ? 1 - sse / sst : .nan,69 standardError: n > 2 ? (sse / Double(n - 2)).squareRoot() : .nan, observations: n, fitted: fitted)70 }7172 /// Seasonal naive forecast: each future period repeats the value of the same season one cycle73 /// earlier, ŷ(n + h) = y(n + h − m·⌈h/m⌉) for season length m.74 public static func seasonalNaive(_ y: [Double], seasonLength m: Int, horizon: Int) throws -> [Double] {75 guard m >= 1, y.count >= m else { throw StatError.insufficientData("seasonal naive needs at least one full season of data") }76 guard horizon >= 0 else { throw StatError.invalidInput("horizon cannot be negative") }77 let n = y.count78 return (1...max(1, horizon)).prefix(horizon).map { h in y[n - m + (h - 1) % m] }79 }8081 /// Naive forecast with drift: ŷ(n + h) = y_n + h·(y_n − y_1)/(n − 1).82 public static func drift(_ y: [Double], horizon: Int) throws -> [Double] {83 guard y.count >= 2, let first = y.first, let last = y.last else { throw StatError.insufficientData("drift needs at least two observations") }84 let d = (last - first) / Double(y.count - 1)85 return (1...max(1, horizon)).prefix(max(0, horizon)).map { last + Double($0) * d }86 }87}88