Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Portfolio/PortfolioViews.swift3// Description: Risk Analytics of the main portfolio (statistics computed from daily closes, plus the server's risk engines). The Portfolios section itself is in PortfoliosView.swift and its panes.4import Charts5import SwiftUI6import UniformTypeIdentifiers7import VQuantCore89// MARK: - Risk Analytics1011/// Statistics of the recorded holdings. Two kinds of numbers appear here and are labelled as such: descriptive12/// statistics computed on this Mac from daily closes the server returned, and results of the server's risk engines.13struct RiskView: View {14 let app: AppEnvironment15 let model: WindowModel16 @State private var series: [(symbol: String, bars: [Bar])] = []17 @State private var missing: [String] = []18 @State private var loading = false19 @State private var fromCache = false20 @State private var years = 12122 var body: some View {23 let positions = app.workspace.positions24 ScrollView {25 VStack(alignment: .leading, spacing: 14) {26 HStack {27 Picker("History", selection: $years) { Text("1 year").tag(1); Text("2 years").tag(2); Text("5 years").tag(5) }.pickerStyle(.segmented).labelsHidden().fixedSize()28 if loading { ProgressView().controlSize(.small) }29 if fromCache { FreshnessBadge(freshness: .cached(fetched: Date()), compact: true) }30 Spacer()31 Menu {32 ForEach(positions) { p in Button("Value at Risk · \(p.symbol)") { launch("var", ["symbol": .string(p.symbol)]) } }33 Divider()34 ForEach(positions) { p in Button("Risk metrics · \(p.symbol)") { launch("risk_metrics", ["symbol": .string(p.symbol)]) } }35 if positions.count >= 2 { Divider(); Button("Optimise the holdings") { launch("portfolio_optimization", ["symbols": .array(positions.prefix(30).map { .string($0.symbol) })]) } }36 } label: { Label("Run a Server Engine", systemImage: "function") }.fixedSize().disabled(positions.isEmpty || !app.connectivity.isOnline)37 }38 if positions.isEmpty {39 EmptyState(symbol: "gauge.with.dots.needle.67percent", title: "No holdings to analyse", detail: "Risk Analytics works on the positions recorded in Portfolio.").frame(height: 300)40 } else {41 if !missing.isEmpty { Text("No daily history for \(missing.joined(separator: ", ")): left out.").font(.caption).foregroundStyle(.orange) }42 let aligned = SeriesStats.alignedReturns(series)43 let symbols = series.map(\.symbol)44 if aligned.dates.count > 20 {45 Text("Descriptive statistics below are computed on this Mac from \(aligned.dates.count) common daily returns (closes from the server, \(Fmt.marketDate(aligned.dates.first!, intraday: false)) → \(Fmt.marketDate(aligned.dates.last!, intraday: false))). They describe the past; they are not model estimates.")46 .font(.caption).foregroundStyle(.secondary)47 Panel("Per holding — annualised from daily returns (×252, ×√252)") {48 Grid(alignment: .trailing, horizontalSpacing: 18, verticalSpacing: 4) {49 GridRow { Text("").gridColumnAlignment(.leading); Text("Return"); Text("Volatility"); Text("Max drawdown"); Text("Worst day"); Text("Best day") }.font(.caption).foregroundStyle(.secondary)50 ForEach(series, id: \.symbol) { s in51 let r = aligned.returns[s.symbol] ?? []52 let dd = SeriesStats.drawdown(s.bars.map(\.close)).min()53 GridRow {54 Text(s.symbol).font(.body.monospaced())55 Text(Fmt.percent(SeriesStats.mean(r).map { $0 * 252 * 100 })); Text(Fmt.plainPercent(SeriesStats.stdev(r).map { $0 * 252.0.squareRoot() * 100 }))56 Text(Fmt.plainPercent(dd)).foregroundStyle(Palette.red); Text(Fmt.percent(r.min().map { $0 * 100 })); Text(Fmt.percent(r.max().map { $0 * 100 }))57 }.monospacedDigit()58 }59 }60 }61 HStack(alignment: .top, spacing: 14) {62 if symbols.count >= 2 {63 Panel("Correlation of daily returns") { CorrelationHeatmap(symbols: symbols) { a, b in a == b ? 1 : SeriesStats.correlation(aligned.returns[a] ?? [], aligned.returns[b] ?? []) } }64 }65 weighted(aligned: aligned, positions: positions)66 }67 } else if !loading {68 Text("Not enough common history across the holdings to compute statistics.").font(.callout).foregroundStyle(.secondary)69 }70 recentJobs71 }72 }73 .padding(16)74 }75 .task(id: "\(positions.map(\.symbol).joined(separator: ","))|\(years)") { await load(positions.map(\.symbol)) }76 .onAppear { app.market.watch(positions.map(\.symbol)) }77 .onDisappear { app.market.unwatch(positions.map(\.symbol)) }78 .onChange(of: positions.map(\.symbol)) { old, new in app.market.unwatch(old); app.market.watch(new) }79 }8081 /// The portfolio's own daily returns with today's weights held constant (a stated simplification), and their drawdown.82 @ViewBuilder private func weighted(aligned: (dates: [Date], returns: [String: [Double]]), positions: [Position]) -> some View {83 let v = PortfolioValuation(positions: positions, quotes: app.market.quotes.mapValues(\.quote))84 let w: [String: Double] = Dictionary(uniqueKeysWithValues: v.lines.compactMap { l in l.weight.map { (l.position.symbol, $0 / 100) } })85 let usable = aligned.returns.keys.filter { w[$0] != nil }86 let total = usable.compactMap { w[$0] }.reduce(0, +)87 if total > 0, !aligned.dates.isEmpty {88 let port: [Double] = aligned.dates.indices.map { i in usable.reduce(0) { $0 + (aligned.returns[$1]?[i] ?? 0) * (w[$1]! / total) } }89 var level = 100.090 let curve = port.map { r -> Double in level *= 1 + r; return level }91 let dd = SeriesStats.drawdown(curve)92 Panel("Holdings at today's weights — drawdown, %") {93 Chart(Array(zip(aligned.dates, dd)), id: \.0) { AreaMark(x: .value("Date", $0.0), y: .value("Drawdown", $0.1)).foregroundStyle(Palette.red.opacity(0.35)); LineMark(x: .value("Date", $0.0), y: .value("Drawdown", $0.1)).foregroundStyle(Palette.red) }94 .frame(height: 200)95 HStack {96 Stat(label: "Volatility (ann.)", value: Fmt.plainPercent(SeriesStats.stdev(port).map { $0 * 252.0.squareRoot() * 100 }))97 Stat(label: "Max drawdown", value: Fmt.plainPercent(dd.min()), color: Palette.red)98 Stat(label: "Weights covered", value: Fmt.plainPercent(total * 100, digits: 0))99 }100 Text("Assumes the current weights were held throughout the period (no rebalancing history is recorded).").font(.caption2).foregroundStyle(.tertiary)101 }102 }103 }104105 @ViewBuilder private var recentJobs: some View {106 let jobs = app.quant.jobs.filter { ["var", "risk_metrics", "portfolio_optimization", "garch"].contains($0.tool) }.prefix(8)107 Panel("Server engine results") {108 if jobs.isEmpty { Text("None yet. Use “Run a Server Engine” for Value at Risk, risk metrics or an optimisation of the holdings.").font(.callout).foregroundStyle(.secondary) }109 ForEach(Array(jobs)) { j in110 Button { model.openQuantJob(j.id) } label: {111 HStack { JobStatusIcon(status: j.status); Text("\(app.quant.tool(j.tool)?.title ?? j.tool) · \(j.subject)").lineLimit(1); Spacer(); Text(Fmt.relative(j.started)).font(.caption).foregroundStyle(.secondary) }.contentShape(Rectangle())112 }.buttonStyle(.plain)113 }114 }115 }116117 private func launch(_ tool: String, _ params: [String: JSONValue]) {118 Task { do { let j = try await app.quant.submit(tool: tool, params: params); model.openQuantJob(j.id) } catch { app.toasts.error(error) } }119 }120121 private func load(_ symbols: [String]) async {122 guard !symbols.isEmpty else { series = []; return }123 loading = true; defer { loading = false }124 let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd"125 let to = f.string(from: Date()), from = f.string(from: Calendar.current.date(byAdding: .year, value: -years, to: Date())!)126 var out: [(String, [Bar])] = []; var miss: [String] = []; var cached = false127 for s in symbols.prefix(20) {128 if Task.isCancelled { return }129 if let r = try? await app.cache.fetch("bars-\(s)-1day-risk\(years)", { [api = app.api] in try await api.dailyBars(s, from: from, to: to).bars }), r.value.count > 20 { out.append((s, r.value)); cached = cached || r.fromCache }130 else { miss.append(s) }131 }132 series = out.map { (symbol: $0.0, bars: $0.1) }; missing = miss; fromCache = cached133 }134}135