Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/RsLabTab.swift3// Description: The strategy laboratory's results as the server exposes them with its agent templates: out-of-sample backtests of strategies (per split, with the engine's stops and the gross-to-net breakdown), studies and their stated assumptions. Everything here is a simulation read from the lab's files — labelled as such on every block; a missing result file is shown as unavailable with its reason.4import SwiftUI5import SPWalletCore67@MainActor @Observable final class RsLabModel {8 let model: AppModel9 private(set) var templates: [AgentTemplate] = []10 private(set) var loadedAt: Date?11 private(set) var loading = false12 private(set) var error: String?1314 init(model: AppModel) { self.model = model }1516 func load() async {17 guard !loading else { return }18 loading = true; defer { loading = false }19 do { templates = try await AgentsAPI(model.client).templates().templates; loadedAt = Date(); error = nil } catch { self.error = model.describe(error) }20 }21 var withVerdicts: [AgentTemplate] { templates.filter { !($0.labVerdicts ?? []).isEmpty } }22}2324struct RsLabTab: View {25 let model: AppModel26 @State private var data: RsLabModel?2728 var body: some View {29 ScrollView {30 VStack(alignment: .leading, spacing: 16) {31 if let data {32 HStack {33 Text("Résultats du laboratoire de stratégies, lus par le serveur dans les fichiers du laboratoire.").font(.callout).foregroundStyle(.secondary)34 Spacer()35 if data.loading { ProgressView().controlSize(.small) }36 OpsAsOf(date: data.loadedAt, prefix: "Reçu")37 Button { Task { await data.load() } } label: { Image(systemName: "arrow.clockwise") }.disabled(data.loading)38 }39 Banner(.info, "Ce sont des BACKTESTS : ce qu’une stratégie aurait fait sur des données passées, sous le modèle d’exécution du laboratoire. Ce n’est ni un historique de performance, ni une prévision, ni un conseil. Un résultat hors échantillon favorable n’annonce pas un résultat futur.")40 if let e = data.error {41 if data.templates.isEmpty { Card { OpsUnavailable(what: "Résultats du laboratoire", reason: e) { Task { await data.load() } } } }42 else { Banner(.warning, "Dernière lecture en échec (\(e)).") }43 }44 if data.loadedAt != nil && data.withVerdicts.isEmpty { EmptyState(symbol: "testtube.2", title: "Aucun résultat de laboratoire exposé", detail: "Le serveur ne joint de résultats de backtest à aucun de ses \(data.templates.count) modèles d’agents.") }45 ForEach(data.withVerdicts) { t in RsLabTemplateCard(template: t) }46 } else { ProgressView().frame(maxWidth: .infinity).padding(40) }47 }.padding(24).frame(maxWidth: 1180, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)48 }49 .task { if data == nil { let d = RsLabModel(model: model); data = d; await d.load() } }50 }51}5253private struct RsLabTemplateCard: View {54 let template: AgentTemplate55 var body: some View {56 Card(template.name.text(locale: "fr"), trailing: AnyView(Text("\(template.family) · \(template.kind)").font(.caption).foregroundStyle(.secondary))) {57 Text(verbatim: template.summary.text(locale: "fr")).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)58 ForEach(Array((template.labVerdicts ?? []).enumerated()), id: \.offset) { _, v in59 Divider()60 if !v.available { RsLabUnavailable(verdict: v) }61 else if v.kind == "strategy" { RsLabStrategy(verdict: v) }62 else { RsLabStudy(verdict: v) }63 }64 }65 }66}6768private struct RsLabUnavailable: View {69 let verdict: LabVerdict70 var body: some View {71 HStack(alignment: .top, spacing: 10) {72 ProvenanceTag(p: .unavailable)73 VStack(alignment: .leading, spacing: 1) {74 Text("\(verdict.kind == "study" ? "Étude" : verdict.kind == "policy" ? "Politique" : "Stratégie") « \(verdict.name) » : résultat indisponible").fontWeight(.medium)75 Text(verdict.reason ?? "Le serveur ne donne pas de raison.").font(.callout).foregroundStyle(.secondary).textSelection(.enabled)76 }77 }78 }79}8081private struct RsLabStrategy: View {82 let verdict: LabVerdict83 private static let splits = ["train", "validation", "test"]8485 var body: some View {86 let v = verdict87 VStack(alignment: .leading, spacing: 6) {88 HStack {89 Text(v.strategy ?? "\(v.name)@\(v.version ?? "?")").font(Theme.mono).fontWeight(.semibold)90 RsFlag(text: scope(v), color: v.scope == "agent" && v.liveCapable == true ? .orange : .secondary, symbol: "scope")91 Spacer()92 ProvenanceTag(p: .simulated, text: "Backtest · laboratoire")93 }94 if let s = v.symbols, !s.isEmpty { Text(s.joined(separator: " · ")).font(.callout).foregroundStyle(.secondary) }95 Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 4) {96 GridRow { Text(""); ForEach(Self.splits, id: \.self) { Text(RsJobText.split($0)).font(.caption).foregroundStyle(.secondary) } }97 row("Rendement net") { OpsFmt.fraction($0.netReturn) }98 row("Sharpe net / brut") { "\(RsFmt.metric($0.netSharpe)) / \(RsFmt.metric($0.grossSharpe))" }99 row("Repli maximal") { $0.maxDrawdown.map { OpsFmt.fraction(-abs($0)) } ?? "—" }100 row("Transactions simulées") { $0.trades.map { $0.formatted(.number.precision(.fractionLength(0))) } ?? "—" }101 row("Résultat net (brut → net)") { $0.grossToNet?.netPnl.map { OpsFmt.signedUsd($0) } ?? "—" }102 row("dont frais / glissement / financement") { s in103 guard let g = s.grossToNet else { return "—" }104 return "\(OpsFmt.usd(g.fees)) / \(OpsFmt.usd(g.slippage)) / \(OpsFmt.signedUsd(g.funding))"105 }106 }107 ForEach(v.stoppedSplits ?? [], id: \.self) { name in108 if let stop = v.splits?[name]??.stop {109 Label("\(RsJobText.split(name)) : arrêté par la limite de perte du moteur (\(stop.reason))", systemImage: "stop.circle").font(.callout.weight(.medium)).foregroundStyle(Theme.negative)110 }111 }112 HStack(spacing: 8) {113 ProvenanceTag(p: .estimate, text: "Estimation statistique")114 Text("Sharpe déflaté \(RsFmt.metric(v.deflatedSharpe, digits: 3)) pour un seuil de \(RsFmt.metric(v.deflatedSharpeThreshold)) · \(v.trialsTested.map { "\(Int($0)) essais" } ?? "essais inconnus")\(v.testSharpeCi.flatMap { $0.count == 2 ? " · IC du Sharpe de test [\(RsFmt.metric($0[0])) ; \(RsFmt.metric($0[1]))]" : nil } ?? "")").font(.callout).monospacedDigit()115 }116 Text(v.significant == true ? "Selon la règle du laboratoire, le résultat hors échantillon dépasse son seuil. Cela reste un backtest." : v.significant == false ? "Selon la règle du laboratoire, le résultat hors échantillon NE dépasse PAS son seuil : rien ne le distingue du hasard des essais." : "Le laboratoire n’a pas tranché la significativité de ce résultat.")117 .font(.callout).foregroundStyle(v.significant == false ? Theme.warning : .secondary)118 if let w = v.window { Text("Fenêtre : \(w.start?.prefix(10) ?? "—") → \(w.end?.prefix(10) ?? "—") · barres de \(w.interval ?? "—")\(w.bars.map { " · \(Int($0)) barres" } ?? "")").font(.caption).foregroundStyle(.secondary) }119 if let c = v.checks, !c.isEmpty { Text("Contrôles : " + c.keys.sorted().map { "\($0) \(c[$0] ?? "")" }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary) }120 if v.engineParityApplied == false { Text("Les règles du moteur réel n’ont PAS été appliquées à ce backtest.").font(.caption).foregroundStyle(Theme.warning) }121 if v.installedHashMatches == false { Text("Le code installé sur le serveur ne correspond pas à celui qui a été testé.").font(.caption.weight(.semibold)).foregroundStyle(Theme.warning) }122 if v.results?.matchesManifest == false { Text("Le fichier de résultats ne correspond pas au manifeste du laboratoire.").font(.caption.weight(.semibold)).foregroundStyle(Theme.warning) }123 if let r = v.results { Text("Source : \(r.dir)/\(r.file ?? "summary.json")\(r.fileSha256.map { " · sha256 \($0.prefix(12))…" } ?? "")").font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }124 }125 }126127 private func scope(_ v: LabVerdict) -> String {128 switch v.scope {129 case "agent": v.liveCapable == true ? "Univers exécutable par un agent" : "Univers d’agent, papier seulement"130 case "backtest_only": "Backtest seulement"131 case "research_only": "Recherche seulement"132 case let s?: s133 case nil: "Portée non précisée"134 }135 }136 private func row(_ label: String, _ value: @escaping (LabVerdict.Split) -> String) -> some View {137 GridRow {138 Text(label)139 ForEach(Self.splits, id: \.self) { name in140 if let s = verdict.splits?[name] ?? nil { Text(value(s)).monospacedDigit() } else { Text("non fourni").foregroundStyle(.secondary) }141 }142 }143 }144}145146private struct RsLabStudy: View {147 let verdict: LabVerdict148 var body: some View {149 VStack(alignment: .leading, spacing: 5) {150 HStack { Text(verdict.name).font(Theme.mono).fontWeight(.semibold); Spacer(); ProvenanceTag(p: .simulated, text: verdict.fillsAreModelled == true ? "Étude · exécutions modélisées" : "Étude du laboratoire") }151 if let s = verdict.statement { Text(verbatim: s).font(.callout).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }152 else { Text("L’étude ne fournit pas d’énoncé.").font(.callout).foregroundStyle(.secondary) }153 Text("Énoncé de l’étude, repris tel quel de son fichier de résultats.").font(.caption).foregroundStyle(.secondary)154 if let a = verdict.assumptions, !a.isEmpty { Text("Hypothèses : " + a.joined(separator: " ; ")).font(.caption).foregroundStyle(.secondary) }155 if verdict.fillsAreModelled == true { Text("Les exécutions de cette étude sont MODÉLISÉES, pas observées.").font(.caption.weight(.semibold)).foregroundStyle(Theme.warning) }156 if let r = verdict.results { Text("Source : \(r.dir)/\(r.file ?? "—")\(r.matchesManifest == false ? " — ne correspond pas au manifeste" : "")").font(.caption).foregroundStyle(.secondary) }157 }158 }159}160