SPB Git

Repository Public

QuickCalcViews.swift 15.4 KB 268 lines swift

1//2//  VQuant iOS3//  File: VQuant/Next/QuickCalcViews.swift4//  Description: Quick financial calculations — option price and Greeks, VaR of a position, position sizing — as short5//               forms in front of the server engines (`options_lab`, `risk_lab`). The device only does the arithmetic6//               that turns an engine's result into an amount, and shows that formula.7//8//  Author: Simon-Pierre Boucher9//  Contact: contact@spboucher.ai10//1112import SwiftUI13import VQuantKit14import VQuantUI1516struct QuickCalcView: View {17    let kind: String18    var body: some View {19        switch kind {20        case "option": OptionQuickCalc()21        case "var": VaRQuickCalc()22        default: SizingQuickCalc()23        }24    }25}2627/// Runs one engine job and follows it to its result (shared by the three calculators).28@MainActor29@Observable30final class QuickRun {31    var job: VQQuantJob?32    var error: String?33    var isRunning = false34    private var task: Task<Void, Never>?3536    func run(_ model: AppModel, tool: String, params: VQJSONObject) {37        task?.cancel()38        error = nil; isRunning = true; job = nil39        task = Task {40            defer { isRunning = false }41            do {42                let started = try await model.next.lab.start(tool: tool, params: params)43                job = started44                for try await state in model.next.vq.lab.follow(started.id, every: 0.8) {45                    if Task.isCancelled { return }46                    job = state47                }48                if let j = job, let m = j.failureMessage { error = m }49                await model.next.lab.refreshJobs()50            } catch { if !Task.isCancelled { self.error = nextMessage(error) } }51        }52    }53    func stop() { task?.cancel() }54    var result: VQLabResult? { job?.labResult.flatMap { $0.success ? $0 : nil } }55}5657private func number(_ s: String) -> Double? {58    let t = s.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "\u{00A0}", with: "")59    return t.isEmpty ? nil : Double(t)60}6162private struct QuickScaffold<Inputs: View, Output: View>: View {63    @Environment(AppModel.self) private var model64    var title: String65    var intro: String66    var run: QuickRun67    var canRun: Bool68    var action: () -> Void69    @ViewBuilder var inputs: Inputs70    @ViewBuilder var output: Output7172    var body: some View {73        Form {74            Section { Text(intro).font(.footnote).foregroundStyle(Theme.textSecondary) }75            Section("Entrées") { inputs }76            Section {77                Button(action: action) {78                    HStack { if run.isRunning { ProgressView().controlSize(.small) }; Text(run.isRunning ? "Calcul sur le serveur…" : "Calculer") }.frame(maxWidth: .infinity)79                }80                .buttonStyle(EmberButtonStyle())81                .listRowInsets(EdgeInsets()).listRowBackground(Color.clear)82                .disabled(!canRun || run.isRunning).requiresNetwork(model.network.isOnline)83                .accessibilityIdentifier("quick-run")84            }85            if let e = run.error { Section { Label(e, systemImage: "exclamationmark.triangle").font(.footnote).foregroundStyle(Theme.down).accessibilityIdentifier("quick-error") } }86            if run.result != nil {87                Section("Résultat") { output }88                if let j = run.job {89                    Section {90                        RouteLink(.quantJob(j.id)) { Label("Ouvrir le résultat complet : graphiques, diagnostics, méthodologie, provenance", systemImage: "arrow.up.right.square") }91                            .accessibilityIdentifier("quick-open-job")92                    }93                }94            }95        }96        .navigationTitle(title).navigationBarTitleDisplayMode(.inline)97        .onDisappear { run.stop() }98        .accessibilityIdentifier("quick-calc")99    }100}101102private struct MetricRows: View {103    let metrics: [VQLabResult.Metric]104    var body: some View {105        ForEach(metrics) { m in106            HStack(alignment: .firstTextBaseline) {107                VStack(alignment: .leading, spacing: 2) {108                    Text(m.label).font(.subheadline)109                    if let n = m.note, !n.isEmpty { Text(n).font(.caption2).foregroundStyle(Theme.textSecondary) }110                }111                Spacer(minLength: 8)112                VStack(alignment: .trailing, spacing: 2) {113                    Text(m.formatted()).font(.mono(.callout, weight: .medium))114                    if let k = m.kind.known { VQKindBadge(k) }115                }116            }117            .accessibilityElement(children: .combine)118        }119    }120}121122struct OptionQuickCalc: View {123    @Environment(AppModel.self) private var model124    @State private var run = QuickRun()125    @State private var symbol = "AAPL"126    @State private var type = "call"127    @State private var style = "european"128    @State private var strike = ""129    @State private var days = 30130    @State private var volatility = ""131    @State private var rate = "4"132133    var body: some View {134        QuickScaffold(title: "Option", intro: "Prix théorique et grecques par le moteur Options Lab du serveur : Black-Scholes-Merton, arbre binomial de Cox-Ross-Rubinstein et Monte Carlo. Sans prix d’exercice, l’option est à la monnaie ; sans volatilité, le moteur prend la volatilité historique et le dit.",135                      run: run, canRun: WatchlistFile.normalise(symbol) != nil, action: calculate) {136            LabeledContent("Sous-jacent") { TextField("AAPL", text: $symbol).textInputAutocapitalization(.characters).autocorrectionDisabled().multilineTextAlignment(.trailing).font(.mono(.body)).accessibilityIdentifier("quick-symbol") }137                .symbolDrop { symbol = $0 }138            Picker("Type", selection: $type) { Text("Call").tag("call"); Text("Put").tag("put") }.pickerStyle(.segmented)139            Picker("Exercice", selection: $style) { Text("Européen").tag("european"); Text("Américain").tag("american") }.pickerStyle(.segmented)140            LabeledContent("Prix d’exercice") { TextField("à la monnaie", text: $strike).keyboardType(.decimalPad).multilineTextAlignment(.trailing).font(.mono(.body)).accessibilityIdentifier("quick-strike") }141            Stepper(value: $days, in: 1...3650, step: days < 30 ? 1 : days < 180 ? 15 : 30) { LabeledContent("Échéance") { Text("\(days) jours").font(.mono(.body)) } }142            LabeledContent("Volatilité (%)") { TextField("historique", text: $volatility).keyboardType(.decimalPad).multilineTextAlignment(.trailing).font(.mono(.body)) }143            LabeledContent("Taux sans risque (%)") { TextField("4", text: $rate).keyboardType(.numbersAndPunctuation).multilineTextAlignment(.trailing).font(.mono(.body)) }144        } output: {145            if let r = run.result {146                Text(r.headline).font(.footnote)147                MetricRows(metrics: r.summary)148            }149        }150    }151152    private func calculate() {153        guard let s = WatchlistFile.normalise(symbol) else { return }154        var p: VQJSONObject = ["symbol": .string(s), "mode": "price", "option_type": .string(type), "style": .string(style), "expiry_days": .number(Double(days))]155        if let k = number(strike) { p["strike"] = .number(k) }156        if let v = number(volatility) { p["volatility"] = .number(v / 100) }157        if let r = number(rate) { p["rate"] = .number(r / 100) }158        run.run(model, tool: "options_lab", params: p)159    }160}161162struct VaRQuickCalc: View {163    @Environment(AppModel.self) private var model164    @State private var run = QuickRun()165    @State private var symbol = "AAPL"166    @State private var value = "10000"167    @State private var confidence = 0.95168    @State private var horizon = 1169170    var body: some View {171        QuickScaffold(title: "VaR d’une position", intro: "Perte qui ne devrait pas être dépassée sur l’horizon, au niveau de confiance choisi, estimée par le Risk Lab du serveur selon plusieurs méthodes. Le montant est la VaR en pourcentage multipliée par la valeur que vous saisissez.",172                      run: run, canRun: WatchlistFile.normalise(symbol) != nil && (number(value) ?? 0) > 0, action: calculate) {173            LabeledContent("Titre") { TextField("AAPL", text: $symbol).textInputAutocapitalization(.characters).autocorrectionDisabled().multilineTextAlignment(.trailing).font(.mono(.body)).accessibilityIdentifier("quick-symbol") }174                .symbolDrop { symbol = $0 }175            LabeledContent("Valeur de la position") { TextField("10000", text: $value).keyboardType(.decimalPad).multilineTextAlignment(.trailing).font(.mono(.body)).accessibilityIdentifier("quick-value") }176            Picker("Confiance", selection: $confidence) { Text("90 %").tag(0.90); Text("95 %").tag(0.95); Text("99 %").tag(0.99) }.pickerStyle(.segmented)177            Stepper(value: $horizon, in: 1...250) { LabeledContent("Horizon") { Text("\(horizon) jour\(horizon > 1 ? "s" : "") de bourse").font(.mono(.body)) } }178        } output: {179            if let r = run.result, let v = number(value) {180                Text(r.headline).font(.footnote)181                if let t = r.tables.first(where: { $0.id == "var" }) {182                    ForEach(Array(t.rows.enumerated()), id: \.offset) { _, row in183                        let pct = row["var"]?.doubleValue, es = row["es"]?.doubleValue184                        VStack(alignment: .leading, spacing: 4) {185                            Text(row["method"]?.stringValue ?? "Méthode").font(.subheadline.weight(.medium))186                            HStack {187                                Text("VaR").foregroundStyle(Theme.textSecondary)188                                Spacer()189                                Text("\(VQFormat.percent(pct)) × \(VQFormat.currency(v)) = ").font(.mono(.caption)).foregroundStyle(Theme.textSecondary)190                                Text(VQFormat.currency(pct.map { $0 * v })).font(.mono(.callout, weight: .medium))191                            }192                            HStack {193                                Text("Perte moyenne au-delà (ES)").foregroundStyle(Theme.textSecondary)194                                Spacer()195                                Text(VQFormat.currency(es.map { $0 * v })).font(.mono(.callout))196                            }197                            if let s = row["scaling"]?.stringValue { Text("Mise à l’horizon : \(s)").font(.caption2).foregroundStyle(Theme.textSecondary) }198                        }199                        .font(.footnote)200                        .accessibilityElement(children: .combine)201                    }202                } else { MetricRows(metrics: Array(r.summary.prefix(4))) }203                Text("Les pourcentages sont calculés par le serveur sur les rendements observés ; les montants sont leur produit par la valeur saisie (devise de cotation du titre).").font(.caption2).foregroundStyle(Theme.textSecondary)204            }205        }206    }207208    private func calculate() {209        guard let s = WatchlistFile.normalise(symbol) else { return }210        run.run(model, tool: "risk_lab", params: ["symbols": VQJSON([s]), "confidence_levels": VQJSON([confidence]), "horizons": VQJSON([Double(horizon)])])211    }212}213214struct SizingQuickCalc: View {215    @Environment(AppModel.self) private var model216    @State private var run = QuickRun()217    @State private var symbol = "AAPL"218    @State private var capital = "100000"219    @State private var riskPercent = "1"220    @State private var confidence = 0.95221    @State private var horizon = 1222223    /// The sizing rule: the position whose VaR equals the risk budget. Pure arithmetic on the engine's VaR.224    static func size(capital: Double, riskFraction: Double, varFraction: Double, price: Double?) -> (budget: Double, value: Double, shares: Double?, weight: Double)? {225        guard capital > 0, riskFraction > 0, varFraction > 0 else { return nil }226        let budget = capital * riskFraction227        let value = budget / varFraction228        return (budget, value, price.flatMap { $0 > 0 ? (value / $0).rounded(.down) : nil }, value / capital)229    }230231    var body: some View {232        QuickScaffold(title: "Taille de position", intro: "Combien détenir pour que la perte possible de la position (sa VaR, mesurée par le Risk Lab du serveur) égale le risque que vous acceptez sur votre capital. C’est une règle de dimensionnement, pas une recommandation.",233                      run: run, canRun: WatchlistFile.normalise(symbol) != nil && (number(capital) ?? 0) > 0 && (number(riskPercent) ?? 0) > 0, action: calculate) {234            LabeledContent("Titre") { TextField("AAPL", text: $symbol).textInputAutocapitalization(.characters).autocorrectionDisabled().multilineTextAlignment(.trailing).font(.mono(.body)).accessibilityIdentifier("quick-symbol") }235                .symbolDrop { symbol = $0 }236            LabeledContent("Capital") { TextField("100000", text: $capital).keyboardType(.decimalPad).multilineTextAlignment(.trailing).font(.mono(.body)) }237            LabeledContent("Risque accepté (% du capital)") { TextField("1", text: $riskPercent).keyboardType(.decimalPad).multilineTextAlignment(.trailing).font(.mono(.body)) }238            Picker("Confiance", selection: $confidence) { Text("95 %").tag(0.95); Text("99 %").tag(0.99) }.pickerStyle(.segmented)239            Stepper(value: $horizon, in: 1...60) { LabeledContent("Horizon") { Text("\(horizon) jour\(horizon > 1 ? "s" : "")").font(.mono(.body)) } }240        } output: {241            if let r = run.result, let c = number(capital), let rp = number(riskPercent),242               let row = r.tables.first(where: { $0.id == "var" })?.rows.first, let v = row["var"]?.doubleValue {243                let price = model.market.quotes[WatchlistFile.normalise(symbol) ?? ""]?.value.price244                if let s = Self.size(capital: c, riskFraction: rp / 100, varFraction: v, price: price) {245                    KeyValueRow(key: "Budget de risque", value: VQFormat.currency(s.budget))246                    KeyValueRow(key: "VaR \(VQFormat.percent(confidence, decimals: 0)), \(horizon) j (\(row["method"]?.stringValue ?? "serveur"))", value: VQFormat.percent(v))247                    HStack {248                        Text("Position maximale").font(.subheadline.weight(.semibold))249                        Spacer()250                        Text(VQFormat.currency(s.value)).font(.mono(.title3, weight: .medium)).accessibilityIdentifier("sizing-value")251                    }252                    KeyValueRow(key: "Part du capital", value: VQFormat.percent(s.weight, decimals: 1))253                    if let shares = s.shares, let price { KeyValueRow(key: "Soit, au cours de \(Fmt.price(price))", value: "\(VQFormat.int(shares)) titres") }254                    Text("Position = budget de risque ÷ VaR = \(VQFormat.currency(s.budget)) ÷ \(VQFormat.percent(v)). La VaR est estimée sur l’historique : une perte plus grande reste possible (voir la perte moyenne au-delà dans le résultat complet).")255                        .font(.caption2).foregroundStyle(Theme.textSecondary)256                    if s.weight > 1 { Label("La position dépasse le capital : la règle demanderait un effet de levier.", systemImage: "exclamationmark.triangle").font(.caption).foregroundStyle(Theme.warning) }257                }258            }259        }260        .task(id: symbol) { if let s = WatchlistFile.normalise(symbol) { await model.market.refreshQuotes([s]) } }261    }262263    private func calculate() {264        guard let s = WatchlistFile.normalise(symbol) else { return }265        run.run(model, tool: "risk_lab", params: ["symbols": VQJSON([s]), "confidence_levels": VQJSON([confidence]), "horizons": VQJSON([Double(horizon)])])266    }267}268
Files main
Menu

Theme