SPB Git

Repository Public

PortfolioAnalysisPane.swift 15.2 KB 228 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Portfolio/PortfolioAnalysisPane.swift3// Description: Analysis of one portfolio by the server's engines: portfolio_lab on its positions, then risk_lab with the weights portfolio_lab valued, rendered by the shared lab renderer; the rebalancing is shown as a proposal that can only be applied to a copy.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89enum AnalysisTab: String, CaseIterable { case portfolio, risk, rebalance }1011struct PortfolioAnalysisPane: View {12    let app: AppEnvironment13    let model: WindowModel14    let id: String15    let portfolio: VQPortfolio16    @Binding var tab: AnalysisTab17    @State private var objective = ""1819    private var store: PortfolioStore { app.portfolios }20    private var lab: PortfolioRun? { store.run(id, .portfolioLab) }21    private var risk: PortfolioRun? { store.run(id, .riskLab) }22    private var running: Bool { store.isRunning(id) }23    private var stale: Bool {24        guard let j = lab?.job, lab?.running != true else { return false }25        return j.params["positions"] != PortfolioStore.portfolioLabParams(store.analysable(portfolio).portfolio, objective: nil, tool: nil)["positions"]26    }2728    var body: some View {29        VStack(alignment: .leading, spacing: 0) {30            controls31            Hairline()32            ScrollView {33                VStack(alignment: .leading, spacing: VQTokens.Space.s5) {34                    let excluded = store.analysable(portfolio).excluded35                    if !excluded.isEmpty {36                        Text("No provider quotes \(excluded.joined(separator: ", ")): left out of the analysis (the engines need a price history). Everything below is about the other \(portfolio.positions.count - excluded.count) positions.")37                            .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.warn).fixedSize(horizontal: false, vertical: true)38                            .accessibilityIdentifier("analysis.excluded")39                    }40                    switch tab {41                    case .portfolio: engine(lab, name: "Portfolio Lab", idle: "Valuation in \(portfolio.baseCurrency) with stated exchange rates, allocation, risk contributions, factor exposures, efficient frontier, scenarios and a Monte Carlo fan — computed by the server on these positions.")42                    case .risk: riskPane43                    case .rebalance: rebalance44                    }45                }46                .padding(.horizontal, VQTokens.Space.s6).padding(.vertical, VQTokens.Space.s5)47                .frame(maxWidth: .infinity, alignment: .leading)48            }49        }50        .task(id: id) {51            await store.loadCatalog()52            if objective.isEmpty { objective = store.defaultObjective }53            await store.restore(id, portfolio)54            // DEBUG launch argument -VQXRunAnalysis 1: visual checks of a computed analysis (engines cost no model usage)55            if app.options.extra["RunAnalysis"] == "1", lab == nil, !portfolio.positions.isEmpty { await store.analyse(id, portfolio, objective: objective) }56        }57    }5859    private var controls: some View {60        HStack(spacing: VQTokens.Space.s3) {61            VQSegmentedControl("Result", selection: $tab, options: [.init(.portfolio, "Portfolio Lab"), .init(.risk, "Risk Lab"), .init(.rebalance, "Rebalancing")])62                .accessibilityIdentifier("analysis.tabs")63            Spacer()64            if running {65                let p = (lab?.running == true ? lab : risk)?.job?.progress66                HStack(spacing: 6) {67                    if let p { ProgressView(value: min(1, max(0, p))).frame(width: 90) } else { ProgressView().controlSize(.small) }68                    Text(lab?.running == true ? "Portfolio Lab\(p.map { " · \(Int($0 * 100)) %" } ?? "…")" : "Risk Lab\(p.map { " · \(Int($0 * 100)) %" } ?? "…")")69                        .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text2).monospacedDigit()70                    Button("Cancel") { Task { await store.cancel(id) } }.controlSize(.small)71                }72                .accessibilityIdentifier("analysis.progress")73            } else {74                Picker("Proposal target", selection: $objective) {75                    ForEach(store.objectives.isEmpty ? [objective] : store.objectives, id: \.self) { Text(PortfolioStore.objectiveTitle($0)).tag($0) }76                }77                .controlSize(.small).fixedSize()78                .help("The target of the rebalancing proposal (a parameter of portfolio_lab)")79                Button(lab?.job == nil ? "Run Analysis" : "Run Again") { Task { await store.analyse(id, portfolio, objective: objective) } }80                    .buttonStyle(EmberButtonStyle())81                    .disabled(portfolio.positions.isEmpty || !app.connectivity.isOnline)82                    .accessibilityIdentifier("analysis.run")83            }84        }85        .padding(.horizontal, VQTokens.Space.s6).padding(.vertical, VQTokens.Space.s2)86    }8788    // MARK: engines8990    @ViewBuilder private func provenanceLine(_ run: PortfolioRun) -> some View {91        if let j = run.job, !run.running {92            HStack(spacing: VQTokens.Space.s2) {93                if run.restored { QuietChip(text: "Earlier run on these holdings", systemImage: "clock.arrow.circlepath") }94                if stale { QuietChip(text: "Positions changed since this run", systemImage: "exclamationmark.triangle", tint: VQTokens.Palette.warn) }95                Text("Computed \(VQFormat.dateTime(j.finishedAt ?? j.startedAt, language: .en))\(j.durationMs.map { " in \(VQFormat.duration(ms: $0, locale: app.numberLocale))" } ?? "")")96                    .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)97                Spacer()98                Button { model.openQuantJob(j.id) } label: { Label("Open in Quant Lab", systemImage: "arrow.up.right") }.controlSize(.small).buttonStyle(.borderless)99            }100        }101    }102103    @ViewBuilder private func engine(_ run: PortfolioRun?, name: String, idle: String) -> some View {104        if portfolio.positions.isEmpty {105            VQEmptyState(systemImage: "function", title: "Nothing to analyse", message: "Add positions in Holdings first.")106        } else if let run {107            if run.running {108                VStack(alignment: .leading, spacing: VQTokens.Space.s4) {109                    Text("\(name) is computing on the server…").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2)110                    VQSkeletonText(lines: 2); VQSkeletonChart(height: 200); VQSkeletonRows(rows: 5, columns: 5)111                }112            } else if let result = run.result, result.success {113                provenanceLine(run)114                LabResultView(result)115            } else {116                VQEmptyState(systemImage: "exclamationmark.triangle", title: "\(name) did not complete", message: run.error ?? run.result?.error ?? "The server returned no result.")117            }118        } else {119            VQEmptyState(systemImage: "function", title: name, message: idle) {120                Text("Engines run on the server and cost no model usage.").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)121            }122        }123    }124125    @ViewBuilder private var riskPane: some View {126        if let note = store.riskNote[id] { Text(note).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.warn) }127        if risk == nil, lab?.result?.success == true, !running {128            VQEmptyState(systemImage: "gauge.with.dots.needle.67percent", title: "Risk Lab", message: "Risk Lab runs after Portfolio Lab, with the weights it valued in \(portfolio.baseCurrency). Run the analysis again to compute it.")129        } else if risk == nil, lab?.running == true {130            Text("Waiting for Portfolio Lab: Risk Lab uses the weights it values in \(portfolio.baseCurrency).").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2)131            VQSkeletonRows(rows: 4, columns: 5)132        } else {133            if risk?.result?.success == true {134                Text("Weights: market values in \(portfolio.baseCurrency) from the Portfolio Lab run (cash excluded), held constant over the sample.")135                    .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)136            }137            engine(risk, name: "Risk Lab", idle: "Value-at-Risk and Expected Shortfall by six methods, backtests, drawdowns, stress replays and correlation dynamics for the weighted portfolio.")138        }139    }140141    // MARK: rebalancing proposal142143    @ViewBuilder private var rebalance: some View {144        if let result = lab?.result, result.success, let r = PortfolioStore.trades(result) {145            let locale = app.numberLocale146            let base = portfolio.baseCurrency147            VStack(alignment: .leading, spacing: VQTokens.Space.s3) {148                HStack(spacing: VQTokens.Space.s2) {149                    Image(systemName: "hand.raised").foregroundStyle(VQTokens.Palette.warn)150                    Text("Proposal — not an order. VQuant cannot place orders.").font(VQTokens.Typography.heading.font).foregroundStyle(VQTokens.Palette.text1)151                        .accessibilityIdentifier("rebalance.label")152                    Spacer()153                }154                .padding(VQTokens.Space.s3)155                .background(RoundedRectangle(cornerRadius: VQTokens.Radius.sm).fill(VQTokens.Palette.warn.opacity(0.10)))156                .overlay(RoundedRectangle(cornerRadius: VQTokens.Radius.sm).strokeBorder(VQTokens.Palette.warn.opacity(0.35), lineWidth: VQTokens.hairline))157                Text(r.title).font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1)158                if let run = lab { provenanceLine(run) }159                VStack(spacing: 0) {160                    HStack(spacing: 0) {161                        Overline("Holding").frame(width: 110, alignment: .leading)162                        th("Current"); th("Target"); th("Change"); Overline("Suggested").frame(width: 90, alignment: .center); th("Units"); th("Local amount"); Overline("Ccy").frame(width: 50, alignment: .center); th("In \(base)")163                    }164                    .padding(.vertical, 5)165                    Hairline(strong: true)166                    ForEach(r.trades) { t in167                        HStack(spacing: 0) {168                            Text(t.symbol).font(VQTokens.Typography.numMd.font).frame(width: 110, alignment: .leading)169                            td(VQFormat.percent(t.current, decimals: 1, locale: locale)); td(VQFormat.percent(t.target, decimals: 1, locale: locale))170                            td(VQFormat.percent(t.change, decimals: 1, signed: true, locale: locale), color: VQTokens.Palette.text2)171                            Text(t.action.isEmpty ? VQFormat.nullText : t.action.capitalized).font(VQTokens.Typography.caption.font.weight(.semibold))172                                .foregroundStyle(t.action == "buy" ? app.settings.upColor : t.action == "sell" ? app.settings.downColor : VQTokens.Palette.text3).frame(width: 90, alignment: .center)173                            td(VQFormat.number(t.units, decimals: 4, signed: true, locale: locale))174                            td(VQFormat.number(t.tradeLocal, decimals: 2, signed: true, locale: locale))175                            Text(t.currency ?? VQFormat.nullText).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text2).frame(width: 50, alignment: .center)176                            td(VQFormat.number(t.tradeBase, decimals: 2, signed: true, locale: locale))177                        }178                        .frame(height: 30)179                        .accessibilityElement(children: .combine)180                        .accessibilityIdentifier("rebalance.row.\(t.symbol)")181                        Hairline()182                    }183                }184                HStack(spacing: VQTokens.Space.s2) { VQKindBadge(.calculated); Text("Calculated by portfolio_lab from daily closes; weights are fractions of the portfolio value in \(base).").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }185                if let note = r.note { Text(note).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text2).fixedSize(horizontal: false, vertical: true) }186                ForEach(result.summary.filter { $0.label.lowercased().contains("rebalanc") }, id: \.label) { m in187                    HStack(spacing: 6) {188                        Text(m.label).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text2)189                        Text(m.formatted(locale: locale)).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text1)190                        if let n = m.note { Text(n).font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }191                    }192                }193                Hairline()194                HStack(alignment: .firstTextBaseline, spacing: VQTokens.Space.s3) {195                    Button { applyToCopy(r.trades) } label: { Label("Apply to a Copy", systemImage: "plus.square.on.square") }196                        .disabled(r.trades.allSatisfy { ($0.units ?? 0) == 0 } || stale)197                        .accessibilityIdentifier("rebalance.copy")198                    Text(stale ? "The positions changed since this proposal was computed: run the analysis again before applying it."199                               : "Creates a new portfolio “\(portfolio.name) (proposal)” with the proposed quantities. “\(portfolio.name)” is not changed, and nothing is bought or sold.")200                        .font(VQTokens.Typography.caption.font).foregroundStyle(stale ? VQTokens.Palette.warn : VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)201                }202            }203        } else if lab?.running == true {204            Text("Portfolio Lab is computing the proposal…").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2)205            VQSkeletonRows(rows: 4, columns: 6)206        } else if lab?.result?.success == true {207            VQEmptyState(systemImage: "arrow.left.arrow.right", title: "No proposal in this run", message: "The analysis was run with “No proposal” as its target. Choose a target and run it again.")208        } else {209            VQEmptyState(systemImage: "arrow.left.arrow.right", title: "Rebalancing proposal", message: "Run the analysis: Portfolio Lab suggests the trades that would move this portfolio toward the chosen target. It is a proposal — VQuant cannot place orders.")210        }211    }212213    private func th(_ t: String) -> some View { Overline(t).frame(maxWidth: .infinity, alignment: .trailing) }214    private func td(_ t: String, color: Color = VQTokens.Palette.text1) -> some View {215        Text(t).font(VQTokens.Typography.numSm.font).foregroundStyle(color).lineLimit(1).frame(maxWidth: .infinity, alignment: .trailing)216    }217218    private func applyToCopy(_ trades: [PortfolioStore.Trade]) {219        let copy = PortfolioStore.proposalCopy(of: portfolio, trades: trades)220        Task {221            if let new = await store.create(copy) {222                app.toasts.show("“\(copy.name)” created. The original portfolio is unchanged.")223                model.openPortfolio(new)224            }225        }226    }227}228
Files main
Menu

Theme