Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/QuantViews.swift3// Description: The native result views of the six legacy quant tools of 1.x (GARCH, VaR, Monte Carlo, options, optimiser, risk metrics), fed from a job's raw result. The Quant Lab section itself is in LabView.swift and its neighbours.4import Charts5import SwiftUI6import UniformTypeIdentifiers7import VQuantCore89struct JobStatusIcon: View {10 let status: QuantJob.Status11 var body: some View {12 switch status {13 case .running: ProgressView().controlSize(.mini).frame(width: 14)14 case .done: Image(systemName: "checkmark.circle.fill").foregroundStyle(Palette.green).frame(width: 14)15 case .error: Image(systemName: "xmark.circle.fill").foregroundStyle(Palette.red).frame(width: 14)16 case .interrupted: Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange).frame(width: 14)17 case .cancelled: Image(systemName: "stop.circle").foregroundStyle(.secondary).frame(width: 14)18 }19 }20}2122/// Renders an engine's result. Known fields get purpose-built tables and charts; every other field of the result is23/// still listed, so nothing the engine returned is hidden.24struct QuantResultView: View {25 let app: AppEnvironment26 let tool: String27 let result: JSONValue2829 var body: some View {30 VStack(alignment: .leading, spacing: 14) {31 switch tool {32 case "garch": garch33 case "var": valueAtRisk34 case "monte_carlo": monteCarlo35 case "options": options36 case "portfolio_optimization": optimisation37 case "risk_metrics": riskMetrics38 default: EmptyView()39 }40 GenericSections(result: result, skip: handled)41 }42 }4344 private var handled: Set<String> {45 switch tool {46 case "garch": ["success", "historical_volatility", "volatility_forecast"]47 case "var": ["success", "var_by_confidence"]48 case "monte_carlo": ["success", "sample_paths", "final_values_distribution"]49 case "options": ["success", "call_option", "put_option"]50 case "portfolio_optimization": ["success", "optimal_portfolios", "efficient_frontier", "correlation_matrix", "asset_statistics"]51 default: ["success"]52 }53 }5455 private func series(_ key: String) -> [(String, Double)] {56 let d = result[key]?["dates"]?.arrayValue?.compactMap(\.stringValue) ?? [], v = result[key]?["values"]?.arrayValue?.compactMap(\.doubleValue) ?? []57 return Array(zip(d, v))58 }5960 @ViewBuilder private var garch: some View {61 let hist = series("historical_volatility"), fc = series("volatility_forecast")62 if !hist.isEmpty || !fc.isEmpty {63 Panel("Conditional volatility (annualised) — estimated, then forecast") {64 Chart {65 ForEach(hist, id: \.0) { d, v in if let t = BarParser.date(d) { LineMark(x: .value("Date", t), y: .value("Volatility", v * 100), series: .value("s", "Estimated")).foregroundStyle(by: .value("s", "Estimated")) } }66 ForEach(fc, id: \.0) { d, v in if let t = BarParser.date(d) { LineMark(x: .value("Date", t), y: .value("Volatility", v * 100), series: .value("s", "Forecast")).foregroundStyle(by: .value("s", "Forecast")).lineStyle(StrokeStyle(lineWidth: 2, dash: [4, 3])) } }67 }68 .chartYAxisLabel("%").chartForegroundStyleScale(["Estimated": Color.blue, "Forecast": Color.orange]).frame(height: 240)69 }70 }71 }7273 @ViewBuilder private var valueAtRisk: some View {74 if let levels = result["var_by_confidence"]?.objectValue {75 let keys = levels.keys.sorted { (levels[$0]?["confidence_level"]?.doubleValue ?? 0) < (levels[$1]?["confidence_level"]?.doubleValue ?? 0) }76 Panel("Value at Risk by confidence level") {77 Grid(alignment: .trailing, horizontalSpacing: 18, verticalSpacing: 6) {78 GridRow { Text("Confidence").gridColumnAlignment(.leading); Text("Historical"); Text("Parametric"); Text("Monte Carlo"); Text("Expected shortfall") }.font(.caption).foregroundStyle(.secondary)79 ForEach(keys, id: \.self) { k in80 let l = levels[k]!81 Divider().gridCellUnsizedAxes(.horizontal)82 GridRow {83 Text(k).fontWeight(.medium)84 ForEach(["historical", "parametric", "monte_carlo"], id: \.self) { m in85 VStack(alignment: .trailing, spacing: 0) { Text(Fmt.money(l[m]?["var_dollar"]?.doubleValue)); Text(Fmt.plainPercent(l[m]?["var_percentage"]?.doubleValue)).font(.caption).foregroundStyle(.secondary) }86 }87 VStack(alignment: .trailing, spacing: 0) { Text(Fmt.money(l["conditional_var"]?["cvar_dollar"]?.doubleValue)); Text(Fmt.plainPercent(l["conditional_var"]?["cvar_percentage"]?.doubleValue)).font(.caption).foregroundStyle(.secondary) }88 }.monospacedDigit()89 }90 }91 }92 }93 }9495 @ViewBuilder private var monteCarlo: some View {96 let paths = (result["sample_paths"]?.arrayValue ?? []).map { $0.arrayValue?.compactMap(\.doubleValue) ?? [] }97 if !paths.isEmpty {98 Panel("Sample of simulated paths (\(paths.count) shown)") {99 Chart {100 ForEach(Array(paths.enumerated()), id: \.offset) { n, p in101 ForEach(Array(p.enumerated()), id: \.offset) { i, v in LineMark(x: .value("Day", i), y: .value("Value", v), series: .value("Path", n)).foregroundStyle(Palette.series[n % Palette.series.count].opacity(0.75)).lineStyle(StrokeStyle(lineWidth: 1)) }102 }103 }104 .chartXAxisLabel("Trading days").frame(height: 240)105 }106 }107 let bins = result["final_values_distribution"]?["bins"]?.arrayValue?.compactMap(\.doubleValue) ?? [], counts = result["final_values_distribution"]?["counts"]?.arrayValue?.compactMap(\.doubleValue) ?? []108 if bins.count == counts.count + 1, !counts.isEmpty {109 Panel("Distribution of final values") {110 Chart { ForEach(counts.indices, id: \.self) { i in RectangleMark(xStart: .value("From", bins[i]), xEnd: .value("To", bins[i + 1]), yStart: .value("0", 0), yEnd: .value("Count", counts[i])).foregroundStyle(Color.accentColor.opacity(0.7)) } }111 .chartYAxisLabel("Simulations").frame(height: 200)112 }113 }114 }115116 @ViewBuilder private var options: some View {117 HStack(alignment: .top, spacing: 14) {118 ForEach(["call_option", "put_option"], id: \.self) { k in119 if let o = result[k] {120 Panel(k == "call_option" ? "Call" : "Put") {121 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {122 kv("Price", Fmt.price(o["price"]?.doubleValue, digits: 4)); kv("Intrinsic value", Fmt.price(o["intrinsic_value"]?.doubleValue, digits: 4)); kv("Time value", Fmt.price(o["time_value"]?.doubleValue, digits: 4))123 kv("Moneyness", o["moneyness"]?.stringValue ?? "—")124 ForEach(["delta", "gamma", "theta", "vega", "rho"], id: \.self) { g in kv(g.capitalized, Fmt.number(o["greeks"]?[g]?.doubleValue, digits: 4)) }125 }126 }127 }128 }129 }130 }131132 @ViewBuilder private var optimisation: some View {133 if let ports = result["optimal_portfolios"]?.objectValue {134 let order = ["max_sharpe_ratio", "min_volatility", "equal_weight"].filter { ports[$0] != nil }135 let symbols = result["symbols"]?.arrayValue?.compactMap(\.stringValue) ?? []136 Panel("Portfolios") {137 Grid(alignment: .trailing, horizontalSpacing: 16, verticalSpacing: 5) {138 GridRow { Text("").gridColumnAlignment(.leading); ForEach(order, id: \.self) { Text($0.replacingOccurrences(of: "_", with: " ").capitalized) } }.font(.caption).foregroundStyle(.secondary)139 ForEach(symbols, id: \.self) { s in GridRow { Text(s).font(.body.monospaced()); ForEach(order, id: \.self) { Text(Fmt.plainPercent(ports[$0]?["allocation"]?[s]?.doubleValue)) } } }140 Divider().gridCellUnsizedAxes(.horizontal)141 GridRow { Text("Expected return"); ForEach(order, id: \.self) { Text(Fmt.plainPercent(ports[$0]?["expected_return"]?.doubleValue)) } }142 GridRow { Text("Volatility"); ForEach(order, id: \.self) { Text(Fmt.plainPercent(ports[$0]?["volatility"]?.doubleValue)) } }143 GridRow { Text("Sharpe ratio"); ForEach(order, id: \.self) { Text(Fmt.number(ports[$0]?["sharpe_ratio"]?.doubleValue, digits: 3)) } }144 }.monospacedDigit()145 }146 let fr = result["efficient_frontier"], rets = fr?["returns"]?.arrayValue?.compactMap(\.doubleValue) ?? [], vols = fr?["volatilities"]?.arrayValue?.compactMap(\.doubleValue) ?? []147 if rets.count == vols.count, !rets.isEmpty {148 Panel("Efficient frontier") {149 Chart {150 // the frontier is a set of (volatility, return) points ordered by target return: drawn as points, a line through x-sorted values would misrepresent it151 ForEach(rets.indices, id: \.self) { i in PointMark(x: .value("Volatility", vols[i] * 100), y: .value("Return", rets[i] * 100)).foregroundStyle(Color.secondary).symbolSize(22) }152 ForEach(order, id: \.self) { k in153 if let v = ports[k]?["volatility"]?.doubleValue, let r = ports[k]?["expected_return"]?.doubleValue {154 PointMark(x: .value("Volatility", v), y: .value("Return", r)).foregroundStyle(by: .value("Portfolio", k.replacingOccurrences(of: "_", with: " ").capitalized)).symbolSize(90)155 }156 }157 }158 .chartXAxisLabel("Annualised volatility, %").chartYAxisLabel("Expected return, %").frame(height: 260)159 }160 }161 if let corr = result["correlation_matrix"]?.objectValue, !symbols.isEmpty {162 Panel("Correlation of daily returns") { CorrelationHeatmap(symbols: symbols) { a, b in corr[a]?[b]?.doubleValue } }163 }164 if let stats = result["asset_statistics"]?.objectValue {165 Panel("Assets") {166 Grid(alignment: .trailing, horizontalSpacing: 16, verticalSpacing: 4) {167 GridRow { Text("").gridColumnAlignment(.leading); Text("Expected return"); Text("Volatility"); Text("Sharpe") }.font(.caption).foregroundStyle(.secondary)168 ForEach(symbols, id: \.self) { s in GridRow { Text(s).font(.body.monospaced()); Text(Fmt.plainPercent(stats[s]?["expected_return"]?.doubleValue)); Text(Fmt.plainPercent(stats[s]?["volatility"]?.doubleValue)); Text(Fmt.number(stats[s]?["sharpe_ratio"]?.doubleValue, digits: 3)) } }169 }.monospacedDigit()170 }171 }172 }173 }174175 @ViewBuilder private var riskMetrics: some View { EmptyView() }176177 private func kv(_ k: String, _ v: String) -> some View { GridRow { Text(k).foregroundStyle(.secondary); Text(v).monospacedDigit().gridColumnAlignment(.trailing) } }178}179180/// Every remaining object of a result as a key/value panel; scalars at the top level go in "Summary".181private struct GenericSections: View {182 let result: JSONValue183 let skip: Set<String>184185 var body: some View {186 let obj = result.objectValue ?? [:]187 let keys = obj.keys.filter { !skip.contains($0) }.sorted()188 let scalars = keys.filter { Self.isScalar(obj[$0]!) }189 let groups = keys.filter { obj[$0]!.objectValue != nil }190 let lists = keys.filter { if let a = obj[$0]!.arrayValue { return !a.isEmpty && a.allSatisfy(Self.isScalar) } else { return false } }191 LazyVGrid(columns: [GridItem(.adaptive(minimum: 300), spacing: 14, alignment: .top)], alignment: .leading, spacing: 14) {192 if !scalars.isEmpty { Panel("Summary") { rows(scalars.map { ($0, obj[$0]!) }) } }193 ForEach(groups, id: \.self) { k in Panel(Self.title(k)) { rows(Self.flatten(obj[k]!)) } }194 ForEach(lists, id: \.self) { k in Panel(Self.title(k)) { Text(obj[k]!.arrayValue!.map(Self.text).joined(separator: "\n")).font(.callout).textSelection(.enabled) } }195 }196 }197198 private func rows(_ items: [(String, JSONValue)]) -> some View {199 Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 4) {200 ForEach(items, id: \.0) { k, v in GridRow { Text(Self.title(k)).foregroundStyle(.secondary); Text(Self.text(v)).monospacedDigit().textSelection(.enabled).gridColumnAlignment(.trailing) } }201 }.font(.callout)202 }203204 static func isScalar(_ v: JSONValue) -> Bool { switch v { case .array, .object: false; default: true } }205 static func title(_ k: String) -> String { k.replacingOccurrences(of: "_", with: " ").prefix(1).uppercased() + k.replacingOccurrences(of: "_", with: " ").dropFirst() }206 static func text(_ v: JSONValue) -> String {207 switch v {208 case .number(let n): n.rounded() == n && abs(n) < 1e12 ? Int64(n).formatted() : n.formatted(.number.precision(.significantDigits(1...6)))209 case .bool(let b): b ? "yes" : "no"210 case .string(let s): s211 case .null: "—"212 case .array(let a): a.map(text).joined(separator: ", ")213 case .object: "…"214 }215 }216 /// One level of nesting is flattened ("parent · child"); deeper structures are summarised by their size.217 static func flatten(_ v: JSONValue) -> [(String, JSONValue)] {218 var out: [(String, JSONValue)] = []219 for (k, x) in (v.objectValue ?? [:]).sorted(by: { $0.key < $1.key }) {220 if let o = x.objectValue { for (k2, y) in o.sorted(by: { $0.key < $1.key }) { out.append(("\(k) · \(k2)", isScalar(y) || y.arrayValue != nil ? y : .string("{\(y.objectValue?.count ?? 0) fields}"))) } }221 else if let a = x.arrayValue, a.count > 12 { out.append((k, .string("\(a.count) values"))) }222 else { out.append((k, x)) }223 }224 return out225 }226}227228/// Square heatmap of a correlation matrix (−1 blue … +1 red), values printed in the cells.229struct CorrelationHeatmap: View {230 let symbols: [String]231 let value: (String, String) -> Double?232233 var body: some View {234 Grid(horizontalSpacing: 2, verticalSpacing: 2) {235 GridRow { Text(""); ForEach(symbols, id: \.self) { Text($0).font(.caption.monospaced()).lineLimit(1).frame(minWidth: 46) } }236 ForEach(symbols, id: \.self) { a in237 GridRow {238 Text(a).font(.caption.monospaced()).gridColumnAlignment(.trailing)239 ForEach(symbols, id: \.self) { b in240 let v = value(a, b)241 Text(v.map { String(format: "%.2f", $0) } ?? "—").font(.caption.monospacedDigit())242 .frame(minWidth: 46, minHeight: 26).frame(maxWidth: .infinity)243 .background(color(v), in: RoundedRectangle(cornerRadius: 3))244 .foregroundStyle(abs(v ?? 0) > 0.6 ? Color.white : Color.primary)245 .accessibilityLabel("\(a) and \(b): \(v.map { String(format: "%.2f", $0) } ?? "not available")")246 }247 }248 }249 }250 }251 private func color(_ v: Double?) -> Color {252 guard let v else { return Color.secondary.opacity(0.1) }253 return v >= 0 ? Color(red: 0.85, green: 0.25, blue: 0.2).opacity(0.12 + 0.75 * min(v, 1)) : Color(red: 0.15, green: 0.4, blue: 0.85).opacity(0.12 + 0.75 * min(-v, 1))254 }255}256