SPB Git

Repository Public

QuantResult.swift 5.3 KB 112 lines swift

1//2//  VQuant iOS3//  File: Core/Quant/QuantResult.swift4//  Description: Turns the JSON result of a server engine into displayable sections without knowing each engine:5//               scalars become rows, {dates, values} becomes a series, an object of homogeneous objects becomes a table.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213enum QuantResult {14    struct Row: Equatable, Sendable, Identifiable { var key: String; var value: JSONValue; var id: String { key } }15    struct Point: Equatable, Sendable, Identifiable { var date: Date; var value: Double; var id: Date { date } }16    struct Table: Equatable, Sendable { var columns: [String]; var rows: [[String]] }1718    enum Body: Equatable, Sendable {19        case values([Row])20        case series([Point])21        case table(Table)22        case notes([String])23    }24    struct Section: Equatable, Sendable, Identifiable {25        var title: String26        var body: Body27        var id: String { title }28    }2930    /// `{dates: [...], values: [...]}` of equal lengths.31    static func series(_ v: JSONValue) -> [Point]? {32        guard let dates = v["dates"]?.arrayValue, let values = v["values"]?.arrayValue, !dates.isEmpty, dates.count == values.count else { return nil }33        let pts = zip(dates, values).compactMap { d, x -> Point? in34            guard let s = d.stringValue, let date = MarketDate.parse(s), let y = x.doubleValue else { return nil }35            return Point(date: date, value: y)36        }37        return pts.count == dates.count ? pts : nil38    }3940    static func sections(_ result: JSONValue) -> [Section] {41        guard let top = result.objectValue else { return [Section(title: "result", body: .values([Row(key: "value", value: result)]))] }42        var out: [Section] = []43        var loose: [Row] = []44        for key in top.keys.sorted(by: order) where key != "success" {45            let v = top[key]!46            if let s = series(v) { out.append(Section(title: key, body: .series(s))); continue }47            switch v {48            case .object(let o):49                if let t = table(o) { out.append(Section(title: key, body: .table(t))); continue }50                var rows: [Row] = []; var notes: [String] = []51                for k in o.keys.sorted() {52                    let x = o[k]!53                    if let s = series(x) { out.append(Section(title: "\(key).\(k)", body: .series(s))) }54                    else if case .array(let a) = x, a.allSatisfy({ $0.stringValue != nil }), !a.isEmpty { notes += a.compactMap(\.stringValue) }55                    else if case .object(let inner) = x { rows += inner.keys.sorted().map { Row(key: "\(k).\($0)", value: inner[$0]!) } }56                    else { rows.append(Row(key: k, value: x)) }57                }58                if !rows.isEmpty { out.append(Section(title: key, body: .values(rows))) }59                if !notes.isEmpty { out.append(Section(title: "\(key).notes", body: .notes(notes))) }60            case .array(let a) where !a.isEmpty && a.allSatisfy({ $0.stringValue != nil }):61                out.append(Section(title: key, body: .notes(a.compactMap(\.stringValue))))62            default:63                loose.append(Row(key: key, value: v))64            }65        }66        if !loose.isEmpty { out.insert(Section(title: "summary", body: .values(loose)), at: 0) }67        return out68    }6970    /// An object whose values are all objects with scalar leaves (one level of nesting flattened): one row per key.71    private static func table(_ o: [String: JSONValue]) -> Table? {72        guard o.count >= 2 else { return nil }73        var flat: [(String, [String: JSONValue])] = []74        for k in o.keys.sorted() {75            guard case .object(let inner) = o[k]! else { return nil }76            var cells: [String: JSONValue] = [:]77            for (ik, iv) in inner {78                if case .object(let deep) = iv { for (dk, dv) in deep { cells["\(ik).\(dk)"] = dv } } else { cells[ik] = iv }79            }80            flat.append((k, cells))81        }82        let columns = Set(flat.flatMap { $0.1.keys }).sorted()83        guard !columns.isEmpty, columns.count <= 24 else { return nil }84        return Table(columns: [""] + columns, rows: flat.map { name, cells in [name] + columns.map { cells[$0].map(format) ?? "—" } })85    }8687    static func format(_ v: JSONValue) -> String {88        switch v {89        case .null: return "—"90        case .bool(let b): return b ? "oui" : "non"91        case .string(let s): return s92        case .number(let n):93            if n == n.rounded(), abs(n) < 1e12 { return String(Int64(n)) }94            let digits = abs(n) >= 100 ? 2 : 495            return n.formatted(.number.precision(.fractionLength(0...digits)).locale(Locale(identifier: "fr_CA")))96        case .array(let a): return a.map(format).joined(separator: ", ")97        case .object: return v.prettyPrinted(limit: 400)98        }99    }100101    /// Sections in a stable, sensible order: identification first, interpretation last.102    private static func order(_ a: String, _ b: String) -> Bool {103        func rank(_ k: String) -> Int {104            if ["symbol", "symbols", "benchmark"].contains(k) { return 0 }105            if k.contains("specification") || k == "parameters" { return 1 }106            if k.contains("interpretation") { return 9 }107            return 5108        }109        return rank(a) == rank(b) ? a < b : rank(a) < rank(b)110    }111}112
Files main
Menu

Theme