SPB Git

Repository Public

Quant.swift 8.8 KB 172 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Models/Quant.swift3// Description: Quantitative computation jobs run by the server's Python engines: tool catalogue, parameters, job records.4import Foundation56public struct QuantParam: Sendable, Equatable, Codable, Identifiable {7    public var name: String8    /// symbol | symbols | int | number | numbers | choice | bool — and, for the lab engines of backend 6, date | text | json | group.9    public var type: String10    public var label: String11    public var required: Bool?12    public var `default`: JSONValue?13    public var min: Double?14    public var max: Double?15    public var choices: [String]?16    // backend 6 (all optional: absent for the six legacy tools)17    public var group: String?18    public var help: String?19    public var schemaHint: String?20    public var id: String { name }21    public var isRequired: Bool { required ?? false }22}2324public struct QuantTool: Sendable, Equatable, Codable, Identifiable {25    public var id: String26    public var title: String27    public var summary: String28    public var params: [QuantParam]29    // backend 6: volatility | risk | econometrics | options | backtest | portfolio | simulation, the engine version, "legacy" | "lab/1"30    public var category: String?31    public var version: String?32    public var resultSchema: String?33    /// A lab engine: its result follows the generic `lab/1` schema (rendered by the shared kit), not a tool-specific shape.34    public var isLab: Bool { resultSchema?.hasPrefix("lab/") ?? false }35}3637public struct QuantCatalogue: Sendable, Equatable, Codable {38    public var tools: [QuantTool]39    public var maxRunning: Int40    /// backend 6: engines the server could not offer, with the reason.41    public var unavailable: [String: String]?42}4344public struct QuantJob: Sendable, Equatable, Codable, Identifiable {45    /// `cancelled` exists since backend 6 (a 2.x client header receives it). A status this version does not know is46    /// read as `interrupted` — finished without a result — instead of failing the whole list.47    public enum Status: String, Sendable, Codable {48        case running, done, error, interrupted, cancelled49        public init(from decoder: Decoder) throws { self = Status(rawValue: try decoder.singleValueContainer().decode(String.self)) ?? .interrupted }50    }51    public var id: String52    public var tool: String53    public var params: [String: JSONValue]54    public var status: Status55    public var startedAt: Double56    public var finishedAt: Double?57    public var error: String?58    /// The Python source the server ran (present on the detail call).59    public var code: String?60    /// The engine's result, as produced (present on the detail call of a finished job).61    public var result: JSONValue?62    // backend 6 (optional: absent from 1.x payloads and from this Mac's older cache files)63    /// 0–1 while a lab engine reports; nil for legacy tools.64    public var progress: Double?65    public var engineVersion: String?66    public var durationMs: Double?67    public var projectId: String?68    public var cancellable: Bool?6970    public var started: Date { Date(timeIntervalSince1970: startedAt / 1000) }71    public var finished: Date? { finishedAt.map { Date(timeIntervalSince1970: $0 / 1000) } }72    public var duration: TimeInterval? { finishedAt.map { ($0 - startedAt) / 1000 } }73    /// "AAPL" or "AAPL, MSFT, NVDA": the subject of the job, for lists.74    public var subject: String {75        if let s = params["symbol"]?.stringValue { return s }76        if let a = params["symbols"]?.arrayValue { return a.compactMap(\.stringValue).joined(separator: ", ") }77        return ""78    }79    /// Parameters in a stable, readable form: the provenance line shown with every result.80    public var paramSummary: String {81        params.keys.sorted().map { k in82            let v = params[k]!83            let text: String84            switch v {85            case .string(let s): text = s86            case .bool(let b): text = b ? "yes" : "no"87            case .number(let n): text = n.rounded() == n && abs(n) < 1e12 ? String(Int(n)) : String(n)88            case .array(let a) where a.contains(where: { $0.objectValue != nil || $0.arrayValue != nil }): text = "\(a.count) item\(a.count == 1 ? "" : "s")"89            case .array(let a): text = a.map { $0.stringValue ?? $0.doubleValue.map { String($0) } ?? "" }.joined(separator: ", ")90            case .object(let o): text = "{\(o.keys.sorted().joined(separator: ", "))}"91            default: text = ""92            }93            return "\(k) = \(text)"94        }.joined(separator: " · ")95    }96}9798public struct QuantJobList: Sendable, Equatable, Codable {99    public var jobs: [QuantJob]100    public var running: Int101}102103struct QuantJobEnvelope: Codable, Sendable { var job: QuantJob }104105/// Answer of the cancel route: 200 with the job, 409 `not_cancellable` (legacy tool) or 409 `not_running`.106public enum QuantCancelOutcome: Sendable, Equatable {107    case cancelled(QuantJob)108    case notCancellable109    case notRunning110}111112/// Client-side check of a parameter form against the server's catalogue, so an obviously invalid request is caught113/// before it is sent. The server validates again and is the authority.114public enum QuantForm {115    public static func build(tool: QuantTool, values: [String: String], flags: [String: Bool]) -> Result<[String: JSONValue], FormError> {116        var out: [String: JSONValue] = [:]117        for p in tool.params {118            if p.type == "bool" { out[p.name] = .bool(flags[p.name] ?? p.default?.boolValue ?? false); continue }119            let raw = (values[p.name] ?? "").trimmingCharacters(in: .whitespacesAndNewlines)120            if raw.isEmpty {121                if p.isRequired { return .failure(FormError("\(p.label) is required.")) }122                continue   // the server applies and records its default123            }124            switch p.type {125            case "symbol": out[p.name] = .string(raw.uppercased())126            case "symbols":127                let list = raw.uppercased().split(whereSeparator: { " ,;\n\t".contains($0) }).map(String.init)128                let distinct = Array(NSOrderedSet(array: list)) as? [String] ?? list129                if let mn = p.min, Double(distinct.count) < mn { return .failure(FormError("\(p.label): at least \(Int(mn)) symbols.")) }130                if let mx = p.max, Double(distinct.count) > mx { return .failure(FormError("\(p.label): at most \(Int(mx)) symbols.")) }131                out[p.name] = .array(distinct.map(JSONValue.string))132            case "int", "number":133                guard let n = Double(raw.replacingOccurrences(of: ",", with: ".")), n.isFinite else { return .failure(FormError("\(p.label): a number is expected.")) }134                if p.type == "int", n.rounded() != n { return .failure(FormError("\(p.label): a whole number is expected.")) }135                if let mn = p.min, n < mn { return .failure(FormError("\(p.label): must be at least \(fmt(mn)).")) }136                if let mx = p.max, n > mx { return .failure(FormError("\(p.label): must be at most \(fmt(mx)).")) }137                out[p.name] = .number(n)138            case "numbers":139                var list: [JSONValue] = []140                for part in raw.split(whereSeparator: { " ,;\n\t".contains($0) }) {141                    guard let n = Double(part), n.isFinite else { return .failure(FormError("\(p.label): numbers separated by commas are expected.")) }142                    if let mn = p.min, n < mn { return .failure(FormError("\(p.label): each value must be at least \(fmt(mn)).")) }143                    if let mx = p.max, n > mx { return .failure(FormError("\(p.label): each value must be at most \(fmt(mx)).")) }144                    list.append(.number(n))145                }146                out[p.name] = .array(list)147            case "choice":148                guard p.choices?.contains(raw) ?? true else { return .failure(FormError("\(p.label): pick one of the listed values.")) }149                out[p.name] = .string(raw)150            default: out[p.name] = .string(raw)151            }152        }153        return .success(out)154    }155    public struct FormError: Error, Sendable, Equatable, LocalizedError {156        public let message: String157        init(_ m: String) { message = m }158        public var errorDescription: String? { message }159    }160    public static func fmt(_ n: Double) -> String { n.rounded() == n && abs(n) < 1e12 ? String(Int(n)) : String(n) }161    /// The text shown in a field for a default value.162    public static func placeholder(_ p: QuantParam) -> String {163        guard let d = p.default else { return p.isRequired ? "required" : "optional" }164        switch d {165        case .string(let s): return s166        case .number(let n): return fmt(n)167        case .array(let a): return a.compactMap { $0.doubleValue.map(fmt) ?? $0.stringValue }.joined(separator: ", ")168        default: return ""169        }170    }171}172
Files main
Menu

Theme