Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Quant/LabDedicated.swift3// Description: What the Quant Lab adds around the generic renderer for particular engines: the always-visible integrity statement of a backtest (look-ahead, survivorship), the hero of the options workbenches (price and Greeks; payoff, break-evens, maximum gain and loss), slices of long results, and the side-by-side comparison of two results.4import SwiftUI5import VQuantCore6import VQuantKit7import VQuantUI89private typealias P = VQTokens.Palette10private typealias S = VQTokens.Space11private typealias T = VQTokens.Typography1213/// Pure reshaping of results for display (no number is changed, added or removed from what the engine returned:14/// parts are only placed elsewhere on the screen).15@MainActor enum LabShape {16 static func options(hidden: Set<LabResultView.Section>, app: AppEnvironment) -> LabResultView.Options {17 var o = LabResultView.Options()18 o.hidden = hidden19 #if DEBUG20 // captures of the lower sections: `-VQXLabHide summary,charts`21 if let h = app.options.extra["LabHide"] { o.hidden.formUnion(h.split(separator: ",").compactMap { LabResultView.Section(rawValue: String($0)) }) }22 #endif23 return o24 }2526 static func sliced(_ r: VQLabResult, _ slice: LabSlice) -> VQLabResult {27 var out = r28 out.charts = r.charts.filter { slice.includesChart($0.id) }29 out.tables = r.tables.filter { slice.includesTable($0.id) }30 out.warnings = []31 return out32 }3334 static func integrity(_ r: VQLabResult, job: VQQuantJob) -> LabIntegrity.Statement {35 LabIntegrity.backtest(diagnostics: r.diagnostics.map { .init(name: $0.name, passed: $0.passed, conclusion: $0.conclusion) },36 warnings: r.warnings, assumptions: r.assumptions, symbols: max(1, job.params["symbols"]?.arrayValue?.count ?? 1))37 }3839 static func paramSummary(_ j: VQQuantJob) -> String {40 j.params.keys.sorted().map { "\($0) = \(LabCompare.paramText(j.params[$0]!.core))" }.joined(separator: " · ")41 }4243 /// Title, headline and summary figures as plain text (for the clipboard and for the agent's context).44 static func plainText(_ j: VQQuantJob, title: String, locale: VQNumberLocale) -> String {45 guard let r = j.labResult else { return "\(title) · \(j.subject)\nEngine \(j.tool) · \(paramSummary(j))\nJob \(j.id)" }46 var lines = [r.title.isEmpty ? title : r.title, r.headline]47 lines += r.summary.map { "\($0.label): \($0.formatted(locale: locale)) (\($0.kind.known?.label(.en).lowercased() ?? $0.kind.rawValue))" }48 lines.append("Job \(j.id) · engine \(r.engine)\(r.engineVersion.map { " v\($0)" } ?? "")")49 return lines.filter { !$0.isEmpty }.joined(separator: "\n")50 }5152 /// A question for the research agent, with the job stated in words (the server receives plain text).53 static func ask(_ j: VQQuantJob, title: String, locale: VQNumberLocale) -> AskDraft {54 var context = "Context — a Quant Lab result I am looking at in VQuant. Job id: \(j.id). Engine: \(j.tool)\(j.engineVersion.map { " v\($0)" } ?? "")."55 if let r = j.labResult {56 if !r.headline.isEmpty { context += " Headline: \(r.headline)" }57 let metrics = r.summary.prefix(12).map { "\($0.label) \($0.formatted(locale: .enCA))" }.joined(separator: "; ")58 if !metrics.isEmpty { context += " Summary: \(metrics)." }59 if !r.warnings.isEmpty { context += " Engine warnings: \(r.warnings.prefix(3).joined(separator: " "))" }60 } else { context += " Legacy tool \(title) on \(j.subject)." }61 context += " Recorded parameters: \(paramSummary(j).prefix(900))."62 return AskDraft(text: "Explain this \(title) result\(j.subject.isEmpty ? "" : " on \(j.subject)"): what it shows, how robust it is, and what could invalidate it.", context: context, projectId: j.projectId)63 }6465 static func describe(_ j: VQQuantJob) -> String {66 [j.subject, j.variant, LabFormat.started(j.startedAt)].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")67 }6869 /// Numeric leaves of a legacy result ("parent · child"), for the comparison of two legacy jobs.70 static func legacyMetrics(_ v: VQJSON, prefix: String = "", depth: Int = 0) -> [LabCompare.Metric] {71 guard depth <= 3, let o = v.objectValue else { return [] }72 var out: [LabCompare.Metric] = []73 for k in o.keys.sorted() {74 let label = prefix.isEmpty ? k.replacingOccurrences(of: "_", with: " ") : "\(prefix) · \(k.replacingOccurrences(of: "_", with: " "))"75 switch o[k]! {76 case .number(let n): out.append(.init(label: label, value: n))77 case .object: out += legacyMetrics(o[k]!, prefix: label, depth: depth + 1)78 default: break79 }80 if out.count > 80 { break }81 }82 return out83 }84}8586// MARK: - Backtest integrity8788/// Look-ahead and survivorship, pinned above every backtest result: the engine's own flags, or a plain statement89/// that it reported none. Glyph and word, never colour alone.90struct LabIntegrityBanner: View {91 let statement: LabIntegrity.Statement92 @Binding var expanded: Bool93 let app: AppEnvironment9495 private func look(_ s: LabIntegrity.State) -> (symbol: String, color: Color, word: String) {96 switch s {97 case .passed: ("checkmark.shield", app.settings.upColor, "passed")98 case .failed: ("xmark.shield", P.critical, "FAILED")99 case .warning: ("exclamationmark.triangle", P.warn, "warning")100 case .informational: ("info.circle", P.info, "stated")101 case .notReported: ("questionmark.diamond", P.warn, "not reported")102 }103 }104105 var body: some View {106 HStack(alignment: .top, spacing: S.s5) {107 column("Look-ahead", statement.lookAhead)108 Rectangle().fill(P.line).frame(width: 1)109 column("Survivorship", [statement.survivorship])110 Button { expanded.toggle() } label: { Image(systemName: expanded ? "chevron.up" : "chevron.down").font(.system(size: 10, weight: .semibold)).foregroundStyle(P.text3).frame(width: 18, height: 18).contentShape(Rectangle()) }111 .buttonStyle(.plain).help(expanded ? "Show less" : "Show the full statements").accessibilityLabel(expanded ? "Collapse the integrity statements" : "Expand the integrity statements")112 }113 .padding(.horizontal, S.s4).padding(.vertical, S.s2)114 .frame(maxWidth: .infinity, alignment: .leading)115 .fixedSize(horizontal: false, vertical: true)116 .background(P.ink1)117 .accessibilityElement(children: .contain)118 .accessibilityIdentifier("lab.integrity")119 }120121 private func column(_ title: String, _ lines: [LabIntegrity.Line]) -> some View {122 VStack(alignment: .leading, spacing: 4) {123 Text(title).vqFont(T.overline).foregroundStyle(P.text3)124 ForEach(lines) { l in125 let v = look(l.state)126 HStack(alignment: .firstTextBaseline, spacing: 6) {127 Image(systemName: v.symbol).font(.system(size: 12, weight: .medium)).foregroundStyle(v.color).frame(width: 15).accessibilityHidden(true)128 (Text(l.fromEngine ? "\(l.title == title ? "Engine" : l.title) — \(v.word). " : "\(v.word.prefix(1).uppercased() + v.word.dropFirst()). ").fontWeight(.semibold).foregroundStyle(P.text1)129 + Text(l.detail).foregroundStyle(P.text2))130 .vqFont(T.caption).lineLimit(expanded ? nil : 2).fixedSize(horizontal: false, vertical: true)131 .help(l.detail + (l.fromEngine ? "\n\nReported by the engine." : "\n\nStated by the app: the engine reported nothing on this point."))132 }133 .accessibilityElement(children: .combine)134 }135 }136 .frame(maxWidth: .infinity, alignment: .topLeading)137 }138}139140// MARK: - Options workbenches141142/// The top of an options result, by mode. The figures are the engine's summary metrics and its payoff chart, moved143/// to the top; `remaining` is the result without them, for the generic renderer underneath.144struct LabOptionsHero: View {145 let result: VQLabResult146 let mode: LabOptionsMode147 let app: AppEnvironment148 private let heroMetrics: [VQLabResult.Metric]149 private let greeks: [VQLabResult.Metric]150 private let chart: VQLabResult.Chart?151152 init?(result: VQLabResult, mode: LabOptionsMode, app: AppEnvironment) {153 self.result = result; self.mode = mode; self.app = app154 func pick(_ prefixes: [String]) -> [VQLabResult.Metric] { prefixes.flatMap { p in result.summary.filter { $0.label.hasPrefix(p) } } }155 switch mode {156 case .price:157 heroMetrics = pick(["Model price", "Price per contract", "Monte Carlo price", "Early-exercise premium"])158 greeks = ["Delta", "Gamma", "Vega", "Theta", "Rho"].compactMap { g in result.summary.first { $0.label == g } }159 chart = result.charts.first { $0.id == "price_vs_spot" }160 case .strategy:161 heroMetrics = pick(["Net cost", "Maximum profit", "Maximum loss", "Breakeven", "Probability of profit"])162 greeks = []163 chart = result.charts.first { $0.type == .payoff }164 default: return nil165 }166 if heroMetrics.isEmpty && chart == nil { return nil }167 }168169 /// The result without what the hero already shows.170 var remaining: VQLabResult {171 var r = result172 let moved = Set((heroMetrics + greeks).map(\.label))173 r.summary = result.summary.filter { !moved.contains($0.label) }174 if let chart { r.charts = result.charts.filter { $0.id != chart.id } }175 // the generic renderer repeats the title block; the hero has already shown it176 r.title = ""; r.headline = ""; r.warnings = []177 return r178 }179180 /// "unbounded" when the engine says so in its warnings and gives no number.181 private func unbounded(_ m: VQLabResult.Metric) -> String? {182 guard m.value == nil, m.text == nil else { return nil }183 let word = m.label.lowercased().contains("profit") ? "profit is unbounded" : m.label.lowercased().contains("loss") ? "loss is unbounded" : ""184 return !word.isEmpty && result.warnings.contains { $0.lowercased().contains(word) } ? "Unbounded" : nil185 }186187 var body: some View {188 VStack(alignment: .leading, spacing: S.s5) {189 VStack(alignment: .leading, spacing: S.s2) {190 Text("OPTIONS LAB · \(mode.title.uppercased())\(result.engineVersion.map { " · V\($0)" } ?? "")").vqFont(T.overline).foregroundStyle(P.text3)191 Text(result.title).vqFont(T.displayMd).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)192 Text(result.headline).vqFont(T.body).lineSpacing(4).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true).frame(maxWidth: 760, alignment: .leading)193 }194 if !result.warnings.isEmpty {195 VStack(alignment: .leading, spacing: S.s2) {196 ForEach(result.warnings, id: \.self) { w in197 HStack(alignment: .firstTextBaseline, spacing: S.s2) {198 Image(systemName: "exclamationmark.triangle").font(.system(size: 11, weight: .semibold)).foregroundStyle(P.warn).accessibilityHidden(true)199 Text(w).vqFont(T.bodySm).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true)200 }201 }202 }203 .padding(S.s3).frame(maxWidth: .infinity, alignment: .leading)204 .overlay(alignment: .leading) { Rectangle().fill(P.warn).frame(width: 2) }.background(P.ink1)205 }206 VStack(alignment: .leading, spacing: S.s4) {207 VQSectionHeader(mode == .strategy ? "Payoff, break-evens, maximum gain and loss" : "Price and Greeks")208 LazyVGrid(columns: [GridItem(.adaptive(minimum: 176, maximum: 320), spacing: S.s4, alignment: .topLeading)], alignment: .leading, spacing: S.s3) {209 ForEach(Array(heroMetrics.enumerated()), id: \.offset) { i, m in210 Group {211 if let u = unbounded(m) {212 VStack(alignment: .leading, spacing: S.s1) {213 HStack { Text(m.label).vqFont(T.overline).foregroundStyle(P.text3); Spacer(minLength: 0); VQKindBadge(.calculated) }214 Text(u).vqFont(T.numMd).foregroundStyle(P.text1)215 Text("No finite value: see the engine's warning.").vqFont(T.caption).foregroundStyle(P.text3)216 }217 } else {218 VQMetricTile(label: m.label, value: m.value, unit: m.unit, kind: m.kind.known, decimals: m.decimals, currency: m.currency ?? "USD", note: m.note, large: i == 0 && mode == .price)219 }220 }221 .padding(.top, S.s2).overlay(alignment: .top) { Rectangle().fill(P.line).frame(height: 1) }222 }223 }224 if !greeks.isEmpty {225 HStack(alignment: .top, spacing: 0) {226 ForEach(Array(greeks.enumerated()), id: \.offset) { i, g in227 VStack(alignment: .leading, spacing: 2) {228 Text(g.label).vqFont(T.overline).foregroundStyle(P.text3)229 Text(VQFormat.number(g.value, decimals: g.decimals ?? 4, locale: app.vqTheme.numberLocale)).vqFont(T.numMd).foregroundStyle(P.text1)230 }231 .padding(.horizontal, S.s3).padding(.vertical, S.s2).frame(maxWidth: .infinity, alignment: .leading)232 .overlay(alignment: .leading) { if i > 0 { Rectangle().fill(P.line).frame(width: 1) } }233 .accessibilityElement(children: .combine)234 }235 }236 .background(P.ink1)237 .overlay { Rectangle().strokeBorder(P.line, lineWidth: 1) }238 .help("Black-Scholes-Merton Greeks per share (see the Greeks table for the tree values and the per-contract figures).")239 }240 if let chart { LabChartView(chart, height: mode == .strategy ? 340 : 280) }241 }242 }243 }244}245246// MARK: - Comparison247248/// Two results of the same engine side by side: parameters that differ, summary metrics with deltas, figures stacked.249struct LabCompareView: View {250 let app: AppEnvironment251 let a: VQQuantJob252 let b: VQQuantJob253 let close: () -> Void254 let swap: () -> Void255256 init(app: AppEnvironment, a: VQQuantJob, b: VQQuantJob, close: @escaping () -> Void, swap: @escaping () -> Void) {257 self.app = app; self.a = a; self.b = b; self.close = close; self.swap = swap258 }259260 private var locale: VQNumberLocale { app.vqTheme.numberLocale }261 private var ra: VQLabResult? { a.labResult.flatMap { $0.success ? $0 : nil } }262 private var rb: VQLabResult? { b.labResult.flatMap { $0.success ? $0 : nil } }263264 private struct Shown: Identifiable { var row: LabCompare.Row; var a: String; var b: String; var delta: String; var direction: VQDirection; var id: String { row.label } }265266 private var rows: [Shown] {267 let ma = ra?.summary ?? [], mb = rb?.summary ?? []268 let la = ra != nil ? ma.map { LabCompare.Metric(label: $0.label, value: $0.value, unit: $0.unit.rawValue) } : (a.result.map { LabShape.legacyMetrics($0) } ?? [])269 let lb = rb != nil ? mb.map { LabCompare.Metric(label: $0.label, value: $0.value, unit: $0.unit.rawValue) } : (b.result.map { LabShape.legacyMetrics($0) } ?? [])270 return LabCompare.rows(a: la, b: lb).map { row in271 let meta = ma.first { $0.label == row.label } ?? mb.first { $0.label == row.label }272 let unit = meta?.unit ?? .none, decimals = meta?.decimals, currency = meta?.currency ?? "USD"273 func show(_ v: Double?, _ present: Bool, _ text: String?) -> String {274 if !present { return "not in this result" }275 if let text { return text }276 return meta != nil ? VQFormat.byUnitName(v, meta?.unitName, decimals: decimals, currency: currency, compact: unit == .currency && abs(v ?? 0) >= 1e7, locale: locale) : VQFormat.number(v, decimals: abs(v ?? 0) >= 100 ? 2 : 4, locale: locale)277 }278 let delta: String279 if let d = row.delta {280 switch unit {281 case .percent: delta = VQFormat.number(d * 100, decimals: decimals ?? 2, signed: true, locale: locale) + " pp"282 case .none where meta == nil: delta = VQFormat.number(d, decimals: abs(d) >= 100 ? 2 : 4, signed: true, locale: locale)283 default: delta = VQFormat.byUnit(d, unit, decimals: decimals, currency: currency, signed: true, compact: unit == .currency && abs(d) >= 1e7, locale: locale)284 }285 } else { delta = VQFormat.nullText }286 return Shown(row: row, a: show(row.a, row.inA, ma.first { $0.label == row.label }?.text), b: show(row.b, row.inB, mb.first { $0.label == row.label }?.text), delta: delta,287 direction: row.delta.map { $0 > 0 ? .up : $0 < 0 ? .down : .flat } ?? .flat)288 }289 }290291 var body: some View {292 let differences = LabCompare.paramDifferences(a: a.params.mapValues(\.core), b: b.params.mapValues(\.core))293 ScrollView {294 VStack(alignment: .leading, spacing: S.s8) {295 VStack(alignment: .leading, spacing: S.s3) {296 HStack(alignment: .firstTextBaseline) {297 VStack(alignment: .leading, spacing: 2) {298 Text("\(app.lab.title(a.tool)) · comparison").vqFont(T.overline).foregroundStyle(P.text3)299 Text("Two results, side by side").vqFont(T.displayMd).foregroundStyle(P.text1).accessibilityIdentifier("lab.compare.view")300 }301 Spacer()302 Button("Swap A and B", action: swap).controlSize(.small)303 Button("Close the Comparison", action: close).controlSize(.small).accessibilityIdentifier("lab.compare.close")304 }305 side("A", a, P.accentText)306 side("B", b, P.info)307 }308309 VStack(alignment: .leading, spacing: S.s3) {310 VQSectionHeader("Parameters that differ") { Text("\(differences.count)").vqFont(T.numSm).foregroundStyle(P.text3) }311 if differences.isEmpty { Text("Both runs recorded the same parameters: any difference in the figures comes from the data available when each ran.").vqFont(T.bodySm).foregroundStyle(P.text2) }312 else {313 Grid(alignment: .leading, horizontalSpacing: S.s5, verticalSpacing: 0) {314 GridRow { head("Parameter"); head("A"); head("B") }315 ForEach(differences) { d in316 GridRow {317 Text(d.name).vqFont(T.caption).foregroundStyle(P.text2)318 Text(d.a).vqFont(T.numSm).foregroundStyle(P.text1).lineLimit(2).truncationMode(.middle)319 Text(d.b).vqFont(T.numSm).foregroundStyle(P.text1).lineLimit(2).truncationMode(.middle)320 }321 .padding(.vertical, 5)322 Rectangle().fill(P.line).frame(height: 1).gridCellColumns(3)323 }324 }325 .frame(maxWidth: 820, alignment: .leading)326 }327 }328329 VStack(alignment: .leading, spacing: S.s3) {330 VQSectionHeader("Metrics", overline: "Δ = B − A · percentages differ in percentage points (pp)")331 let shown = rows332 if shown.isEmpty { Text("These results have no summary figures to align.").vqFont(T.bodySm).foregroundStyle(P.text2) }333 else {334 Grid(alignment: .trailing, horizontalSpacing: S.s5, verticalSpacing: 0) {335 GridRow { head("Metric").gridColumnAlignment(.leading); head("A"); head("B"); head("Δ") }336 ForEach(shown) { r in337 GridRow {338 Text(r.row.label).vqFont(T.bodySm).foregroundStyle(P.text1).fixedSize(horizontal: false, vertical: true).frame(maxWidth: 320, alignment: .leading)339 Text(r.a).vqFont(r.row.inA ? T.numMd : T.caption).foregroundStyle(r.row.inA ? P.text1 : P.text3)340 Text(r.b).vqFont(r.row.inB ? T.numMd : T.caption).foregroundStyle(r.row.inB ? P.text1 : P.text3)341 HStack(spacing: 4) {342 if r.direction != .flat { VQDirectionGlyph(r.direction, size: 7).foregroundStyle(r.direction == .up ? app.settings.upColor : app.settings.downColor) }343 Text(r.delta).vqFont(T.numMd).foregroundStyle(r.row.delta == nil ? P.text3 : P.text1)344 }345 }346 .padding(.vertical, 6)347 Rectangle().fill(P.line).frame(height: 1).gridCellColumns(4)348 }349 }350 .frame(maxWidth: 900, alignment: .leading)351 }352 }353354 if let ra, let rb {355 let shared = ra.charts.filter { c in rb.charts.contains { $0.id == c.id } }356 let onlyOne = (ra.charts.filter { c in !rb.charts.contains { $0.id == c.id } }.map { "A: \($0.title)" }) + (rb.charts.filter { c in !ra.charts.contains { $0.id == c.id } }.map { "B: \($0.title)" })357 VStack(alignment: .leading, spacing: S.s5) {358 VQSectionHeader("Figures", overline: "Same figure of each result, A above B")359 ForEach(shared) { ca in360 if let cb = rb.charts.first(where: { $0.id == ca.id }) {361 VStack(alignment: .leading, spacing: S.s2) {362 stacked("A", P.accentText, ca)363 stacked("B", P.info, cb)364 }365 .padding(.bottom, S.s3)366 }367 }368 if !onlyOne.isEmpty { Text("In one result only — \(onlyOne.joined(separator: " · "))").vqFont(T.caption).foregroundStyle(P.text3).fixedSize(horizontal: false, vertical: true) }369 }370 } else {371 Text("Legacy results have no generic figures: open each result to see its own charts.").vqFont(T.caption).foregroundStyle(P.text3)372 }373 }374 .padding(.horizontal, S.s8).padding(.vertical, S.s6)375 .frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)376 }377 }378379 private func head(_ t: String) -> some View { Text(t).vqFont(T.overline).foregroundStyle(P.text3).padding(.bottom, 4) }380381 private func tag(_ letter: String, _ color: Color) -> some View {382 Text(letter).font(.system(size: 11, weight: .bold, design: .monospaced)).foregroundStyle(color).frame(width: 20, height: 20)383 .overlay { RoundedRectangle(cornerRadius: 4, style: .continuous).strokeBorder(color, lineWidth: 1) }384 }385386 private func side(_ letter: String, _ j: VQQuantJob, _ color: Color) -> some View {387 HStack(alignment: .firstTextBaseline, spacing: S.s2) {388 tag(letter, color)389 VStack(alignment: .leading, spacing: 1) {390 Text(LabShape.describe(j)).vqFont(T.bodySm).fontWeight(.medium).foregroundStyle(P.text1)391 if let h = j.labResult?.headline, !h.isEmpty { Text(h).vqFont(T.caption).foregroundStyle(P.text2).fixedSize(horizontal: false, vertical: true).frame(maxWidth: 820, alignment: .leading) }392 Text("Job \(j.id)").vqFont(T.numSm).foregroundStyle(P.text3).textSelection(.enabled)393 }394 }395 }396397 private func stacked(_ letter: String, _ color: Color, _ chart: VQLabResult.Chart) -> some View {398 HStack(alignment: .top, spacing: S.s2) {399 tag(letter, color)400 LabChartView(chart, height: 200)401 }402 }403}404