SPB Git

Repository Public

VQLabResult.swift 19.2 KB 347 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Lab/VQLabResult.swift3// Description: The generic Quant Lab result schema `lab/1` (CONTRACT §4.2). One model, one renderer per platform4//              (`LabResultView` in VQuantUI). Results of the six legacy tools are not `lab/1`: the apps keep their own5//              rendering for those (`VQLabResult.isLab(_:)` tells them apart).6import Foundation78/// Whether a number is observed, calculated, assumed or forecast.9public enum VQValueKind: String, Sendable, Hashable, CaseIterable {10    case observed, calculated, assumption, forecast1112    public func label(_ language: VQLanguage = .preferred) -> String {13        switch self {14        case .observed: return VQL10n.string("Observed", language)15        case .calculated: return VQL10n.string("Calculated", language)16        case .assumption: return VQL10n.string("Assumption", language)17        case .forecast: return VQL10n.string("Forecast", language)18        }19    }20    /// The short tag of the badge: OBS, CALC, HYP, PRÉV.21    public func short(_ language: VQLanguage = .preferred) -> String {22        switch self {23        case .observed: return VQL10n.string("OBS", language)24        case .calculated: return VQL10n.string("CALC", language)25        case .assumption: return VQL10n.string("ASM", language)26        case .forecast: return VQL10n.string("FCST", language)27        }28    }29    public func explanation(_ language: VQLanguage = .preferred) -> String {30        switch self {31        case .observed: return VQL10n.string("Observed value: provided as is by a data source, with its timestamp.", language)32        case .calculated: return VQL10n.string("Value calculated by an engine from observed data; the method and parameters are available.", language)33        case .assumption: return VQL10n.string("An assumption made by you or by the agent: not data.", language)34        case .forecast: return VQL10n.string("A model forecast: uncertain by nature.", language)35        }36    }37}3839public struct VQLabResult: Sendable, Equatable, VQJSONDecodable {40    public var success: Bool41    /// "lab/1"42    public var schema: String43    public var engine: String44    public var engineVersion: String?45    public var title: String46    /// One factual sentence.47    public var headline: String48    /// For `success == false`: a sentence a person can act on.49    public var error: String?50    public var summary: [Metric]51    public var tables: [Table]52    public var charts: [Chart]53    public var diagnostics: [Diagnostic]54    public var assumptions: [String]55    public var warnings: [String]56    /// Markdown, formulas in `$…$`.57    public var methodology: String58    public var provenance: Provenance?5960    public static let schemaPrefix = "lab/"61    /// True for a result in the generic schema (any `lab/…` version); false for the legacy tools' results.62    public static func isLab(_ json: VQJSON) -> Bool { json["schema"]?.stringValue?.hasPrefix(schemaPrefix) == true }63    /// nil for a legacy (non-`lab/…`) result.64    public static func ifLab(_ json: VQJSON?) -> VQLabResult? { json.flatMap { isLab($0) ? VQLabResult(json: $0) : nil } }6566    public init(json j: VQJSON) {67        success = j.flag("success"); schema = j.str("schema"); engine = j.str("engine"); engineVersion = j.optStr("engineVersion")68        title = j.str("title"); headline = j.str("headline"); error = j.optStr("error")69        summary = j.models("summary"); tables = j.models("tables"); charts = j.models("charts"); diagnostics = j.models("diagnostics")70        assumptions = j.strings("assumptions"); warnings = j.strings("warnings"); methodology = j.str("methodology"); provenance = j.model("provenance")71    }7273    // MARK: summary7475    public struct Metric: Sendable, Equatable, Identifiable, VQJSONDecodable {76        public var label: String77        /// nil = not available ("—").78        public var value: Double?79        /// A summary value that is text rather than a number (kept, shown as is).80        public var text: String?81        public var unit: VQValueUnit82        public var kind: VQOpen<VQValueKind>83        public var currency: String?84        public var decimals: Int?85        public var note: String?86        /// The unit exactly as the server wrote it (`years` and any unit added later are not cases of `VQValueUnit`).87        public var unitName: String?88        public var id: String { label }89        public init(json j: VQJSON) {90            unitName = j.optStr("unit")91            label = j.str("label"); value = j.num("value"); text = j.optStr("value"); unit = VQValueUnit(j.optStr("unit"))92            kind = j.open("kind", .calculated); currency = j.optStr("currency"); decimals = j.int("decimals"); note = j.optStr("note")93        }94        public func formatted(locale: VQNumberLocale = .frCA) -> String {95            if let text { return text }96            return VQFormat.byUnitName(value, unitName, decimals: decimals, currency: currency ?? "USD", compact: unit == .currency && abs(value ?? 0) >= 1e7, locale: locale)97        }98    }99100    // MARK: tables101102    public struct Table: Sendable, Equatable, Identifiable, VQJSONDecodable {103        public var id: String104        public var title: String105        public var columns: [Column]106        /// One object per row, keyed by `Column.key`; cells are numbers, strings, booleans or null.107        public var rows: [VQJSONObject]108        public var note: String?109        public init(json j: VQJSON) {110            id = j.str("id"); title = j.str("title"); columns = j.models("columns"); rows = j.list("rows").compactMap(\.objectValue); note = j.optStr("note")111        }112113        public struct Column: Sendable, Equatable, Identifiable, VQJSONDecodable {114            public var key: String115            public var label: String116            public var unit: VQValueUnit117            public var decimals: Int?118            /// `left` | `right` | `center`; nil = numbers right, text left.119            public var align: String?120            /// ISO 4217 code of a `currency` column whose rows share one currency.121            public var currency: String?122            /// Key of the column that holds each row's ISO code, when rows are in different currencies.123            public var currencyKey: String?124            /// What the values are; nil on results recorded before the server said it (then it is inferred).125            public var type: VQOpen<ColumnType>?126            /// The unit exactly as the server wrote it.127            public var unitName: String?128            public var id: String { key }129            public enum ColumnType: String, Sendable, Hashable, CaseIterable { case year, date, integer, text, number }130            public init(json j: VQJSON) {131                key = j.str("key"); label = j.str("label", key); unit = VQValueUnit(j.optStr("unit")); decimals = j.int("decimals"); align = j.optStr("align")132                currency = j.optStr("currency"); currencyKey = j.optStr("currencyKey"); type = j.optOpen("type"); unitName = j.optStr("unit")133            }134        }135136        /// The ISO code a currency cell of this row is in: the row's own (`currencyKey`), else the column's, else nil.137        public func currency(of row: VQJSONObject, _ column: Column) -> String? {138            column.currencyKey.flatMap { row[$0]?.stringValue } ?? column.currency139        }140141        /// The text of a cell as the renderer shows it, and whether it is numeric (right-aligned, tabular).142        /// Keys of the columns whose numbers are calendar years (undeclared unit, every value an integer in 1800…2200):143        /// they are written without digit grouping ("2026", not "2 026").144        public var yearLikeColumns: Set<String> {145            Set(columns.filter { c in146                if let t = c.type { return t == .year }               // the server said what the column is147                guard c.unit == .none, c.decimals == nil else { return false }148                let values = rows.compactMap { $0[c.key]?.doubleValue }149                return !values.isEmpty && values.allSatisfy { $0.rounded() == $0 && $0 >= 1800 && $0 <= 2200 }150            }.map(\.key))151        }152153        public func cell(_ row: VQJSONObject, _ column: Column, plainInteger: Bool = false, locale: VQNumberLocale = .frCA) -> (text: String, numeric: Bool) {154            switch row[column.key] {155            case .number(let n)? where (plainInteger || column.type == .year) && n.rounded() == n: return (String(Int(n)), true)156            case .number(let n)? where column.type == .integer && column.unit == .none: return (VQFormat.int(n, locale: locale), true)157            case .number(let n)? where column.unit == .currency || column.unit == .perShare:158                return (VQFormat.currency(n, currency(of: row, column) ?? "USD", decimals: column.decimals ?? 2, locale: locale), true)159            case .number(let n)? where column.unitName != nil && column.unit == .none:160                return (VQFormat.byUnitName(n, column.unitName, decimals: column.decimals, locale: locale), true)161            case .number(let n)?:162                if column.unit == .none, column.decimals == nil {163                    // an undeclared number: integers as integers, others with up to 4 significant decimals164                    return (n.rounded() == n && abs(n) < 1e15 ? VQFormat.int(n, locale: locale) : VQFormat.number(n, decimals: abs(n) >= 100 ? 2 : 4, locale: locale), true)165                }166                return (VQFormat.byUnit(n, column.unit, decimals: column.decimals, locale: locale), true)167            case .string(let s)?: return (s, false)168            case .bool(let b)?: return (b ? "✓" : "✗", false)169            case .null?, nil: return (VQFormat.nullText, column.unit != .none || column.decimals != nil)170            case .array(let a)?: return (a.compactMap(\.displayString).joined(separator: ", "), false)171            case .object(let o)?: return (VQJSON.object(o).text(), false)172            }173        }174    }175176    // MARK: charts177178    public struct Chart: Sendable, Equatable, Identifiable, VQJSONDecodable {179        public enum ChartType: String, Sendable, Hashable, CaseIterable { case line, area, bar, scatter, histogram, heatmap, surface, candles, payoff, fan }180        public enum AxisType: String, Sendable, Hashable, CaseIterable { case time, number, category }181        public var id: String182        public var title: String183        public var type: VQOpen<ChartType>184        public var x: XAxis185        public var y: YAxis186        public var series: [Series]187        /// Heatmaps and surfaces: `z[row][column]`, rows along `y`, columns along `x`; null = no value.188        public var matrix: Matrix?189        public var annotations: [Annotation]190        public var note: String?191        /// What the cells of a `matrix` are (heat maps, surfaces). Authoritative over `y.unit` when present;192        /// nil on results recorded before the server sent it (the cell unit is then `y.unit`).193        public var z: ZAxis?194195        public struct XAxis: Sendable, Equatable, VQJSONDecodable {196            public var label: String197            public var type: VQOpen<AxisType>198            /// Unit of a numeric x (`.none` when dimensionless or not stated).199            public var unit: VQValueUnit200            public var unitName: String?201            public var currency: String?202            public init(json j: VQJSON) { label = j.str("label"); type = j.open("type", .number); unit = VQValueUnit(j.optStr("unit")); unitName = j.optStr("unit"); currency = j.optStr("currency") }203        }204        public struct YAxis: Sendable, Equatable, VQJSONDecodable {205            public var label: String206            public var unit: VQValueUnit207            public var log: Bool208            public var unitName: String?209            public var currency: String?210            public init(json j: VQJSON) { label = j.str("label"); unit = VQValueUnit(j.optStr("unit")); log = j.flag("log"); unitName = j.optStr("unit"); currency = j.optStr("currency") }211        }212        public struct ZAxis: Sendable, Equatable, VQJSONDecodable {213            public var label: String214            public var unit: VQValueUnit215            public var unitName: String?216            public var currency: String?217            public init(json j: VQJSON) { label = j.str("label"); unit = VQValueUnit(j.optStr("unit")); unitName = j.optStr("unit"); currency = j.optStr("currency") }218        }219        /// Label, unit, raw unit name and currency of the matrix cells: `z` when the server sent it, else `y`.220        public var cellAxis: (label: String, unit: VQValueUnit, unitName: String?, currency: String?) {221            if let z { return (z.label, z.unit, z.unitName, z.currency) }222            return (y.label, y.unit, y.unitName, y.currency)223        }224        public struct Series: Sendable, Equatable, Identifiable, VQJSONDecodable {225            public enum Kind: String, Sendable, Hashable, CaseIterable { case observed, calculated, forecast }226            public enum Style: String, Sendable, Hashable, CaseIterable { case line, dashed, bar, points, band }227            public var name: String228            public var kind: VQOpen<Kind>229            /// ISO dates / datetimes on a time axis, numbers on a numeric axis, labels on a category axis.230            public var x: [VQJSON]231            public var y: [Double?]232            /// Interval bounds: a band (fan charts, `style: band`) or error bars (bars).233            public var lower: [Double?]?234            public var upper: [Double?]?235            /// nil = the chart type's own mark.236            public var style: VQOpen<Style>?237            /// Bands only (`lower`/`upper` drawn as a band): true = draw `y` as the centre line with the band,238            /// false = the band alone (`y` is a reference, the centre is another series). nil = not stated239            /// (older results, error bars).240            public var drawsCentreLine: Bool?241            /// `candles` charts: the four price arrays, each as long as `x` (`y` repeats `close`).242            public var open: [Double?]?, high: [Double?]?, low: [Double?]?, close: [Double?]?243            public var volume: [Double?]?244            public var id: String { name }245            public init(json j: VQJSON) {246                name = j.str("name"); kind = j.open("kind", .calculated); x = j.list("x"); y = j.list("y").map(\.doubleValue)247                lower = j["lower"]?.arrayValue?.map(\.doubleValue); upper = j["upper"]?.arrayValue?.map(\.doubleValue); style = j.optOpen("style")248                drawsCentreLine = j.optFlag("line")249                func prices(_ k: String) -> [Double?]? { j[k]?.arrayValue?.map(\.doubleValue) }250                open = prices("open"); high = prices("high"); low = prices("low"); close = prices("close"); volume = prices("volume")251            }252            public var hasInterval: Bool { lower != nil && upper != nil }253            /// The series carries the four OHLC arrays of a candles chart.254            public var hasCandles: Bool { open != nil && high != nil && low != nil && close != nil }255        }256        public struct Matrix: Sendable, Equatable, VQJSONDecodable {257            public var x: [VQJSON]258            public var y: [VQJSON]259            public var z: [[Double?]]260            public init(json j: VQJSON) { x = j.list("x"); y = j.list("y"); z = j.list("z").map { ($0.arrayValue ?? []).map(\.doubleValue) } }261            /// Smallest and largest finite value (nil for an empty matrix).262            public var range: ClosedRange<Double>? {263                let values = z.flatMap { $0.compactMap { $0 } }264                guard let lo = values.min(), let hi = values.max() else { return nil }265                return lo...hi266            }267        }268        public struct Annotation: Sendable, Equatable, VQJSONDecodable {269            public var x: VQJSON270            /// nil = a vertical rule at `x`.271            public var y: Double?272            public var text: String273            public init(json j: VQJSON) { x = j["x"] ?? .null; y = j.num("y"); text = j.str("text") }274        }275        public init(json j: VQJSON) {276            id = j.str("id"); title = j.str("title"); type = j.open("type", .line); x = XAxis(json: j["x"] ?? .null); y = YAxis(json: j["y"] ?? .null)277            series = j.models("series"); matrix = j.model("matrix"); annotations = j.models("annotations"); note = j.optStr("note"); z = j.model("z")278        }279    }280281    // MARK: diagnostics282283    public struct Diagnostic: Sendable, Equatable, Identifiable, VQJSONDecodable {284        public var name: String285        public var statistic: Double?286        public var pvalue: Double?287        /// Degrees of freedom — a number or a text such as "(2, 250)".288        public var df: String?289        public var conclusion: String290        /// true = passed, false = failed, nil = informational (no verdict).291        public var passed: Bool?292        public var id: String { name }293        public init(json j: VQJSON) {294            name = j.str("name"); statistic = j.num("statistic"); pvalue = j.num("pvalue"); df = j["df"]?.displayString295            conclusion = j.str("conclusion"); passed = j.optFlag("passed")296        }297    }298299    // MARK: provenance300301    public struct Provenance: Sendable, Equatable, VQJSONDecodable {302        public var data: [DataSource]303        /// The full specification the engine ran with (defaults written out).304        public var spec: VQJSONObject305        public var seed: Int?306        /// Library versions, sorted by name with `python` first.307        public var software: [Software]308        /// ISO datetime.309        public var computedAt: String?310        public var durationMs: Double?311        /// A Python snippet that reproduces the core computation.312        public var reproduce: String?313314        public struct Software: Sendable, Equatable, Identifiable {315            public var name: String316            public var version: String317            public var id: String { name }318        }319        public struct DataSource: Sendable, Equatable, Identifiable, VQJSONDecodable {320            public var symbol: String321            public var provider: String322            /// ISO datetime.323            public var retrievedAt: String?324            public var start: String?, end: String?325            public var observations: Int?326            public var frequency: String?327            /// `split_div` | `split` | `none`328            public var adjusted: String?329            public var currency: String?330            public var fallbackFrom: String?331            public var id: String { "\(symbol)|\(frequency ?? "")|\(start ?? "")" }332            public init(json j: VQJSON) {333                symbol = j.str("symbol"); provider = j.str("provider"); retrievedAt = j.optStr("retrievedAt"); start = j.optStr("start"); end = j.optStr("end")334                observations = j.int("observations"); frequency = j.optStr("frequency")335                adjusted = j.optStr("adjusted") ?? j.optFlag("adjusted").map { $0 ? "yes" : "none" }336                currency = j.optStr("currency"); fallbackFrom = j.optStr("fallbackFrom")337            }338        }339        public init(json j: VQJSON) {340            data = j.models("data"); spec = j.dict("spec"); seed = j.int("seed")341            software = j.dict("software").compactMap { k, v in v.displayString.map { Software(name: k, version: $0) } }342                .sorted { ($0.name == "python" ? "" : $0.name) < ($1.name == "python" ? "" : $1.name) }343            computedAt = j.optStr("computedAt"); durationMs = j.num("durationMs"); reproduce = j.optStr("reproduce")344        }345    }346}347
Files main
Menu

Theme