Repository Public
1import Foundation2import SheetCore3import Statistics4import AnalysisKit5import SheetUI67/// Shared presentation of forecasts: history + fitted + forecast with band, and the forecast table.8enum ForecastSupport {9 struct Forecast {10 var mean: [Double]11 var lower: [Double]?12 var upper: [Double]?13 var standardError: [Double]?14 }1516 static func chart(title: String, series s: Sup.Series, axis: Sup.Axis, fitted: [Double]?, fittedOffset: Int = 0, forecast f: Forecast,17 level: Double, locale: Locale) -> ChartBlock {18 let fx = axis.extended(f.mean.count)19 var lines = [ChartKit.Line(s.name, s.values, x: axis.x)]20 if let fitted { lines.append(.init(L("Fitted"), fitted, x: Array(axis.x.dropFirst(fittedOffset)), dash: .dot)) }21 // the forecast line starts at the last observation so the two join22 let joinX = [axis.x.last ?? 0] + fx, last = s.values.last ?? .nan23 lines.append(.init(L("Forecast"), [last] + f.mean, x: joinX, lower: f.lower.map { [last] + $0 }, upper: f.upper.map { [last] + $0 }, dash: .dash))24 let spec = ChartKit.lines(lines, xTitle: axis.title, yTitle: s.name, dateAxis: axis.isDate)25 let band = f.lower != nil ? L("with a %@ prediction band", Fmt.percent(level, 0, locale: locale)) : L("without a prediction band")26 return ChartBlock(title: title, spec: spec,27 summary: L("%d observations of %@ followed by %d forecasts %@; the last forecast is %@.", s.values.count, s.name, f.mean.count, band,28 Fmt.number(f.mean.last ?? .nan, locale: locale)), height: 290)29 }3031 static func table(axis: Sup.Axis, forecast f: Forecast, level: Double, locale: Locale) -> ReportTable {32 let pct = Fmt.percent(level, 0, locale: locale)33 let fx = axis.extended(f.mean.count)34 var header: [Value] = [.text(L("Horizon"))]35 if axis.isDate { header.append(.text(axis.title)) }36 header.append(.text(L("Forecast")))37 if f.standardError != nil { header.append(.text(L("Std. error"))) }38 if f.lower != nil { header += [.text(L("%@ lower", pct)), .text(L("%@ upper", pct))] }39 var rows = [header]40 for i in f.mean.indices {41 var r: [Value] = [.number(Double(i + 1))]42 if axis.isDate { r.append(.number(fx[i])) }43 r.append(.finite(f.mean[i]))44 if let se = f.standardError { r.append(.finite(se[i])) }45 if let lo = f.lower, let hi = f.upper { r += [.finite(lo[i]), .finite(hi[i])] }46 rows.append(r)47 }48 var t = ReportTable(title: L("Forecasts"), rows: rows, headerColumn: false, columnFormats: [0: .integer])49 if axis.isDate { t.columnFormats[1] = .date }50 return t51 }5253 /// Action writing the forecasts below the series (same column), as values.54 static func writeAction(series s: Sup.Series, column: DataColumn, forecast f: Forecast) -> ResultAction {55 let frame = s.frame56 let values = f.mean57 return ResultAction(id: "write-forecasts", title: L("Write Forecasts Below the Series"), systemImage: "arrow.down.to.line",58 help: L("Writes the point forecasts in the rows under the data, in the column of the series. One step to undo.")) { session in59 let first = frame.range.r1 + 160 let col = column.sheetColumn61 session.perform(L("Write Forecasts")) { e in62 for (i, v) in values.enumerated() where v.isFinite {63 e.set(sheet: frame.sheet, row: first + i, col: col, .value(.number(v)))64 e.setStyle(sheet: frame.sheet, range: RangeRef(CellRef(first + i, col))) { $0.italic = true }65 }66 }67 let rg = RangeRef(r0: first, c0: col, r1: first + max(values.count - 1, 0), c1: col)68 session.select(rg, sheet: frame.sheet)69 session.scrollTarget = rg.topLeft70 return L("Forecasts written to %@", frame.sheetName + "!" + rg.a1)71 }72 }73}74