Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Terminal/StatementsView.swift3// Description: Financial statements of a company (GET /api/v2/data/statements/:symbol): income, balance sheet, cash flow, ratios and growth by annual or quarterly period, a comparison of two periods, common-size view, and an inspector that shows how a derived line is calculated. Dense and tabular; values are the provider's, derived rows are the server's, nothing is estimated here.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910enum StatementTab: String, CaseIterable, Identifiable {11 case income, balance, cashflow, ratios, growth12 var id: String { rawValue }13 var title: String {14 switch self { case .income: "Income"; case .balance: "Balance sheet"; case .cashflow: "Cash flow"; case .ratios: "Ratios"; case .growth: "Growth" }15 }16 var hasCommonSize: Bool { self == .income || self == .balance }17}1819struct StatementsView: View {20 let app: AppEnvironment21 @Bindable var model: WindowModel2223 @State private var tab: StatementTab = .income24 @State private var period = "annual"25 @State private var limit = 826 @State private var commonSize = false27 @State private var comparing = false28 /// Indexes into `periods` (newest first): the change shown is `to − from`.29 @State private var fromIndex = 130 @State private var toIndex = 031 @State private var selectedKey: String?32 @State private var read: TerminalRead<VQStatements>?33 @State private var failure: String?34 @State private var loading = false35 @State private var scroll = CGPoint.zero36 @State private var launchApplied = false37 /// What currency lines are divided by on screen (1e6 = millions).38 @State private var divisor = 1.03940 private struct LoadKey: Hashable { var symbol: String; var period: String; var limit: Int }41 private typealias Row = VQStatements.Row4243 private static let labelWidth: CGFloat = 264, deltaWidth: CGFloat = 104, relWidth: CGFloat = 82, periodWidth: CGFloat = 10844 private static let rowHeight: CGFloat = 26, headerHeight: CGFloat = 4245 /// Totals and results a reader looks for first.46 private static let emphasised: Set<String> = ["revenue", "grossProfit", "operatingIncome", "netIncome", "ebitda", "totalCurrentAssets", "totalAssets", "totalCurrentLiabilities", "totalLiabilities",47 "totalStockholdersEquity", "totalEquity", "operatingCashFlow", "netCashProvidedByInvestingActivities", "netCashProvidedByFinancingActivities", "freeCashFlow"]4849 var body: some View {50 VStack(spacing: 0) {51 header52 Hairline(strong: true)53 if let s = read?.value, !s.periods.isEmpty {54 HStack(spacing: 0) {55 table(s).frame(maxWidth: .infinity, maxHeight: .infinity)56 Rectangle().fill(TP.line).frame(width: VQTokens.hairline)57 inspector(s).frame(width: 300)58 }59 } else if loading || (read == nil && failure == nil) {60 VStack(alignment: .leading) { VQSkeletonRows(rows: 12, columns: 6) }.padding(TS.s6).frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)61 } else {62 // an overlay: the empty state never takes part in the layout of the window63 Color.clear.overlay {64 VQEmptyState(systemImage: "doc.text.magnifyingglass", title: "No statements for \(model.symbol)", message: failure ?? "The provider returned no period.") {65 Button("Try Again") { Task { await load() } }66 }67 }68 .frame(maxWidth: .infinity, maxHeight: .infinity)69 .accessibilityIdentifier("statements.unavailable")70 }71 }72 .background(TP.ink0)73 .task(id: LoadKey(symbol: model.symbol, period: period, limit: limit)) { applyLaunchArguments(); await load() }74 .onChange(of: tab) { _, t in if !t.hasCommonSize { commonSize = false }; dropStaleSelection() }75 .onChange(of: commonSize) { _, _ in dropStaleSelection() }76 }7778 /// DEBUG launch arguments for captures: `-VQTab income|balance|cashflow|ratios|growth`, `-VQXStmtPeriod quarter`,79 /// `-VQXStmtLimit 12`, `-VQXStmtCommon 1`, `-VQXStmtCompare 1`, `-VQXStmtRow <key>`.80 private func applyLaunchArguments() {81 guard !launchApplied else { return }82 launchApplied = true83 let x = app.options.extra84 if let t = model.launchTab.flatMap(StatementTab.init(rawValue:)) { tab = t; model.launchTab = nil }85 if x["StmtPeriod"] == "quarter" { period = "quarter" }86 if let n = x["StmtLimit"].flatMap(Int.init), (1...40).contains(n) { limit = n }87 if x["StmtCommon"] != nil, tab.hasCommonSize { commonSize = true }88 if x["StmtCompare"] != nil { comparing = true }89 if let k = x["StmtRow"] { selectedKey = k }90 }9192 /// A line selected in one statement does not stay selected in another that does not have it.93 private func dropStaleSelection() {94 guard let s = read?.value, let k = selectedKey, !rows(s).contains(where: { $0.key == k }) else { return }95 selectedKey = nil96 }9798 private func load() async {99 loading = true; defer { loading = false }100 let symbol = model.symbol101 do {102 let r = try await app.terminal.statements(symbol, period: period, limit: limit)103 guard !Task.isCancelled, symbol == model.symbol else { return }104 divisor = Self.divisor(of: r.value)105 read = r; failure = nil106 let n = r.value.periods.count107 if toIndex >= n || fromIndex >= n || toIndex == fromIndex { toIndex = 0; fromIndex = min(1, max(0, n - 1)) }108 } catch is CancellationError {} catch {109 guard !Task.isCancelled else { return }110 read = nil; failure = (error as? VQError)?.userMessage ?? error.localizedDescription111 }112 }113114 // MARK: data on screen115116 private func rows(_ s: VQStatements?) -> [Row] {117 guard let s else { return [] }118 switch tab {119 case .income: return commonSize ? s.commonSizeIncome : s.income120 case .balance: return commonSize ? s.commonSizeBalance : s.balance121 case .cashflow: return s.cashflow122 case .ratios: return s.ratios123 case .growth: return s.growth124 }125 }126127 /// Currency lines are shown in millions (or thousands) when the company's figures are that large; the header says so.128 private func scale(_ s: VQStatements) -> (divisor: Double, word: String) { (divisor, divisor == 1e6 ? "millions" : divisor == 1e3 ? "thousands" : "units") }129130 /// Decided once per answer (every cell asks for it).131 private static func divisor(of s: VQStatements) -> Double {132 let top = (s.income + s.balance).filter { $0.unit == .currency }.flatMap(\.values).compactMap { $0.map(abs) }.max() ?? 0133 return top >= 1e9 ? 1e6 : top >= 1e7 ? 1e3 : 1134 }135136 private func text(_ v: Double?, _ row: Row, _ s: VQStatements) -> String {137 guard let v else { return VQFormat.nullText }138 let locale = app.vqTheme.numberLocale, k = scale(s)139 switch row.unit.known {140 case .currency?: return VQFormat.number(v / k.divisor, decimals: k.divisor == 1 ? 2 : 0, locale: locale)141 case .count?: return VQFormat.number(v / k.divisor, decimals: 0, locale: locale)142 case .percent?: return VQFormat.percent(v, decimals: 2, locale: locale)143 case .ratio?: return VQFormat.number(v, decimals: 2, locale: locale) + "×"144 case .perShare?: return VQFormat.number(v, decimals: 2, locale: locale)145 case nil: return VQFormat.number(v, decimals: 2, locale: locale)146 }147 }148149 private func absoluteText(_ v: Double?, _ row: Row, _ s: VQStatements) -> String {150 guard let v else { return VQFormat.nullText }151 let locale = app.vqTheme.numberLocale, k = scale(s)152 switch row.unit.known {153 case .currency?, .count?: return VQFormat.number(v / k.divisor, decimals: k.divisor == 1 && row.unit == .currency ? 2 : 0, signed: true, locale: locale)154 case .percent?: return VQFormat.number(v * 100, decimals: 2, signed: true, locale: locale) + "\u{00A0}pt" // a difference of rates is in points155 default: return VQFormat.number(v, decimals: 2, signed: true, locale: locale)156 }157 }158159 private func compareIndexes(_ s: VQStatements) -> (base: Int, value: Int)? {160 guard comparing, s.periods.indices.contains(fromIndex), s.periods.indices.contains(toIndex), fromIndex != toIndex else { return nil }161 return (fromIndex, toIndex)162 }163164 private func periodLabel(_ p: VQStatements.Period) -> String { p.label.isEmpty ? p.date : p.label }165166 // MARK: header167168 private var header: some View {169 let s = read?.value170 return VStack(alignment: .leading, spacing: TS.s3) {171 HStack(alignment: .firstTextBaseline, spacing: TS.s3) {172 Text(model.symbol).font(TT.displayMd.font).tracking(TT.displayMd.tracking).foregroundStyle(TP.text1).accessibilityIdentifier("statements.symbol")173 if let s {174 let k = scale(s)175 Text(commonSize ? "Common size: each line as a share of \(tab == .income ? "revenue" : "total assets")"176 : tab == .income || tab == .balance || tab == .cashflow ? "\(s.currency ?? "Reporting currency") \(k.word)\(tab == .income && k.divisor > 1 ? " · shares in \(k.word) · per-share in \(s.currency ?? "currency")" : "")"177 : tab == .ratios ? "Derived by VQuant from the reported lines" : "Change against the same period one year earlier")178 .font(TT.caption.font).foregroundStyle(TP.text2).lineLimit(1).accessibilityIdentifier("statements.caption")179 }180 Spacer(minLength: TS.s3)181 if let r = read, r.fromCache { CachedChip(received: r.receivedAt) }182 if let f = s?.provenance?.freshness { VQProvenanceChip(f) }183 Button { copy() } label: { Label("Copy", systemImage: "doc.on.doc") }.disabled(s == nil).help("Copy the table (tab-separated, values as received)")184 .accessibilityIdentifier("statements.copy")185 Button { export() } label: { Label("Export CSV…", systemImage: "square.and.arrow.up") }.disabled(s == nil).accessibilityIdentifier("statements.export")186 Button { ask() } label: { Label { Text("Ask the Agent") } icon: { Image(systemName: "sparkles").foregroundStyle(TP.accentText) } }.disabled(s == nil)187 .help("Hands this statement to the research agent as a prepared question; nothing is sent until you send it").accessibilityIdentifier("statements.ask")188 }189 .controlSize(.small)190 HStack(spacing: TS.s3) {191 VQSegmentedControl("Statement", selection: $tab, options: StatementTab.allCases.map { .init($0, $0.title) }).accessibilityIdentifier("statements.tabs")192 VQSegmentedControl("Period", selection: $period, options: [.init("annual", "Annual"), .init("quarter", "Quarterly")]).accessibilityIdentifier("statements.period")193 Picker("Periods", selection: $limit) { ForEach([4, 8, 12, 20, 40], id: \.self) { Text("\($0) periods").tag($0) } }194 .labelsHidden().fixedSize().help("Number of periods asked from the server").accessibilityIdentifier("statements.limit")195 Spacer(minLength: TS.s2)196 Toggle("Common size", isOn: $commonSize).toggleStyle(.button).disabled(!tab.hasCommonSize)197 .help(tab.hasCommonSize ? "Each line as a share of revenue (income) or total assets (balance sheet)" : "Common size applies to the income statement and the balance sheet")198 .accessibilityIdentifier("statements.commonsize")199 Toggle("Compare", isOn: $comparing).toggleStyle(.button).disabled((s?.periods.count ?? 0) < 2).help("Change between two periods, in value and in percent")200 .accessibilityIdentifier("statements.compare")201 }202 .controlSize(.small)203 if comparing, let s, s.periods.count >= 2 {204 HStack(spacing: TS.s2) {205 Text("Change from").font(TT.caption.font).foregroundStyle(TP.text2)206 periodPicker("From", $fromIndex, s)207 Text("to").font(TT.caption.font).foregroundStyle(TP.text2)208 periodPicker("To", $toIndex, s)209 if fromIndex == toIndex { Label("Pick two different periods", systemImage: "exclamationmark.circle").font(TT.caption.font).foregroundStyle(TP.warn) }210 else { Text("Δ = to − from · Δ % is left empty when the base is zero, negative or a rate").font(TT.caption.font).foregroundStyle(TP.text3).lineLimit(1) }211 Spacer()212 }213 .controlSize(.small)214 }215 }216 .padding(.horizontal, TS.s6).padding(.top, TS.s4).padding(.bottom, TS.s3)217 }218219 private func periodPicker(_ label: String, _ index: Binding<Int>, _ s: VQStatements) -> some View {220 Picker(label, selection: index) { ForEach(Array(s.periods.enumerated()), id: \.offset) { i, p in Text(periodLabel(p)).tag(i) } }221 .labelsHidden().fixedSize().accessibilityIdentifier("statements.compare.\(label.lowercased())")222 }223224 // MARK: table (sticky header row and label column)225226 private struct ScrollOrigin: PreferenceKey {227 static let defaultValue = CGPoint.zero228 static func reduce(value: inout CGPoint, nextValue: () -> CGPoint) { value = nextValue() }229 }230231 private func table(_ s: VQStatements) -> some View {232 let rows = self.rows(s)233 let cmp = compareIndexes(s)234 let sticky = Self.labelWidth + (cmp == nil ? 0 : Self.deltaWidth + Self.relWidth)235 let content = sticky + CGFloat(s.periods.count) * Self.periodWidth + TS.s4236 return GeometryReader { g in237 ScrollView([.horizontal, .vertical]) {238 ZStack(alignment: .topLeading) {239 // the two compared periods are tinted from top to bottom240 if let c = cmp {241 ForEach([c.base, c.value], id: \.self) { j in242 Rectangle().fill(TP.ink3.opacity(0.6)).frame(width: Self.periodWidth, height: Self.headerHeight + CGFloat(rows.count) * Self.rowHeight)243 .offset(x: sticky + CGFloat(j) * Self.periodWidth).accessibilityHidden(true)244 }245 }246 // the figures: one column per period, newest first247 VStack(spacing: 0) {248 Color.clear.frame(height: Self.headerHeight)249 ForEach(Array(rows.enumerated()), id: \.element.key) { i, row in250 HStack(spacing: 0) {251 Color.clear.frame(width: sticky)252 ForEach(Array(s.periods.enumerated()), id: \.offset) { j, _ in253 let v = row.values.indices.contains(j) ? row.values[j] : nil254 Text(text(v, row, s)).font(.system(size: 12, weight: Self.emphasised.contains(row.key) ? .semibold : .regular, design: .monospaced)).monospacedDigit()255 .foregroundStyle(v == nil ? TP.text3 : (v ?? 0) < 0 ? TP.text1 : TP.text1).lineLimit(1)256 .padding(.trailing, 12).frame(width: Self.periodWidth, alignment: .trailing)257 }258 Spacer(minLength: 0)259 }260 .frame(height: Self.rowHeight)261 .background(rowFill(row.key, i))262 .overlay(alignment: .bottom) { Hairline() }263 .contentShape(Rectangle())264 .onTapGesture { selectedKey = row.key }265 }266 }267 // the period header stays at the top268 HStack(spacing: 0) {269 Color.clear.frame(width: sticky)270 ForEach(Array(s.periods.enumerated()), id: \.offset) { j, p in271 VStack(alignment: .trailing, spacing: 1) {272 HStack(spacing: 4) {273 if let c = cmp, c.base == j || c.value == j {274 Text(c.value == j ? "TO" : "FROM").font(.system(size: 8.5, weight: .bold)).foregroundStyle(TP.accentText)275 }276 Text(periodLabel(p)).font(.system(size: 12, weight: .semibold)).foregroundStyle(TP.text1)277 }278 Text(p.date).font(.system(size: 10, design: .monospaced)).foregroundStyle(TP.text3)279 }280 .padding(.trailing, 12).frame(width: Self.periodWidth, height: Self.headerHeight, alignment: .trailing)281 .help(p.filingDate.map { "Period ending \(p.date), filed \($0)" } ?? "Period ending \(p.date)")282 }283 Spacer(minLength: 0)284 }285 .frame(height: Self.headerHeight)286 .background(TP.ink0)287 .overlay(alignment: .bottom) { Hairline(strong: true) }288 .offset(y: scroll.y).zIndex(2)289 // the labels (and the change columns) stay at the left290 VStack(spacing: 0) {291 Color.clear.frame(height: Self.headerHeight)292 ForEach(Array(rows.enumerated()), id: \.element.key) { i, row in293 HStack(spacing: 0) {294 labelCell(row)295 if let c = cmp { changeCells(row, c, s) }296 }297 .frame(width: sticky, height: Self.rowHeight)298 .background(rowFill(row.key, i)).background(TP.ink0)299 .overlay(alignment: .bottom) { Hairline() }300 .overlay(alignment: .leading) { if selectedKey == row.key { Rectangle().fill(TP.accent).frame(width: 2) } }301 }302 }303 .frame(width: sticky)304 .overlay(alignment: .trailing) { Rectangle().fill(TP.lineStrong).frame(width: VQTokens.hairline) }305 .offset(x: scroll.x).zIndex(3)306 // the corner307 HStack(spacing: 0) {308 Text(commonSize ? "\(tab.title), common size" : tab.title).font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3)309 .padding(.leading, TS.s6).frame(width: Self.labelWidth, alignment: .leading)310 if let c = cmp {311 Text("Δ").frame(width: Self.deltaWidth - 12, alignment: .trailing).padding(.trailing, 12)312 Text("Δ %").frame(width: Self.relWidth - 12, alignment: .trailing).padding(.trailing, 12)313 .help("\(periodLabel(s.periods[c.base])) → \(periodLabel(s.periods[c.value]))")314 }315 }316 .font(.system(size: 12, weight: .semibold)).foregroundStyle(TP.text1)317 .frame(width: sticky, height: Self.headerHeight)318 .background(TP.ink0)319 .overlay(alignment: .bottom) { Hairline(strong: true) }320 .overlay(alignment: .trailing) { Rectangle().fill(TP.lineStrong).frame(width: VQTokens.hairline) }321 .offset(x: scroll.x, y: scroll.y).zIndex(4)322 }323 .frame(minWidth: max(content, g.size.width), minHeight: g.size.height, alignment: .topLeading)324 .background(GeometryReader { inner in Color.clear.preference(key: ScrollOrigin.self, value: inner.frame(in: .named("statements.scroll")).origin) })325 }326 .coordinateSpace(name: "statements.scroll")327 .onPreferenceChange(ScrollOrigin.self) { o in328 let p = CGPoint(x: max(0, -o.x), y: max(0, -o.y))329 if p != scroll { scroll = p }330 }331 }332 .accessibilityIdentifier("statements.table")333 }334335 private func rowFill(_ key: String, _ index: Int) -> Color { selectedKey == key ? TP.ink4.opacity(0.7) : Color.clear }336337 private func labelCell(_ row: Row) -> some View {338 Button { selectedKey = row.key } label: {339 HStack(spacing: 5) {340 Text(row.label).font(.system(size: 12.5, weight: Self.emphasised.contains(row.key) ? .semibold : .regular)).foregroundStyle(TP.text1).lineLimit(1)341 if row.formula != nil {342 Text("ƒ").font(.system(size: 11, weight: .medium, design: .serif)).italic().foregroundStyle(TP.text3).help("Derived by VQuant: select the line to see its calculation")343 }344 Spacer(minLength: 0)345 }346 .padding(.leading, TS.s6).padding(.trailing, 8)347 .frame(width: Self.labelWidth, height: Self.rowHeight, alignment: .leading)348 .contentShape(Rectangle())349 }350 .buttonStyle(.plain)351 .help(row.label)352 .accessibilityLabel(row.label)353 .accessibilityAddTraits(selectedKey == row.key ? [.isButton, .isSelected] : .isButton)354 .accessibilityIdentifier("statements.row.\(row.key)")355 }356357 @ViewBuilder private func changeCells(_ row: Row, _ c: (base: Int, value: Int), _ s: VQStatements) -> some View {358 let ch = StatementMath.change(from: row.values.indices.contains(c.base) ? row.values[c.base] : nil, to: row.values.indices.contains(c.value) ? row.values[c.value] : nil, unit: row.unit.rawValue)359 TDelta(value: ch.absolute, text: absoluteText(ch.absolute, row, s)).padding(.trailing, 12).frame(width: Self.deltaWidth, alignment: .trailing)360 TDelta(value: ch.relative, text: VQFormat.percent(ch.relative, decimals: 1, signed: true, locale: app.vqTheme.numberLocale)).padding(.trailing, 12).frame(width: Self.relWidth, alignment: .trailing)361 }362363 // MARK: formula inspector364365 private func inspector(_ s: VQStatements) -> some View {366 let row = rows(s).first { $0.key == selectedKey }367 return ScrollView {368 VStack(alignment: .leading, spacing: TS.s4) {369 Text("Formula inspector").font(TT.overline.font).tracking(TT.overline.tracking).textCase(.uppercase).foregroundStyle(TP.text3)370 if let row { inspected(row, s) } else {371 Text("Select a line to see where it comes from: the provider's field for a reported line, the calculation and its inputs for a derived one.")372 .font(TT.bodySm.font).foregroundStyle(TP.text2).fixedSize(horizontal: false, vertical: true)373 if let notes = s.provenance?.notes, !notes.isEmpty {374 Hairline()375 ForEach(notes, id: \.self) { n in Text(n).font(TT.caption.font).foregroundStyle(TP.text3).fixedSize(horizontal: false, vertical: true) }376 }377 }378 }379 .padding(TS.s5)380 .frame(maxWidth: .infinity, alignment: .leading)381 }382 .background(TP.ink1)383 .accessibilityIdentifier("statements.inspector")384 }385386 @ViewBuilder private func inspected(_ row: Row, _ s: VQStatements) -> some View {387 let at = compareIndexes(s)?.value ?? 0388 let period = s.periods.indices.contains(at) ? periodLabel(s.periods[at]) : ""389 Text(row.label).font(TT.title.font).tracking(TT.title.tracking).foregroundStyle(TP.text1).fixedSize(horizontal: false, vertical: true)390 .accessibilityIdentifier("statements.inspector.title")391 if let formula = row.formula {392 let parts = StatementMath.splitNote(formula)393 fact("Origin", "Derived by VQuant from the reported lines")394 VStack(alignment: .leading, spacing: 6) {395 Text("Formula").font(TT.caption.font).foregroundStyle(TP.text3)396 Text(parts.expression).font(.system(size: 12, design: .monospaced)).foregroundStyle(TP.text1).textSelection(.enabled)397 .fixedSize(horizontal: false, vertical: true)398 .padding(10).frame(maxWidth: .infinity, alignment: .leading)399 .background(RoundedRectangle(cornerRadius: 6, style: .continuous).fill(TP.ink3))400 .accessibilityIdentifier("statements.inspector.formula")401 if let n = parts.note { Text(n.prefix(1).uppercased() + n.dropFirst() + ".").font(TT.caption.font).foregroundStyle(TP.text2).fixedSize(horizontal: false, vertical: true) }402 }403 let all = s.income + s.balance + s.cashflow404 let inputs = StatementMath.inputs(ofFormula: formula, known: Set(all.map(\.key)))405 if !inputs.isEmpty {406 VStack(alignment: .leading, spacing: 0) {407 Text("Inputs · \(period)").font(TT.caption.font).foregroundStyle(TP.text3).padding(.bottom, 4)408 ForEach(inputs, id: \.self) { key in409 if let input = all.first(where: { $0.key == key }) {410 Hairline()411 HStack(alignment: .firstTextBaseline) {412 VStack(alignment: .leading, spacing: 1) {413 Text(input.label).font(.system(size: 12)).foregroundStyle(TP.text1).lineLimit(2)414 Text(key).font(.system(size: 10, design: .monospaced)).foregroundStyle(TP.text3).lineLimit(1)415 }416 Spacer(minLength: 6)417 Text(text(input.values.indices.contains(at) ? input.values[at] : nil, input, s)).font(.system(size: 12, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1)418 }419 .padding(.vertical, 5)420 }421 }422 Hairline(strong: true)423 HStack {424 Text("Result").font(.system(size: 12, weight: .semibold)).foregroundStyle(TP.text1)425 Spacer()426 Text(text(row.values.indices.contains(at) ? row.values[at] : nil, row, s)).font(.system(size: 12, weight: .semibold, design: .monospaced)).monospacedDigit().foregroundStyle(TP.text1)427 }428 .padding(.vertical, 6)429 if row.values.indices.contains(at), row.values[at] == nil {430 Text("No value: an input is missing, or the denominator is zero or not meaningful for this period.").font(TT.caption.font).foregroundStyle(TP.text2).fixedSize(horizontal: false, vertical: true)431 }432 }433 }434 } else {435 fact("Origin", "Reported by the provider, field \(row.key)")436 Text("The value is shown as \(VQFreshness.providerName(s.provenance?.provider) ?? "the provider") reports it. A zero can mean the company does not report this line separately.")437 .font(TT.caption.font).foregroundStyle(TP.text2).fixedSize(horizontal: false, vertical: true)438 }439 fact("Unit", unitSentence(row, s))440 let series = Array(row.values.reversed())441 if series.compactMap({ $0 }).count > 1, let first = s.periods.last, let last = s.periods.first {442 VStack(alignment: .leading, spacing: 4) {443 Text("\(periodLabel(first)) → \(periodLabel(last))").font(TT.caption.font).foregroundStyle(TP.text3)444 VQSparkline(series, label: "\(row.label) over \(series.count) periods").scaleEffect(x: 2.4, y: 1.6, anchor: .leading).frame(width: 160, height: 30, alignment: .leading)445 }446 }447 }448449 private func fact(_ label: String, _ value: String) -> some View {450 VStack(alignment: .leading, spacing: 2) {451 Text(label).font(TT.caption.font).foregroundStyle(TP.text3)452 Text(value).font(TT.bodySm.font).foregroundStyle(TP.text1).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)453 }454 .accessibilityElement(children: .combine)455 .accessibilityIdentifier("statements.inspector.\(label.lowercased())")456 }457458 private func unitSentence(_ row: Row, _ s: VQStatements) -> String {459 let k = scale(s), cur = s.currency ?? "the reporting currency"460 switch row.unit.known {461 case .currency?: return k.divisor == 1 ? cur : "\(cur), shown in \(k.word)"462 case .count?: return k.divisor == 1 ? "A count" : "A count, shown in \(k.word)"463 case .percent?: return "A fraction, shown as a percentage (0.25 = 25 %)"464 case .ratio?: return "A ratio, shown as a multiple (×)"465 case .perShare?: return "\(cur) per share"466 case nil: return row.unit.rawValue467 }468 }469470 // MARK: copy, export, ask471472 private func csvRows(_ s: VQStatements) -> [StatementMath.CSVRow] {473 rows(s).map { StatementMath.CSVRow(label: $0.label, key: $0.key, unit: $0.unit.rawValue, values: $0.values, formula: $0.formula) }474 }475 private func csv(_ s: VQStatements) -> String {476 StatementMath.csv(periods: s.periods.map { "\(periodLabel($0)) (\($0.date))" }, rows: csvRows(s), compare: compareIndexes(s))477 }478479 private func copy() {480 guard let s = read?.value else { return }481 // tab-separated for spreadsheets: the same content as the CSV export482 let tsv = csv(s).components(separatedBy: "\r\n").map { line in Self.splitCSV(line).joined(separator: "\t") }.joined(separator: "\n")483 VQPasteboard.copy(tsv)484 app.toasts.show("\(tab.title) of \(s.symbol) copied (\(rows(s).count) lines).")485 }486487 /// Fields of one RFC 4180 line.488 private static func splitCSV(_ line: String) -> [String] {489 var out: [String] = [], cur = "", quoted = false490 var it = line.makeIterator()491 while let c = it.next() {492 if quoted { if c == "\"" { if let n = it.next() { if n == "\"" { cur.append("\"") } else { quoted = false; if n == "," { out.append(cur); cur = "" } else { cur.append(n) } } } else { quoted = false } } else { cur.append(c) } }493 else if c == "\"" { quoted = true } else if c == "," { out.append(cur); cur = "" } else { cur.append(c) }494 }495 out.append(cur)496 return out497 }498499 private func export() {500 guard let s = read?.value else { return }501 let name = "\(s.symbol)-\(tab.rawValue)\(commonSize ? "-common-size" : "")-\(period).csv"502 if let url = SavePanel.save(Data(csv(s).utf8), name: name, types: [.commaSeparatedText]) { app.toasts.show("Saved \(url.lastPathComponent).") }503 }504505 private func ask() {506 guard let s = read?.value else { return }507 let labels = s.periods.map(periodLabel)508 var context = "Statement on screen: \(tab.title.lowercased())\(commonSize ? " (common size)" : "") of \(s.symbol), \(period == "annual" ? "annual" : "quarterly") periods \(labels.joined(separator: ", ")); currency \(s.currency ?? "not stated"); source: VQuant data layer (/api/v2/data/statements), provider \(VQFreshness.providerName(s.provenance?.provider) ?? "unknown")."509 if let c = compareIndexes(s) { context += " The person is comparing \(labels[c.base]) with \(labels[c.value])." }510 if let row = rows(s).first(where: { $0.key == selectedKey }) { context += " Selected line: \(row.label) (\(row.key))\(row.formula.map { ", calculated as \($0)" } ?? "")." }511 model.ask(AskDraft(text: "Review the \(tab.title.lowercased()) of \(s.symbol): what are the main trends, and is anything unusual?", context: context))512 }513}514