SPB Git

Repository Public

AgentStrategyViews.swift 16.0 KB 194 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/TradingAgents/AgentStrategyViews.swift3// Description: The strategy of an agent and its evidence: the versions pinned by the hash of their code, their backtest reports and the laboratory's verdicts. Every such figure is framed as RESEARCH — a simulation on historical data under stated assumptions, never a promise and never a track record — and the laboratory's own statement is shown verbatim, including when it found no edge.4import SwiftUI5import SPWalletCore67/// The label that precedes every backtest figure.8struct BacktestLabel: View {9    var note: String?10    var body: some View {11        let kind = ModeKind(.research)12        VStack(alignment: .leading, spacing: 4) {13            HStack(spacing: 8) { ModeTag(kind: kind); Text("BACKTEST").font(.caption.weight(.bold)).foregroundStyle(kind.color) }14            Text(note ?? "Backtest = simulation sur des données historiques, sous les hypothèses indiquées. Ce n’est ni un historique réel ni une promesse de rendement.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)15        }16    }17}1819/// The laboratory's out-of-sample verdict for a strategy, a study or a policy, as its files state it.20struct LabVerdictView: View {21    let verdict: LabVerdict22    var body: some View {23        let v = verdict, kind = ModeKind(.research)24        VStack(alignment: .leading, spacing: 8) {25            HStack(spacing: 8) {26                Text("Verdict du laboratoire — \(v.name)\(v.version.map { " \($0)" } ?? "")").font(.callout.weight(.semibold))27                ModeTag(kind: kind, compact: true)28                Text("BACKTEST").font(.caption2.weight(.bold)).foregroundStyle(kind.color)29            }30            if !v.available { Banner(.warning, "Résultat du laboratoire indisponible\(v.reason.map { " : \($0)" } ?? ".") Aucun chiffre n’est affiché.") }31            else {32                if let s = v.statement, !s.isEmpty { Banner(v.significant == true ? .info : .warning, "Énoncé du laboratoire : \(s)") }33                switch v.significant {34                case true?: Text("Selon la règle du laboratoire, le résultat hors échantillon dépasse son seuil. Cela reste une simulation : rien ne garantit qu’il se reproduise.").font(.callout).fixedSize(horizontal: false, vertical: true)35                case false?: Text("Selon la règle du laboratoire, AUCUN avantage statistiquement significatif n’a été trouvé hors échantillon.").font(.callout.weight(.medium)).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true)36                case nil: Text("Le laboratoire n’a pas tranché sur la significativité de ce résultat.").font(.callout).foregroundStyle(.secondary)37                }38                HStack(spacing: 10) {39                    ModeFigure(label: "Sharpe dégonflé", value: AgentText.number(v.deflatedSharpe, fraction: 3), kind: kind, reason: "non calculé")40                    ModeFigure(label: "Seuil du laboratoire", value: AgentText.number(v.deflatedSharpeThreshold, fraction: 3), kind: kind, reason: "non précisé")41                    ModeFigure(label: "Essais testés", value: AgentText.number(v.trialsTested, fraction: 0), kind: kind, reason: "non précisé")42                    if let ci = v.testSharpeCi, ci.count == 2 { ModeFigure(label: "IC du Sharpe (test)", value: "\(AgentText.number(ci[0]) ?? "—") à \(AgentText.number(ci[1]) ?? "—")", kind: kind) }43                }44                if let splits = v.splits {45                    ForEach(["train", "validation", "test"].filter { splits[$0] != nil }, id: \.self) { name in46                        if let s = splits[name] ?? nil {47                            HStack(alignment: .firstTextBaseline, spacing: 10) {48                                Text(name == "train" ? "Entraînement" : name == "validation" ? "Validation" : "Test (hors échantillon)").frame(width: 170, alignment: .leading).foregroundStyle(.secondary)49                                Text("rendement net \(AgentText.ratio(s.netReturn) ?? "—") · Sharpe net \(AgentText.number(s.netSharpe) ?? "—") (brut \(AgentText.number(s.grossSharpe) ?? "—")) · repli max. \(AgentText.ratio(s.maxDrawdown) ?? "—") · \(AgentText.number(s.trades, fraction: 0) ?? "—") transactions").font(.callout).monospacedDigit().fixedSize(horizontal: false, vertical: true)50                            }51                            if let st = s.stop { Text("Ce segment a été interrompu par la limite de perte du moteur ou une liquidation : \(st.reason) [\(st.code)]").font(.caption).foregroundStyle(Theme.warning) }52                        }53                    }54                }55                if v.fillsAreModelled == true { Text("Les exécutions de ce backtest sont modélisées, non observées.").font(.caption).foregroundStyle(.secondary) }56                if v.installedHashMatches == false { Banner(.warning, "Le code installé sur le serveur ne correspond PAS à celui que le laboratoire a évalué.") }57                if v.results?.matchesManifest == false { Banner(.warning, "Le fichier de résultats ne correspond pas au manifeste du laboratoire.") }58                DisclosureGroup("Hypothèses, fenêtre et portée") {59                    VStack(alignment: .leading, spacing: 4) {60                        if let w = v.window { Field(label: "Fenêtre", value: "\(w.start ?? "?") → \(w.end ?? "?") · pas \(w.interval ?? "?")\(w.bars.map { " · \(Int($0)) barres" } ?? "")") }61                        if let s = v.scope { Field(label: "Portée", value: "\(s)\(v.liveCapable.map { $0 ? " · peut passer en réel" : " · ne peut pas passer en réel" } ?? "")") }62                        if let sy = v.symbols, !sy.isEmpty { Field(label: "Marchés", value: sy.joined(separator: ", ")) }63                        if let c = v.checks, !c.isEmpty { Field(label: "Contrôles", value: c.keys.sorted().map { "\($0) : \(c[$0]!)" }.joined(separator: " · ")) }64                        ForEach(v.assumptions ?? [], id: \.self) { a in Text("• \(a)").font(.callout).fixedSize(horizontal: false, vertical: true) }65                        if let h = v.codeSha256 ?? v.sha256 { Field(label: "Code (SHA-256)", value: h, mono: true) }66                    }.padding(.top, 6)67                }68            }69        }70        .padding(10).frame(maxWidth: .infinity, alignment: .leading).modeFramed(kind)71        .background(kind.color.opacity(0.05), in: RoundedRectangle(cornerRadius: 8))72    }73}7475struct AgentStrategySection: View {76    let model: AppModel77    let d: AgentDetailStore78    let templates: AgentTemplates?7980    private var versions: [StrategyVersion] {81        switch d.detail { case .spot(let s): s.versions; case .perp(let p): p.versions; default: d.overview?.backtests.versions ?? [] }82    }83    private var template: AgentTemplate? { templates?.templates.first { $0.id == (d.agent?.template ?? d.summary?.template) } }8485    var body: some View {86        let kind = ModeKind(.research)87        Card("Stratégie en service") {88            if let s = d.summary?.strategy {89                Field(label: "Nom et version", value: "\(s.name) \(s.version)", emphasis: true)90                Field(label: "Nature", value: s.kind == "rule" ? "Règle intégrée au serveur" : "Code du laboratoire, épinglé par son empreinte")91                Field(label: "État", value: s.status)92                Field(label: "SHA-256", value: s.sha256, mono: true)93                if let p = s.path { Field(label: "Chemin", value: p, mono: true) }94            } else { Text(d.overview == nil ? "—" : "Aucune version de stratégie n’est rattachée à cet agent.").foregroundStyle(.secondary) }95            Text("Le serveur n’écrit jamais de code de stratégie : une version est choisie dans la bibliothèque du laboratoire, testée, puis approuvée par vous. Un mandat réel épingle l’empreinte de la version approuvée.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)96        }97        if let t = template, let verdicts = t.labVerdicts, !verdicts.isEmpty {98            Card("Rapport du laboratoire") { ForEach(Array(verdicts.enumerated()), id: \.offset) { _, v in LabVerdictView(verdict: v) } }99        }100        Card("Versions et backtests", trailing: AnyView(HStack { if let j = d.job, !j.status.isFinished { ProgressView().controlSize(.small); Text("Backtest \(j.status.rawValue)…").font(.caption).foregroundStyle(.secondary) } })) {101            BacktestLabel(note: d.overview?.backtests.note)102            if versions.isEmpty { Text("Aucune version rattachée. Choisissez-en une dans la bibliothèque ci-dessous : son backtest démarrera.").foregroundStyle(.secondary) }103            ForEach(versions) { v in versionBlock(v, kind) }104            if let r = d.overview?.backtests.recorded, !r.isNull {105                DisclosureGroup("Rejeu enregistré de la règle (simulation)") { JSONFacts(value: r, depth: 3).padding(.top, 6).modeFramed(kind) }106            }107            if let n = d.notice { Banner(.info, n) }108            if let e = d.actionError { Banner(.danger, e) }109        }110        if d.agent?.resolvedKind == .spot || d.agent?.resolvedKind == .perp {111            Card("Bibliothèque du laboratoire") {112                if let lib = d.library {113                    if lib.isEmpty { Text("La bibliothèque du serveur est vide.").foregroundStyle(.secondary) }114                    ForEach(lib) { s in115                        HStack(alignment: .top, spacing: 10) {116                            VStack(alignment: .leading, spacing: 2) {117                                Text("\(s.meta.name) \(s.meta.version)").fontWeight(.medium)118                                Text("Marchés : \(s.generic == true ? "ceux de l’agent (\(s.minSymbols ?? 1) à \(s.maxSymbols.map(String.init) ?? "?"))" : s.meta.universe.joined(separator: ", ")) · pas \(s.meta.interval)\(s.meta.maxLeverage.map { " · levier ≤ ×\(AgentCreateForm.plain($0))" } ?? "")").font(.caption).foregroundStyle(.secondary)119                                Text(s.sha256).font(.system(.caption2, design: .monospaced)).foregroundStyle(.tertiary).textSelection(.enabled)120                                if let r = s.readme, !r.isEmpty { Text(r).font(.caption).lineLimit(4).foregroundStyle(.secondary).textSelection(.enabled) }121                            }122                            Spacer()123                            ModeButton(title: "Rattacher et tester", kind: kind) { Task { await d.register(s) } }.disabled(!model.canOperate || d.busy != nil || d.agent?.mode == .live)124                        }125                        Divider()126                    }127                    Text("Rattacher une version lance son backtest. Cela n’approuve rien et ne donne aucune autorité.").font(.caption).foregroundStyle(.secondary)128                } else { Unavailable(what: "Bibliothèque", error: d.error("library")) }129            }130            .task { await d.loadLibrary() }131        }132    }133134    @ViewBuilder private func versionBlock(_ v: StrategyVersion, _ kind: ModeKind) -> some View {135        let current = v.id == d.agent?.strategyVersionId136        VStack(alignment: .leading, spacing: 6) {137            HStack(spacing: 8) {138                Text("\(v.name) \(v.version)").fontWeight(.semibold)139                Text(v.status).font(.caption.weight(.medium)).padding(.horizontal, 6).padding(.vertical, 2).background(Color.secondary.opacity(0.15), in: Capsule())140                if current { Text("en service").font(.caption.weight(.medium)).foregroundStyle(Theme.positive) }141                Spacer()142                Text(Fmt.date(v.createdAt)).font(.caption).foregroundStyle(.secondary)143            }144            Text(v.sha256).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)145            if v.isApproved { Text("Approuvée\(v.approvedAt.map { " le \(Fmt.date($0))" } ?? "")\(v.approvedBy.map { " par \($0)" } ?? "") — pour le papier ; l’approbation ne promet aucun résultat.").font(.caption).foregroundStyle(.secondary) }146            if let n = v.notes, !n.isEmpty { Text(n).font(.caption).foregroundStyle(.secondary) }147            if let p = v.perpSummary {148                if let pb = p.problem { Banner(.danger, "Cette version ne peut pas être approuvée : \(pb)") }149                if p.buyAndHoldIsSpot == false { Text("Référence « acheter et conserver » : prix du perpétuel lui-même (aucune bougie au comptant fournie).").font(.caption).foregroundStyle(Theme.warning) }150                if let m = p.metrics {151                    ForEach(["train", "validation", "test"].filter { m[$0] != nil }, id: \.self) { split in152                        if let x = m[split] ?? nil {153                            Text(split == "train" ? "Entraînement" : split == "validation" ? "Validation" : "Test (hors échantillon)").font(.caption.weight(.semibold)).foregroundStyle(kind.color)154                            JSONFacts(value: x, depth: 2)155                        }156                    }157                }158                if let l = p.liquidations, !l.isEmpty { Field(label: "Liquidations simulées", value: l.keys.sorted().map { "\($0) : \(l[$0]!)" }.joined(separator: " · ")) }159                DisclosureGroup("Modèle d’exécution, robustesse, biais des données, contrôles") {160                    VStack(alignment: .leading, spacing: 8) {161                        ForEach(Array([("Modèle d’exécution", p.executionModel), ("Parité avec le moteur", p.engineParity), ("Robustesse", p.robustness), ("Biais des données", p.dataBias), ("Contrôles", p.checks), ("Références", p.benchmarks)].enumerated()), id: \.offset) { _, b in162                            if let j = b.1, !j.isNull { Text(b.0).font(.caption.weight(.semibold)); JSONFacts(value: j, depth: 3) }163                        }164                    }.padding(.top, 6)165                }166            } else if v.simulation.isEmpty {167                Text(v.hasReport == false || v.status == "backtesting" ? "Backtest en cours ou pas encore de rapport : aucun chiffre." : "Aucun rapport de backtest pour cette version.").font(.callout).foregroundStyle(.secondary)168            } else {169                if let l = v.simulation.lookaheadCheck { Label("Contrôle d’anticipation (look-ahead) : \(l)", systemImage: l == "pass" ? "checkmark.circle" : "xmark.octagon").font(.caption).foregroundStyle(l == "pass" ? Theme.positive : Theme.negative) }170                Text("Métriques (\(v.simulation.label))").font(.caption.weight(.semibold)).foregroundStyle(kind.color)171                JSONFacts(value: v.simulation.metrics, depth: 3, empty: "Aucune métrique dans le rapport.")172                DisclosureGroup("Robustesse, références, hypothèses et contrôles") {173                    VStack(alignment: .leading, spacing: 8) {174                        ForEach(Array([("Robustesse", v.simulation.robustness), ("Références", v.simulation.benchmarks), ("Hypothèses", v.simulation.config), ("Contrôles", v.simulation.checks)].enumerated()), id: \.offset) { _, b in175                            if let j = b.1 { Text(b.0).font(.caption.weight(.semibold)); JSONFacts(value: j, depth: 3) }176                        }177                    }.padding(.top, 6)178                }179            }180            HStack(spacing: 10) {181                ModeButton(title: "Relancer le backtest", kind: kind, systemImage: "arrow.clockwise") { Task { await d.backtest(versionId: v.id) } }182                if !v.isApproved {183                    Button("Approuver cette version pour le papier") { Task { await d.approveVersion(v) } }184                        .disabled(v.perpSummary?.problem != nil || (v.perpSummary == nil && v.simulation.lookaheadCheck != "pass") || d.agent?.mode == .live)185                        .help("Sans passkey : approuver une version ne donne aucune autorité sur des fonds. Le serveur refuse une version sans rapport ou dont le contrôle d’anticipation a échoué.")186                }187                Spacer(minLength: 0)188            }.disabled(!model.canOperate || d.busy != nil)189        }190        .padding(10).frame(maxWidth: .infinity, alignment: .leading).modeFramed(kind)191        .background(kind.color.opacity(0.05), in: RoundedRectangle(cornerRadius: 8))192    }193}194
Files main
Menu

Theme