SPB Git

Repository Public

VQuantAPI.swift 16.1 KB 225 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Services/VQuantAPI.swift3// Description: One typed method per verified backend route (see docs/API_INVENTORY.md). No route is called that the server does not define.4import Foundation56/// Tabular datasets the backend proxies from the data provider, one row per period or event.7public enum Dataset: String, Sendable, CaseIterable, Identifiable, Codable {8    case income = "income-statement", balance = "balance-sheet", cashFlow = "cash-flow", keyMetrics = "key-metrics", ratios = "financial-ratios"9    case estimates = "analyst-estimates", priceTargets = "price-target", grades = "upgrades-downgrades", earnings = "earnings-surprises"10    case dividends = "dividend-history", holders = "institutional-holders", insiders = "insider-trading", news = "financial-news", esg = "esg-score"11    case dailyPrices = "historical-price"1213    public var id: String { rawValue }14    public var title: String {15        switch self {16        case .income: "Income statement"; case .balance: "Balance sheet"; case .cashFlow: "Cash flow"; case .keyMetrics: "Key metrics"; case .ratios: "Financial ratios"17        case .estimates: "Analyst estimates"; case .priceTargets: "Price targets"; case .grades: "Upgrades & downgrades"; case .earnings: "Earnings"18        case .dividends: "Dividends"; case .holders: "Institutional filings"; case .insiders: "Insider trading"; case .news: "News"; case .esg: "ESG scores"19        case .dailyPrices: "Daily prices"20        }21    }22    public var group: String {23        switch self {24        case .income, .balance, .cashFlow, .keyMetrics, .ratios: "Fundamentals"25        case .estimates, .priceTargets, .grades, .earnings: "Analysts"26        case .dividends, .holders, .insiders, .esg: "Ownership & events"27        case .news: "News"28        case .dailyPrices: "Prices"29        }30    }31    /// The server reads `period` (annual | quarter) for these.32    public var hasPeriod: Bool { [.income, .balance, .cashFlow, .keyMetrics, .ratios, .estimates].contains(self) }33    /// The server reads `limit` for these (its page size; there is no offset).34    public var hasLimit: Bool { [.income, .balance, .cashFlow, .keyMetrics, .ratios, .news, .insiders].contains(self) }35    public var defaultLimit: Int { switch self { case .news: 10; case .insiders: 20; default: 5 } }36}3738/// Limits of one analysis (CONTRACT §2.4). When absent the person's synced preference applies on the server.39public struct ChatBudget: Sendable, Equatable {40    public var maxCostUsd: Double?41    public var maxMinutes: Double?42    public init(maxCostUsd: Double? = nil, maxMinutes: Double? = nil) { self.maxCostUsd = maxCostUsd; self.maxMinutes = maxMinutes }43    public var isEmpty: Bool { maxCostUsd == nil && maxMinutes == nil }44}4546public struct ChatRequest: Sendable, Equatable {47    public var query: String48    public var sessionId: String?49    public var history: [(question: String, answer: String)]50    public var mode: ResearchMode51    /// Any selectable model id of the server registry, or `"auto"` (the server routes and says why).52    public var model: String53    public var imageBase64: String?54    public var imageMimeType: String?55    /// Backend 6: cost and time limits of this analysis.56    public var budget: ChatBudget?57    /// Backend 6: the research project this conversation is filed in.58    public var projectId: String?59    public init(query: String, sessionId: String?, history: [(question: String, answer: String)], mode: ResearchMode, model: String, imageBase64: String? = nil, imageMimeType: String? = nil,60                budget: ChatBudget? = nil, projectId: String? = nil) {61        self.query = query; self.sessionId = sessionId; self.history = history; self.mode = mode; self.model = model; self.imageBase64 = imageBase64; self.imageMimeType = imageMimeType62        self.budget = budget; self.projectId = projectId63    }64    public static func == (a: ChatRequest, b: ChatRequest) -> Bool {65        a.query == b.query && a.sessionId == b.sessionId && a.mode == b.mode && a.model == b.model && a.history.count == b.history.count && a.budget == b.budget && a.projectId == b.projectId66    }67    var body: JSONValue {68        var o: [String: JSONValue] = ["query": .string(query), "mode": .string(mode.rawValue), "model": .string(model),69                                      "history": .array(history.map { ["question": .string($0.question), "answer": .string($0.answer)] })]70        if let sessionId { o["sessionId"] = .string(sessionId) }71        if let imageBase64, let imageMimeType { o["imageData"] = .string(imageBase64); o["imageMimeType"] = .string(imageMimeType) }72        if let budget, !budget.isEmpty {73            var b: [String: JSONValue] = [:]74            if let c = budget.maxCostUsd, c > 0 { b["maxCostUsd"] = .number(min(c, 1000)) }75            if let m = budget.maxMinutes, m > 0 { b["maxMinutes"] = .number(min(m, 240)) }76            if !b.isEmpty { o["budget"] = .object(b) }77        }78        if let projectId, projectId.range(of: "^[A-Za-z0-9_-]{1,64}$", options: .regularExpression) != nil { o["projectId"] = .string(projectId) }79        return .object(o)80    }81}8283public struct ServiceHealth: Sendable, Equatable {84    public var name: String85    public var ok: Bool86    public var detail: String87    public var latencyMs: Double?88    public init(name: String, ok: Bool, detail: String, latencyMs: Double?) { self.name = name; self.ok = ok; self.detail = detail; self.latencyMs = latencyMs }89}9091public final class VQuantAPI: Sendable {92    public let client: APIClient93    public init(client: APIClient) { self.client = client }9495    private func seg(_ s: String) -> String { APIClient.segment(s) }9697    // MARK: Health9899    public func health() async throws -> (uptime: Int, latencyMs: Double) {100        let t0 = ContinuousClock.now101        let j = try await client.json(.get, "/api/health", authenticated: false)102        let d = ContinuousClock.now - t0103        return (j["uptime"]?.intValue ?? 0, Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15)104    }105106    // MARK: Market data (FMP proxy)107108    public func indices() async throws -> [Quote] { try await client.decode([Quote].self, .get, "/api/fmp/indices") }109    public func movers(_ m: Mover) async throws -> [Quote] { try await client.decode([Quote].self, .get, "/api/fmp/\(m.rawValue)") }110    public func marketHours() async throws -> [ExchangeHours] { try await client.decode([ExchangeHours].self, .get, "/api/fmp/market-hours") }111    public func search(_ q: String, limit: Int = 12) async throws -> [SymbolMatch] { try await client.decode([SymbolMatch].self, .get, "/api/fmp/search", query: ["q": q, "limit": String(limit)]) }112113    /// The quote of a symbol, or nil when the provider has none (unknown ticker): absence is reported, not papered over.114    public func quote(_ symbol: String) async throws -> Quote? { try await client.decode([Quote].self, .get, "/api/fmp/quote/\(seg(symbol))").first }115    public func profile(_ symbol: String) async throws -> CompanyProfile? { try await client.decode([CompanyProfile].self, .get, "/api/fmp/company-profile/\(seg(symbol))").first }116117    /// Daily bars between two dates (inclusive), ascending.118    public func dailyBars(_ symbol: String, from: String, to: String) async throws -> (bars: [Bar], dropped: Int) {119        let j = try await client.json(.get, "/api/fmp/chart/full/\(seg(symbol))", query: ["from": from, "to": to])120        return BarParser.bars(j.arrayValue ?? [])121    }122123    public func intradayBars(_ symbol: String, interval: BarInterval, from: String, to: String) async throws -> (bars: [Bar], dropped: Int) {124        precondition(interval.isIntraday)125        let j = try await client.json(.get, "/api/fmp/chart/intraday/\(seg(symbol))", query: ["interval": interval.rawValue, "from": from, "to": to])126        return BarParser.bars(j.arrayValue ?? [])127    }128129    /// Rows of a dataset exactly as the provider returns them. `limit` is the server's page size where it supports one.130    public func dataset(_ d: Dataset, symbol: String, quarterly: Bool = false, limit: Int? = nil) async throws -> [JSONValue] {131        var q: [String: String?] = [:]132        if d.hasPeriod { q["period"] = quarterly ? "quarter" : "annual" }133        if d.hasLimit { q["limit"] = String(limit ?? d.defaultLimit) }134        let j = try await client.json(.get, "/api/fmp/\(d.rawValue)/\(seg(symbol))", query: q)135        if d == .dailyPrices { return j["historical"]?.arrayValue ?? [] }136        return j.arrayValue ?? []137    }138139    // MARK: Conversations140141    public func sessions(search: String? = nil) async throws -> [SessionSummary] {142        try await client.decode([SessionSummary].self, .get, "/api/sessions", query: ["q": search.flatMap { $0.isEmpty ? nil : $0 }])143    }144    public func conversation(_ id: String) async throws -> Conversation { try await client.decode(Conversation.self, .get, "/api/sessions/\(seg(id))") }145    public func renameSession(_ id: String, title: String) async throws { try await client.data(.patch, "/api/sessions/\(seg(id))", body: ["title": .string(title)]) }146    public func pinSession(_ id: String, pinned: Bool) async throws { try await client.data(.patch, "/api/sessions/\(seg(id))", body: ["pinned": .bool(pinned)]) }147    public func deleteSession(_ id: String) async throws { try await client.data(.delete, "/api/sessions/\(seg(id))") }148149    // MARK: Analyses (server jobs)150151    public func generations() async throws -> GenerationList { try await client.decode(GenerationList.self, .get, "/api/generations") }152    public func cancelGeneration(_ id: String) async throws { try await client.data(.post, "/api/generations/\(seg(id))/cancel") }153154    /// Starts an analysis. The server creates the job and this request becomes its first viewer.155    public func startAnalysis(_ r: ChatRequest) async throws -> AsyncThrowingStream<String, Error> { try await client.lines(.post, "/api/chat", body: r.body) }156    /// Watches a job again from event `from` (replay, then live).157    public func watchGeneration(_ id: String, from: Int) async throws -> AsyncThrowingStream<String, Error> {158        try await client.lines(.get, "/api/generations/\(seg(id))/stream", query: ["from": String(from)])159    }160161    // MARK: Workspace (memory, portfolio, watches)162163    public func workspace() async throws -> Workspace { try await client.decode(Workspace.self, .get, "/api/workspace") }164    public func addMemory(content: String, category: String) async throws -> Memory { try await client.decode(Memory.self, .post, "/api/workspace/memories", body: ["content": .string(content), "category": .string(category)]) }165    public func deleteMemory(_ id: String) async throws { try await client.data(.delete, "/api/workspace/memories/\(seg(id))") }166    public func savePosition(symbol: String, quantity: Double, costBasis: Double?, note: String?) async throws -> Position {167        var b: [String: JSONValue] = ["quantity": .number(quantity)]168        b["costBasis"] = costBasis.map(JSONValue.number) ?? .null169        b["note"] = note.map(JSONValue.string) ?? .null170        return try await client.decode(Position.self, .put, "/api/workspace/portfolio/\(seg(symbol))", body: .object(b))171    }172    public func deletePosition(_ symbol: String) async throws { try await client.data(.delete, "/api/workspace/portfolio/\(seg(symbol))") }173    public func createWatch(title: String, prompt: String, time: String, days: String, deep: Bool, model: String) async throws -> Watch {174        try await client.decode(Watch.self, .post, "/api/workspace/watches", body: ["title": .string(title), "prompt": .string(prompt), "time": .string(time), "days": .string(days), "deep": .bool(deep), "model": .string(model)])175    }176    public func updateWatch(_ id: String, _ patch: [String: JSONValue]) async throws -> Watch { try await client.decode(Watch.self, .patch, "/api/workspace/watches/\(seg(id))", body: .object(patch)) }177    public func deleteWatch(_ id: String) async throws { try await client.data(.delete, "/api/workspace/watches/\(seg(id))") }178    public func runWatch(_ id: String) async throws { try await client.data(.post, "/api/workspace/watches/\(seg(id))/run") }179180    // MARK: Quantitative computations181182    public func quantCatalogue() async throws -> QuantCatalogue { try await client.decode(QuantCatalogue.self, .get, "/api/quant/tools") }183    public func quantJobs() async throws -> QuantJobList { try await client.decode(QuantJobList.self, .get, "/api/quant/jobs") }184    public func quantJob(_ id: String) async throws -> QuantJob { try await client.decode(QuantJobEnvelope.self, .get, "/api/quant/jobs/\(seg(id))").job }185    public func submitQuantJob(tool: String, params: [String: JSONValue], projectId: String? = nil) async throws -> QuantJob {186        var body: [String: JSONValue] = ["tool": .string(tool), "params": .object(params)]187        if let projectId { body["projectId"] = .string(projectId) }188        return try await client.decode(QuantJobEnvelope.self, .post, "/api/quant/jobs", body: .object(body)).job189    }190    /// Stops a running lab job (backend 6). A legacy tool cannot be stopped; a finished job says with which status it ended.191    public func cancelQuantJob(_ id: String) async throws -> QuantCancelOutcome {192        do { return .cancelled(try await client.decode(QuantJobEnvelope.self, .post, "/api/quant/jobs/\(seg(id))/cancel").job) }193        catch let e as APIError where e.kind == .conflict { return e.message == "not_cancellable" ? .notCancellable : .notRunning }194    }195    public func deleteQuantJob(_ id: String) async throws { try await client.data(.delete, "/api/quant/jobs/\(seg(id))") }196197    // MARK: Documents198199    public func sharedReports() async throws -> [SharedReportSummary] { try await client.decode([SharedReportSummary].self, .get, "/api/shared-reports") }200    public func sharedReport(_ id: String) async throws -> SharedReport { try await client.decode(SharedReport.self, .get, "/api/share/\(seg(id))") }201    public func share(question: String, answer: String, sources: [WebSource], figures: [FigureBatch]) async throws -> String {202        let fig: JSONValue = .array(figures.map { ["figures": .array($0.figureUrls.map(JSONValue.string)), "figureUrls": .array($0.figureUrls.map(JSONValue.string)), "description": $0.description.map(JSONValue.string) ?? .null] })203        let src: JSONValue = .array(sources.map { ["title": .string($0.title), "url": .string($0.url)] })204        let j = try await client.json(.post, "/api/share", body: ["question": .string(question), "answer": .string(answer), "sources": src, "customPythonFigures": fig])205        guard let id = j["shareId"]?.stringValue else { throw APIError(.decoding, "The server did not return a share identifier.") }206        return id207    }208    /// The server renders the report (PDF by Puppeteer, DOCX by Pandoc) and returns the file.209    public func renderPDF(question: String, answer: String) async throws -> Data { try await client.data(.post, "/api/generate-pdf", body: ["question": .string(question), "answer": .string(answer)], accept: "application/pdf") }210    public func renderDOCX(question: String, answer: String) async throws -> Data { try await client.data(.post, "/api/generate-docx", body: ["question": .string(question), "answer": .string(answer)], accept: "*/*") }211    public func renderSlides(question: String, answer: String, author: String, company: String, figureUrls: [String]) async throws -> Data {212        try await client.data(.post, "/api/convert-to-slides", body: ["question": .string(question), "answer": .string(answer), "author": .string(author), "company": .string(company), "figureUrls": .array(figureUrls.map(JSONValue.string))], accept: "application/pdf")213    }214    /// A figure (`/figures/…`, `/plots/…`) or a generated file (`/api/download/…`) of the signed-in person.215    public func asset(path: String) async throws -> Data {216        guard path.hasPrefix("/figures/") || path.hasPrefix("/plots/") || path.hasPrefix("/api/download/") else { throw APIError(.rejected, "Not a server asset path.") }217        guard path.range(of: "^/[A-Za-z0-9/._-]+$", options: .regularExpression) != nil, !path.contains("..") else { throw APIError(.rejected, "Not a server asset path.") }218        return try await client.data(.get, path, accept: "*/*")219    }220221    // MARK: Usage222223    public func usage() async throws -> UsageStats { try await client.decode(UsageStats.self, .get, "/api/analytics/real-time-stats") }224}225
Files main
Menu

Theme