SPB Git

Repository Public

PortfolioStore.swift 15.2 KB 267 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Portfolio/PortfolioStore.swift3// Description: State of the Portfolios section: batched quotes of the data layer, writes of synced portfolio objects with undo, and the portfolio_lab / risk_lab runs of each portfolio (parameters mapped from its positions through the live engine catalogue).4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89extension AppEnvironment {10    var portfolios: PortfolioStore { store { PortfolioStore(app: self) } }11}1213/// One engine run on a portfolio.14struct PortfolioRun: Equatable {15    var job: VQQuantJob?16    var running = false17    var error: String?18    /// The result was found among the person's past jobs for exactly these holdings (not computed in this session).19    var restored = false20    var result: VQLabResult? { job?.labResult }21}2223enum PortfolioEngine: String, CaseIterable { case portfolioLab = "portfolio_lab", riskLab = "risk_lab" }2425@Observable final class PortfolioStore: SessionScoped {26    private(set) var quotes: [String: VQQuote] = [:]27    /// Symbols no provider quoted: shown as unavailable.28    private(set) var missing: Set<String> = []29    private(set) var quoteError: String?30    private(set) var loadingQuotes = false31    private(set) var quotesFetchedAt: Date?32    private(set) var catalog: VQLabCatalog?33    private(set) var runs: [String: PortfolioRun] = [:]34    /// Why Risk Lab did not start after Portfolio Lab (a sentence), per portfolio.35    private(set) var riskNote: [String: String] = [:]3637    @ObservationIgnored private unowned let app: AppEnvironment38    @ObservationIgnored private var restoredKeys = Set<String>()3940    init(app: AppEnvironment) { self.app = app }41    func reset() { quotes = [:]; missing = []; quoteError = nil; quotesFetchedAt = nil; runs = [:]; riskNote = [:]; restoredKeys = []; catalog = nil }4243    // MARK: quotes (≤ 60 symbols per request)4445    static let quoteBatch = 604647    func loadQuotes(_ symbols: [String]) async {48        let batches = Batching.chunks(symbols, size: Self.quoteBatch)49        guard !batches.isEmpty else { return }50        loadingQuotes = true; defer { loadingQuotes = false }51        var failure: String?52        for batch in batches {53            if Task.isCancelled { return }54            do {55                let r = try await app.vq.data.quotes(batch)56                for q in r.quotes { quotes[q.symbol] = q; missing.remove(q.symbol) }57                for m in r.missing { missing.insert(m); quotes[m] = nil }58                quotesFetchedAt = Date()59            } catch let e as VQError { failure = e.userMessage } catch is CancellationError { return } catch { failure = error.localizedDescription }60        }61        quoteError = failure62    }6364    // MARK: writes with undo6566    /// Saves the whole value of a portfolio (unknown keys included) through the sync engine and registers the67    /// inverse with the window's undo manager. Redo comes for free: undoing registers the opposite write.68    func write(_ new: VQPortfolio, id: String, action: String, undo: UndoManager?) {69        guard let coll = app.sync.active?.portfolios, let old = coll[id]?.data, old != new else { return }70        undo?.registerUndo(withTarget: self) { store in71            MainActor.assumeIsolated { store.write(old, id: id, action: action, undo: undo) }72        }73        undo?.setActionName(action)74        Task { await coll.save(new, id: id); await self.afterWrite(id, coll) }75    }7677    /// `main` is also what the agent, Risk Analytics and the 1.x routes read: they are refreshed once the server has it.78    private func afterWrite(_ id: String, _ coll: VQSyncedCollection<VQPortfolio>) async {79        if let e = coll.lastError { app.toasts.show(e.userMessage, error: true) }80        guard id == VQObjectID.mainPortfolio else { return }81        await app.sync.syncNow()82        await app.workspace.refresh()83    }8485    @discardableResult func create(_ p: VQPortfolio) async -> String? {86        guard let coll = app.sync.active?.portfolios else { return nil }87        let id = await coll.create(p)88        if let e = coll.lastError { app.toasts.show(e.userMessage, error: true); return nil }89        return id90    }9192    func delete(_ id: String) async {93        guard id != VQObjectID.mainPortfolio, let coll = app.sync.active?.portfolios else { return }94        await coll.delete(id)95        if let e = coll.lastError { app.toasts.show(e.userMessage, error: true) }96        for e in PortfolioEngine.allCases { runs[Self.key(id, e)] = nil }97    }9899    // MARK: analysis (portfolio_lab, then risk_lab with the weights it valued)100101    static func key(_ id: String, _ engine: PortfolioEngine) -> String { "\(id)|\(engine.rawValue)" }102    func run(_ id: String, _ engine: PortfolioEngine) -> PortfolioRun? { runs[Self.key(id, engine)] }103    func isRunning(_ id: String) -> Bool { PortfolioEngine.allCases.contains { runs[Self.key(id, $0)]?.running == true } }104105    func loadCatalog() async {106        guard catalog == nil else { return }107        catalog = try? await app.vq.lab.catalog()108    }109110    /// The choices of `portfolio_lab.objective` as the live catalogue lists them.111    var objectives: [String] { catalog?.tool(PortfolioEngine.portfolioLab.rawValue)?.params.first { $0.name == "objective" }?.choices ?? [] }112    var defaultObjective: String { catalog?.tool(PortfolioEngine.portfolioLab.rawValue)?.params.first { $0.name == "objective" }?.defaultValue?.stringValue ?? "min_variance" }113114    static func objectiveTitle(_ id: String) -> String {115        switch id {116        case "max_sharpe": "Maximum Sharpe"; case "min_variance": "Minimum variance"; case "risk_parity": "Risk parity"; case "hrp": "Hierarchical risk parity"117        case "max_diversification": "Maximum diversification"; case "equal_weight": "Equal weight"; case "target": "Target weights"; case "none": "No proposal"118        default: id.replacingOccurrences(of: "_", with: " ").capitalized119        }120    }121122    /// positions → `portfolio_lab` parameters. Only parameters the catalogue declares are sent; everything else keeps123    /// the engine's default.124    static func portfolioLabParams(_ p: VQPortfolio, objective: String?, tool: VQLabTool?) -> VQJSONObject {125        var out: VQJSONObject = [:]126        let declared = tool.map { Set($0.params.map(\.name)) }127        func put(_ k: String, _ v: VQJSON) { if declared?.contains(k) ?? true { out[k] = v } }128        put("positions", .array(p.positions.filter { !$0.symbol.isEmpty && $0.quantity != 0 }.map { pos in129            var o: VQJSONObject = ["symbol": .string(pos.symbol), "quantity": .number(pos.quantity)]130            if let c = pos.costBasis { o["costBasis"] = .number(c) }131            if let c = pos.currency, !c.isEmpty { o["currency"] = .string(c) }132            return .object(o)133        }))134        let cash = p.cash.filter { !$0.currency.isEmpty && $0.amount != 0 }135        if !cash.isEmpty { put("cash", .object(Dictionary(cash.map { ($0.currency, VQJSON.number($0.amount)) }, uniquingKeysWith: { a, b in .number((a.doubleValue ?? 0) + (b.doubleValue ?? 0)) }))) }136        put("base_currency", .string(p.baseCurrency))137        if let b = p.benchmark, !b.isEmpty { put("benchmark", .string(b)) }138        if let objective { put("objective", .string(objective)) }139        return out140    }141142    /// `risk_lab` parameters from the holdings table `portfolio_lab` valued in the base currency: symbols and their143    /// weights (the engine rescales them), limited to what the catalogue allows.144    static func riskLabParams(from lab: VQLabResult, held: Set<String>, tool: VQLabTool?) -> (params: VQJSONObject, note: String?)? {145        guard let holdings = lab.tables.first(where: { $0.id == "holdings" }) else { return nil }146        var pairs: [(String, Double)] = holdings.rows.compactMap { r in147            // the table also lists the cash balances ("Cash USD"): only the holdings are risk assets148            guard let s = r["symbol"]?.stringValue, held.contains(s), let w = r["weight"]?.doubleValue, w != 0 else { return nil }149            return (s, w)150        }151        guard !pairs.isEmpty else { return nil }152        let limit = tool?.params.first { $0.name == "symbols" }?.max.map { Int($0) } ?? 20153        var note: String?154        if pairs.count > limit {155            pairs = Array(pairs.sorted { abs($0.1) > abs($1.1) }.prefix(limit))156            note = "Risk Lab accepts \(limit) symbols: the \(limit) largest holdings are analysed, with their weights rescaled."157        }158        return (["symbols": VQJSON(pairs.map(\.0)), "weights": VQJSON(pairs.map(\.1))], note)159    }160161    /// The portfolio as the engines can take it: a symbol nobody quotes has no price history either and would fail162    /// the whole run, so it is left out — and the pane says which.163    func analysable(_ p: VQPortfolio) -> (portfolio: VQPortfolio, excluded: [String]) {164        let out = p.positions.filter { missing.contains($0.symbol) }.map(\.symbol)165        guard !out.isEmpty else { return (p, []) }166        var q = p; q.positions = p.positions.filter { !missing.contains($0.symbol) }167        return (q, out)168    }169170    func analyse(_ id: String, _ whole: VQPortfolio, objective: String) async {171        guard !isRunning(id) else { return }172        await loadCatalog()173        if whole.positions.contains(where: { quotes[$0.symbol] == nil && !missing.contains($0.symbol) }) { await loadQuotes(whole.positions.map(\.symbol)) }174        let portfolio = analysable(whole).portfolio175        let labKey = Self.key(id, .portfolioLab), riskKey = Self.key(id, .riskLab)176        runs[labKey] = PortfolioRun(running: true); runs[riskKey] = nil; riskNote[id] = nil177        let lab = await execute(labKey, tool: PortfolioEngine.portfolioLab.rawValue, params: Self.portfolioLabParams(portfolio, objective: objective, tool: catalog?.tool(PortfolioEngine.portfolioLab.rawValue)))178        guard let result = lab?.labResult, result.success else { return }179        guard let risk = Self.riskLabParams(from: result, held: Set(portfolio.positions.map(\.symbol)), tool: catalog?.tool(PortfolioEngine.riskLab.rawValue)) else {180            riskNote[id] = "Risk Lab was not run: Portfolio Lab priced no holding."; return181        }182        riskNote[id] = risk.note183        runs[riskKey] = PortfolioRun(running: true)184        _ = await execute(riskKey, tool: PortfolioEngine.riskLab.rawValue, params: risk.params)185    }186187    private func execute(_ key: String, tool: String, params: VQJSONObject) async -> VQQuantJob? {188        do {189            let job = try await app.vq.lab.run(tool: tool, params: params) { [weak self] state in190                Task { @MainActor in if self?.runs[key]?.running == true { self?.runs[key]?.job = state } }191            }192            runs[key] = PortfolioRun(job: job, running: false, error: job.labResult?.success == true ? nil : (job.failureMessage ?? job.labResult?.error ?? "The computation did not complete."))193            return job194        } catch let e as VQError {195            runs[key] = PortfolioRun(running: false, error: e.userMessage)196        } catch {197            runs[key] = PortfolioRun(running: false, error: error is CancellationError ? "Cancelled." : error.localizedDescription)198        }199        return nil200    }201202    func cancel(_ id: String) async {203        for e in PortfolioEngine.allCases { if let r = runs[Self.key(id, e)], r.running, let j = r.job { _ = try? await app.vq.lab.cancel(j.id) } }204    }205206    /// Looks among the person's finished jobs for an analysis of exactly these holdings, once per portfolio state,207    /// so that reopening the tab shows the last result instead of nothing. Nothing is computed.208    func restore(_ id: String, _ whole: VQPortfolio) async {209        if whole.positions.contains(where: { quotes[$0.symbol] == nil && !missing.contains($0.symbol) }) { await loadQuotes(whole.positions.map(\.symbol)) }210        let portfolio = analysable(whole).portfolio211        let wanted = Self.portfolioLabParams(portfolio, objective: nil, tool: nil)212        let stamp = id + "|" + VQJSON.object(wanted).text()213        guard run(id, .portfolioLab) == nil, restoredKeys.insert(stamp).inserted, wanted["positions"]?.arrayValue?.isEmpty == false else { return }214        guard let list = try? await app.vq.lab.jobs() else { restoredKeys.remove(stamp); return }215        func same(_ j: VQQuantJob) -> Bool {216            j.tool == PortfolioEngine.portfolioLab.rawValue && j.status == .done && j.params["positions"] == wanted["positions"]217                && (j.params["cash"] ?? .object([:])) == (wanted["cash"] ?? .object([:])) && j.params["base_currency"] == wanted["base_currency"]218        }219        guard let hit = list.jobs.first(where: same), let job = try? await app.vq.lab.job(hit.id), let result = job.labResult, result.success, run(id, .portfolioLab) == nil else { return }220        runs[Self.key(id, .portfolioLab)] = PortfolioRun(job: job, restored: true)221        guard let risk = Self.riskLabParams(from: result, held: Set(portfolio.positions.map(\.symbol)), tool: nil), let symbols = risk.params["symbols"] else { return }222        if let r = list.jobs.first(where: { $0.tool == PortfolioEngine.riskLab.rawValue && $0.status == .done && $0.params["symbols"] == symbols && ($0.startedAt ?? .distantPast) >= (hit.startedAt ?? .distantPast) }),223           let rj = try? await app.vq.lab.job(r.id), rj.labResult?.success == true, run(id, .riskLab) == nil {224            runs[Self.key(id, .riskLab)] = PortfolioRun(job: rj, restored: true)225        }226    }227228    // MARK: rebalancing proposal229230    struct Trade: Identifiable, Equatable {231        var symbol: String232        var current: Double?, target: Double?, change: Double?233        var action: String234        var units: Double?235        var tradeLocal: Double?236        var currency: String?237        var tradeBase: Double?238        var id: String { symbol }239    }240241    static func trades(_ lab: VQLabResult) -> (title: String, note: String?, trades: [Trade])? {242        guard let t = lab.tables.first(where: { $0.id == "rebalance" }) else { return nil }243        let rows = t.rows.compactMap { r -> Trade? in244            guard let s = r["symbol"]?.stringValue else { return nil }245            return Trade(symbol: s, current: r["current"]?.doubleValue, target: r["target"]?.doubleValue, change: r["change"]?.doubleValue, action: r["action"]?.stringValue ?? "",246                         units: r["units"]?.doubleValue, tradeLocal: r["tradeLocal"]?.doubleValue, currency: r["currency"]?.stringValue, tradeBase: r["tradeBase"]?.doubleValue)247        }248        return (t.title, t.note, rows)249    }250251    /// The portfolio the proposal leads to, as a NEW value: the original is not touched. Quantities change by the252    /// proposed units; every other key of each position (cost basis, notes, unknown keys) is carried over.253    static func proposalCopy(of p: VQPortfolio, trades: [Trade]) -> VQPortfolio {254        var copy = p255        copy.name = p.name + " (proposal)"256        let units = Dictionary(trades.compactMap { t in t.units.map { (t.symbol, $0) } }, uniquingKeysWith: { a, _ in a })257        let after = RebalanceMath.apply(units: units, to: p.positions.map { ($0.symbol, $0.quantity) })258        let bySymbol = Dictionary(p.positions.map { ($0.symbol, $0) }, uniquingKeysWith: { a, _ in a })259        copy.positions = after.map { s, q in260            var pos = bySymbol[s] ?? VQPortfolio.Position(symbol: s, quantity: q, currency: trades.first { $0.symbol == s }?.currency)261            pos.quantity = q262            return pos263        }264        return copy265    }266}267
Files main
Menu

Theme