Repository Public
1//2// VQuant iOS3// File: VQuant/Features/Markets/AssetView.swift4// Description: Asset screen: quote with its freshness, interactive chart, statistics, analytics, fundamentals, news,5// and the actions that start server-side work on this asset.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//1011import SwiftUI12import VQuantKit13import VQuantUI14import UniformTypeIdentifiers1516/// Bars of one symbol and range, with their provenance.17@MainActor18@Observable19final class ChartLoader {20 var bars: [Bar] = []21 var origin: DataOrigin?22 var isLoading = false23 var error: String?24 private var loadedKey = ""2526 func load(_ symbol: String, range: ChartRange, market: MarketStore, force: Bool = false) async {27 let key = "\(symbol)|\(range.rawValue)"28 if key == loadedKey && !force && !bars.isEmpty { return }29 isLoading = true; error = nil30 defer { isLoading = false }31 do {32 let l = try await market.bars(symbol, range: range)33 if Task.isCancelled { return }34 bars = l.value; origin = l.origin; loadedKey = key35 if l.value.isEmpty { error = "Le serveur n’a renvoyé aucune barre pour cette période." }36 } catch {37 let e = APIError.from(error)38 if e.kind != .cancelled { self.error = e.message; if key != loadedKey { bars = []; origin = nil } }39 }40 }41}4243struct AssetView: View {44 let symbol: String45 @Environment(AppModel.self) private var model46 @Environment(\.horizontalSizeClass) private var sizeClass47 @Environment(\.openWindow) private var openWindow48 @Environment(\.supportsMultipleWindows) private var multiWindow49 @State private var loader = ChartLoader()50 @State private var range: ChartRange = .quarter51 @State private var inspected: Bar?52 @State private var profile: CompanyProfile?53 @State private var news: [NewsItem] = []54 @State private var newsError: String?55 @State private var showFullScreen = false56 @State private var tab: DetailTab = .overview5758 enum DetailTab: String, CaseIterable, Identifiable {59 case overview = "Aperçu", analytics = "Analyse", fundamentals = "Fondamentaux", news = "Actualités"60 var id: String { rawValue }61 }6263 private var quote: Quote? { model.market.quotes[symbol]?.value }6465 var body: some View {66 Group {67 if sizeClass == .regular { padLayout } else { phoneLayout }68 }69 .background(Theme.background)70 .navigationTitle(symbol.replacingOccurrences(of: "^", with: ""))71 .navigationBarTitleDisplayMode(.inline)72 .toolbar { toolbar }73 .task(id: symbol) { await loadAll() }74 .task(id: range) { await loader.load(symbol, range: range, market: model.market) }75 .onAppear {76 range = model.preferences.chartRange77 model.startQuotePolling { [symbol] }78 }79 .onDisappear { model.stopQuotePolling() }80 .refreshable { await loadAll(force: true) }81 .fullScreenCover(isPresented: $showFullScreen) {82 ChartScreen(symbol: symbol, name: quote?.name, range: $range, loader: loader).environment(model)83 }84 .userActivity("ai.spboucher.vquant.asset") { a in85 a.title = "\(symbol) dans VQuant"; a.isEligibleForSearch = true; a.isEligibleForHandoff = false86 a.userInfo = ["symbol": symbol]87 }88 .accessibilityIdentifier("asset-\(symbol)")89 }9091 private func loadAll(force: Bool = false) async {92 async let q = model.market.refreshQuote(symbol)93 async let c: Void = loader.load(symbol, range: range, market: model.market, force: force)94 async let h: Void = refreshHoursIfNeeded()95 _ = await (q, c, h)96 if let p = try? await model.market.profile(symbol) { profile = p.value }97 do { news = try await model.market.news(symbol).value; newsError = nil } catch { newsError = APIError.from(error).message }98 }99100 private func refreshHoursIfNeeded() async {101 if model.market.hours.value == nil { await model.market.refreshOverview() }102 }103104 // MARK: layouts105106 private var phoneLayout: some View {107 ScrollView {108 VStack(alignment: .leading, spacing: 14) {109 OfflineBanner().clipShape(RoundedRectangle(cornerRadius: 10))110 header111 chartCard(height: 300)112 Picker("Section", selection: $tab) { ForEach(DetailTab.allCases) { Text($0.rawValue).tag($0) } }.pickerStyle(.segmented)113 detail(tab)114 }115 .padding(16)116 }117 }118119 /// iPad: chart on the left, a resizable inspector column on the right.120 private var padLayout: some View {121 HStack(spacing: 0) {122 ScrollView {123 VStack(alignment: .leading, spacing: 14) {124 OfflineBanner().clipShape(RoundedRectangle(cornerRadius: 10))125 header126 chartCard(height: 440)127 detail(.analytics)128 }129 .padding(20)130 }131 .frame(maxWidth: .infinity)132 Divider()133 ScrollView {134 VStack(alignment: .leading, spacing: 14) {135 Picker("Section", selection: $tab) {136 ForEach([DetailTab.overview, .fundamentals, .news]) { Text($0.rawValue).tag($0) }137 }138 .pickerStyle(.segmented)139 detail(tab == .analytics ? .overview : tab)140 }141 .padding(16)142 }143 .frame(width: 380)144 .background(Theme.surface2.opacity(0.4))145 }146 }147148 @ViewBuilder private func detail(_ t: DetailTab) -> some View {149 switch t {150 case .overview: statistics; actions; about151 case .analytics: AssetAnalytics(bars: loader.bars, intraday: range.isIntraday)152 case .fundamentals: FundamentalsView(symbol: symbol)153 case .news: newsList154 }155 }156157 // MARK: pieces158159 private var header: some View {160 VStack(alignment: .leading, spacing: 6) {161 if let n = quote?.name ?? profile?.companyName { Text(n).font(.subheadline).foregroundStyle(Theme.textSecondary) }162 if let b = inspected {163 HStack(alignment: .firstTextBaseline, spacing: 10) {164 Text(Fmt.price(b.close)).font(.system(.largeTitle, design: .rounded).weight(.semibold).monospacedDigit())165 Text(range.isIntraday ? Fmt.dateTime(b.date) : Fmt.day(b.date)).font(.subheadline).foregroundStyle(Theme.textSecondary)166 }167 Text("Observation du graphique").font(.caption).foregroundStyle(Theme.textSecondary)168 } else if let q = quote {169 HStack(alignment: .firstTextBaseline, spacing: 10) {170 Text(Fmt.price(q.price)).font(.system(.largeTitle, design: .rounded).weight(.semibold).monospacedDigit())171 .accessibilityIdentifier("asset-price")172 ChangeLabel(percent: q.changePercent, absolute: q.change)173 }174 HStack(spacing: 8) {175 if let f = model.market.quoteFreshness[symbol], model.market.quotes[symbol]?.isFromCache != true { ProvenanceChip(f) }176 else { FreshnessBadge(freshness: model.market.freshness(of: symbol)) }177 if let c = profile?.currency { Text(c).font(.caption).foregroundStyle(Theme.textSecondary) }178 }179 } else if let e = model.market.quoteErrors[symbol] {180 StateView(kind: .failed, title: "Cotation indisponible", message: e.message) { Task { await model.market.refreshQuote(symbol) } }181 } else {182 ProgressView()183 }184 }185 .frame(maxWidth: .infinity, alignment: .leading)186 }187188 private func chartCard(height: CGFloat) -> some View {189 VStack(alignment: .leading, spacing: 8) {190 HStack {191 Picker("Période", selection: $range) { ForEach(ChartRange.allCases) { Text($0.rawValue).tag($0) } }192 .pickerStyle(.segmented)193 .accessibilityIdentifier("range-picker")194 }195 ZStack {196 if loader.bars.isEmpty {197 if loader.isLoading { StateView(kind: .loading, title: "Chargement du graphique…") }198 else { StateView(kind: .failed, title: "Graphique indisponible", message: loader.error) { Task { await loader.load(symbol, range: range, market: model.market, force: true) } } }199 } else {200 PriceChartView(bars: loader.bars, configuration: model.preferences.chartConfiguration, intraday: range.isIntraday,201 previousClose: range == .day ? quote?.previousClose : nil,202 overlay: { scene in AnyView(DrawingLayer(scene: scene, drawings: ChartObject(model: model, symbol: symbol).drawings, tool: nil, selected: nil, onAdd: { _ in }, onSelect: { _ in }).allowsHitTesting(false)) },203 onInspect: { inspected = $0 })204 .opacity(loader.isLoading ? 0.5 : 1)205 }206 }207 .frame(height: height)208 HStack(spacing: 8) {209 ChartOptionsMenu()210 Spacer()211 if case .cache(let t)? = loader.origin { FreshnessBadge(freshness: .cached(savedAt: t), compact: true) }212 else if let p = model.market.provenance(symbol, range: range) { ProvenanceChip(p.freshness ?? VQFreshness(kind: .historical, asOf: p.retrievedAt, provider: p.provider)) }213 Text("\(loader.bars.count) observations\(range.interval.map { " · \($0.label)" } ?? " · quotidien")").font(.caption2).foregroundStyle(Theme.textSecondary).lineLimit(1)214 Button { showFullScreen = true } label: { Image(systemName: "arrow.up.left.and.arrow.down.right").frame(minWidth: 44, minHeight: 44).contentShape(Rectangle()) }215 .accessibilityLabel("Graphique en plein écran").accessibilityIdentifier("chart-fullscreen")216 }217 }218 .padding(12)219 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))220 .overlay(RoundedRectangle(cornerRadius: Theme.corner, style: .continuous).strokeBorder(Theme.border, lineWidth: 0.5))221 .onChange(of: range) { _, r in model.preferences.chartRange = r }222 }223224 @ViewBuilder private var statistics: some View {225 if let q = quote {226 Card("Séance", systemImage: "list.number") {227 VStack(spacing: 8) {228 KeyValueRow(key: "Ouverture", value: Fmt.price(q.open))229 KeyValueRow(key: "Clôture précédente", value: Fmt.price(q.previousClose))230 KeyValueRow(key: "Bas – haut du jour", value: "\(Fmt.price(q.dayLow)) – \(Fmt.price(q.dayHigh))")231 KeyValueRow(key: "Bas – haut 52 sem.", value: "\(Fmt.price(q.yearLow)) – \(Fmt.price(q.yearHigh))")232 KeyValueRow(key: "Volume", value: Fmt.compact(q.volume))233 if q.marketCap != nil { KeyValueRow(key: "Capitalisation", value: Fmt.compact(q.marketCap)) }234 if q.priceAvg50 != nil { KeyValueRow(key: "Moyennes 50 j / 200 j", value: "\(Fmt.price(q.priceAvg50)) / \(Fmt.price(q.priceAvg200))") }235 if let t = q.timestamp { KeyValueRow(key: "Dernière transaction", value: Fmt.dateTime(t)) }236 }237 }238 }239 }240241 private var actions: some View {242 Card("Travail sur le serveur", systemImage: "server.rack") {243 VStack(alignment: .leading, spacing: 10) {244 Button {245 model.router.compose(mode: .research, draft: "Étude complète de \(symbol) : activité, valorisation, risques et momentum récent.")246 } label: { Label("Confier une étude à l’agent", systemImage: "sparkles") }247 .accessibilityIdentifier("asset-analyse")248 RouteLink(.statements(symbol)) { Label("États financiers, ratios et croissance", systemImage: "tablecells") }.accessibilityIdentifier("asset-statements")249 RouteLink(.chart(symbol)) { Label("Graphique de travail et tracés", systemImage: "pencil.and.ruler") }.accessibilityIdentifier("asset-chart")250 Divider()251 DisclosureGroup("Moteurs du Quant Lab") {252 ForEach(model.next.lab.catalog.value?.tools.filter { t in t.params.contains { $0.name == "symbol" || $0.name == "symbols" } } ?? []) { tool in253 RouteLink(.quantTool("\(tool.id)|\(symbol)")) { Label(tool.title, systemImage: "function").frame(minHeight: 36) }254 }255 }256 .accessibilityIdentifier("asset-engines")257 }258 .requiresNetwork(model.network.isOnline)259 }260 .task { if model.next.lab.catalog.value == nil { await model.next.lab.refreshCatalog() } }261 }262263 @ViewBuilder private var about: some View {264 if let p = profile {265 Card("Société", systemImage: "building.2") {266 VStack(alignment: .leading, spacing: 8) {267 if let v = p.sector ?? p.industry { KeyValueRow(key: "Secteur", value: [p.sector, p.industry].compactMap { $0 }.joined(separator: " · ").isEmpty ? v : [p.sector, p.industry].compactMap { $0 }.joined(separator: " · ")) }268 if let v = p.exchangeFullName ?? p.exchange { KeyValueRow(key: "Place", value: v) }269 if let v = p.ceo { KeyValueRow(key: "Direction", value: v) }270 if let v = p.beta { KeyValueRow(key: "Bêta", value: Fmt.price(v)) }271 if let v = p.isin { KeyValueRow(key: "ISIN", value: v) }272 if let d = p.description, !d.isEmpty { Text(d).font(.footnote).foregroundStyle(Theme.textSecondary).lineLimit(8) }273 if let w = p.website, let url = URL(string: w), url.scheme == "https" { Link(destination: url) { Label(url.host() ?? w, systemImage: "safari").frame(minHeight: 44, alignment: .leading).contentShape(Rectangle()) }.font(.footnote).accessibilityLabel("Site web de la société").accessibilityHint("Ouvre le navigateur") }274 }275 }276 }277 }278279 @ViewBuilder private var newsList: some View {280 if news.isEmpty {281 StateView(kind: newsError == nil ? .empty : .failed, title: newsError == nil ? "Aucune actualité" : "Actualités indisponibles", message: newsError, systemImage: "newspaper")282 } else {283 VStack(spacing: 10) {284 ForEach(news.prefix(20)) { n in285 if let url = URL(string: n.url), url.scheme == "https" {286 Link(destination: url) {287 VStack(alignment: .leading, spacing: 4) {288 Text(n.title).font(.subheadline.weight(.medium)).multilineTextAlignment(.leading).foregroundStyle(.primary)289 Text([n.publisher ?? n.site, n.published.map { Fmt.relative($0) }].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(Theme.textSecondary)290 }291 .frame(maxWidth: .infinity, alignment: .leading)292 .padding(12).background(Theme.surface, in: RoundedRectangle(cornerRadius: 12))293 }294 .accessibilityHint("Ouvre l’article dans le navigateur")295 }296 }297 }298 }299 }300301 @ToolbarContentBuilder private var toolbar: some ToolbarContent {302 ToolbarItemGroup(placement: .topBarTrailing) {303 Button {304 model.watchlist.toggle(symbol, name: quote?.name ?? profile?.companyName)305 Haptics.tap()306 } label: {307 Image(systemName: model.watchlist.contains(symbol) ? "star.fill" : "star")308 }309 .accessibilityLabel(model.watchlist.contains(symbol) ? "Retirer de la liste de suivi" : "Ajouter à la liste de suivi")310 .accessibilityIdentifier("asset-star")311 if multiWindow {312 Button { openWindow(id: "route", value: Route.asset(symbol)) } label: { Image(systemName: "macwindow.badge.plus") }313 .accessibilityLabel("Ouvrir dans une nouvelle fenêtre")314 }315 }316 }317}318319/// Chart style, overlays and panels (stored in the preferences).320struct ChartOptionsMenu: View {321 @Environment(AppModel.self) private var model322 var body: some View {323 @Bindable var prefs = model.preferences324 Menu {325 Picker("Type", selection: $prefs.chartConfiguration.kind) {326 ForEach(ChartKind.allCases) { Label($0.label, systemImage: $0.systemImage).tag($0) }327 }328 Section("Indicateurs") {329 ForEach(ChartOverlay.allCases) { o in330 Toggle(o.label, isOn: Binding(get: { prefs.chartConfiguration.overlays.contains(o) },331 set: { if $0 { prefs.chartConfiguration.overlays.insert(o) } else { prefs.chartConfiguration.overlays.remove(o) } }))332 }333 }334 Section("Panneaux") {335 ForEach(ChartPanel.allCases) { p in336 Toggle(p.label, isOn: Binding(get: { prefs.chartConfiguration.panels.contains(p) },337 set: { if $0 { prefs.chartConfiguration.panels.insert(p) } else { prefs.chartConfiguration.panels.remove(p) } }))338 }339 }340 } label: {341 Label("Indicateurs", systemImage: "slider.horizontal.3").font(.footnote.weight(.medium)).frame(minHeight: 44).contentShape(Rectangle())342 }343 .menuActionDismissBehavior(.disabled)344 .accessibilityIdentifier("chart-options")345 }346}347348/// Descriptive statistics of the displayed window, computed on device from the bars the server returned.349struct AssetAnalytics: View {350 let bars: [Bar]351 let intraday: Bool352353 var body: some View {354 if bars.count < 30 {355 Card("Analyse", systemImage: "chart.bar.xaxis") {356 Text("Au moins 30 observations sont nécessaires. Choisissez une période plus longue.").font(.footnote).foregroundStyle(Theme.textSecondary)357 }358 } else {359 let closes = bars.map(\.close)360 // Annualisation only makes sense for daily bars; intraday windows are reported per period.361 let s = Indicators.summary(closes: closes, periodsPerYear: intraday ? 1 : 252)362 Card("Statistiques de la période", systemImage: "sum") {363 VStack(spacing: 8) {364 KeyValueRow(key: "Observations", value: "\(s.observations)")365 KeyValueRow(key: "Rendement total", value: Fmt.fraction(s.totalReturn))366 KeyValueRow(key: intraday ? "Volatilité par barre" : "Volatilité annualisée", value: Fmt.fraction(s.annualisedVolatility).replacingOccurrences(of: "+", with: ""))367 KeyValueRow(key: "Drawdown maximal", value: Fmt.fraction(s.maxDrawdown))368 KeyValueRow(key: "Meilleure / pire variation", value: "\(Fmt.fraction(s.bestDay)) / \(Fmt.fraction(s.worstDay))")369 KeyValueRow(key: "Asymétrie / kurtosis excédentaire", value: "\(Fmt.price(s.skewness)) / \(Fmt.price(s.excessKurtosis))")370 }371 Text("Calculé sur l’appareil à partir des observations affichées. Les modèles (GARCH, VaR, optimisation) s’exécutent sur le serveur, dans Calculs.")372 .font(.caption2).foregroundStyle(Theme.textSecondary)373 }374 Card("Distribution des rendements", systemImage: "chart.bar") { ReturnsHistogramChart(closes: closes).frame(height: 200) }375 Card("Drawdown", systemImage: "arrow.down.right") { DrawdownChart(bars: bars).frame(height: 180) }376 if !intraday { Card("Volatilité réalisée glissante (21 jours)", systemImage: "waveform.path.ecg") { RollingVolatilityChart(bars: bars).frame(height: 180) } }377 }378 }379}380381/// Full-screen chart: landscape-friendly, with the drawing tools (anchored to time and price, synced), sharing382/// (image, CSV) and "Demander à l’agent" on the visible window.383struct ChartScreen: View {384 let symbol: String385 var name: String?386 @Binding var range: ChartRange387 let loader: ChartLoader388 @Environment(\.dismiss) private var dismiss389390 struct ShareItem: Identifiable { let id = UUID(); let url: URL }391392 var body: some View {393 NavigationStack { ChartWorkstation(symbol: symbol, name: name, onClose: { dismiss() }) }394 }395}396397/// System share sheet.398struct ActivityView: UIViewControllerRepresentable {399 let items: [Any]400 func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: items, applicationActivities: nil) }401 func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}402}403404/// Fundamental tables exactly as the server returns them: one column per reported period, one row per field.405struct FundamentalsView: View {406 let symbol: String407 @Environment(AppModel.self) private var model408 @State private var table: FundamentalTable = .income409 @State private var records: [FundamentalRecord] = []410 @State private var origin: DataOrigin?411 @State private var error: String?412 @State private var loading = false413414 private static let titles: [FundamentalTable: String] = [415 .income: "Résultat", .balance: "Bilan", .cashFlow: "Flux de trésorerie", .metrics: "Métriques clés", .ratios: "Ratios", .estimates: "Estimations",416 .earnings: "Surprises de résultats", .dividends: "Dividendes", .holders: "Institutionnels", .insiders: "Initiés", .grades: "Recommandations", .targets: "Objectifs de cours",417 ]418419 var body: some View {420 VStack(alignment: .leading, spacing: 10) {421 Picker("Tableau", selection: $table) { ForEach(FundamentalTable.allCases) { Text(Self.titles[$0] ?? $0.rawValue).tag($0) } }422 .pickerStyle(.menu)423 .accessibilityIdentifier("fundamentals-picker")424 if loading && records.isEmpty { StateView(kind: .loading, title: "Chargement…") }425 else if let error, records.isEmpty { StateView(kind: .failed, title: "Données indisponibles", message: error) { Task { await load() } } }426 else if records.isEmpty { StateView(kind: .empty, title: "Aucune donnée", message: "Le fournisseur ne publie pas ce tableau pour \(symbol).", systemImage: "tablecells") }427 else {428 if case .cache(let t)? = origin { FreshnessBadge(freshness: .cached(savedAt: t)) }429 RecordTable(records: Array(records.prefix(8)))430 }431 }432 .task(id: table) { await load() }433 }434435 private func load() async {436 loading = true; defer { loading = false }437 do { let l = try await model.market.fundamentals(table, symbol: symbol); records = l.value; origin = l.origin; error = nil }438 catch let e { let a = APIError.from(e); if a.kind != .cancelled { error = a.message; records = [] } }439 }440}441442/// Generic records → a scrollable grid (fields in rows, records in columns).443struct RecordTable: View {444 let records: [FundamentalRecord]445446 private var columnTitles: [String] {447 records.map { r in448 let date = r["date"]?.stringValue ?? r["publishedDate"]?.stringValue ?? r["filingDate"]?.stringValue ?? ""449 let period = r["period"]?.stringValue450 return [String(date.prefix(10)), period].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " ")451 }452 }453 private var keys: [String] {454 let skip: Set<String> = ["symbol", "date", "period", "cik", "link", "finalLink", "filingDate", "acceptedDate", "reportedCurrency", "fiscalYear"]455 var seen = Set<String>(); var out: [String] = []456 for r in records { for k in r.keys.sorted() where !skip.contains(k) && !seen.contains(k) { seen.insert(k); out.append(k) } }457 return out458 }459460 var body: some View {461 let keys = keys, titles = columnTitles462 ScrollView(.horizontal) {463 Grid(alignment: .trailing, horizontalSpacing: 14, verticalSpacing: 6) {464 GridRow {465 Text(records.first?["reportedCurrency"]?.stringValue ?? "").font(.caption2).foregroundStyle(Theme.textSecondary).gridColumnAlignment(.leading)466 ForEach(Array(titles.enumerated()), id: \.offset) { _, t in Text(t.isEmpty ? "—" : t).font(.caption.weight(.semibold)) }467 }468 Divider()469 ForEach(keys, id: \.self) { k in470 GridRow {471 Text(Self.humanise(k)).font(.caption).foregroundStyle(Theme.textSecondary).lineLimit(2).frame(maxWidth: 170, alignment: .leading)472 ForEach(Array(records.enumerated()), id: \.offset) { _, r in Text(Self.cell(r[k])).font(.caption.monospacedDigit()) }473 }474 }475 }476 .padding(12)477 }478 .background(Theme.surface, in: RoundedRectangle(cornerRadius: Theme.corner, style: .continuous))479 }480481 /// `netIncomeRatio` → `Net income ratio` (the provider's field names, split at capitals).482 static func humanise(_ key: String) -> String {483 var out = ""484 for (i, c) in key.enumerated() {485 if c.isUppercase, i > 0, let last = out.last, !last.isUppercase, last != " " { out.append(" ") }486 out.append(i == 0 ? Character(c.uppercased()) : c)487 }488 return out.replacingOccurrences(of: "_", with: " ")489 }490 static func cell(_ v: JSONValue?) -> String {491 guard let v else { return "—" }492 if case .number(let n) = v { return abs(n) >= 1e5 ? Fmt.compact(n) : QuantResult.format(v) }493 let s = QuantResult.format(v)494 return s.count > 28 ? String(s.prefix(27)) + "…" : s495 }496}497