Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Portfolio/HoldingsPane.swift3// Description: Holdings of one portfolio: valuation from the data layer's quotes (grouped by currency, never converted on this Mac), allocation, and the dense table that edits positions in place, plus cash, add, CSV import and export.4import SwiftUI5import UniformTypeIdentifiers6import VQuantCore7import VQuantKit8import VQuantUI910struct HoldingsPane: View {11 let app: AppEnvironment12 let model: WindowModel13 let id: String14 let portfolio: VQPortfolio15 let importCSV: () -> Void16 let dropped: (URL) -> Void1718 @Environment(\.undoManager) private var undo19 @State private var newSymbol: String?20 @State private var newQuantity = ""21 @State private var newCost = ""22 @State private var dropTargeted = false23 @FocusState private var quantityFocused: Bool2425 private var store: PortfolioStore { app.portfolios }26 private var symbols: [String] { portfolio.positions.map(\.symbol) }27 private var locale: VQNumberLocale { app.numberLocale }2829 private var valuation: HoldingsValuation {30 var quotes: [String: HoldingQuote] = [:]31 for s in symbols { if let q = store.quotes[s] { quotes[s] = HoldingQuote(price: q.price, change: q.change, changePct: q.changePct, currency: q.currency, asOf: q.providerTimestamp) } }32 return HoldingsValuation(holdings: portfolio.positions.map { HoldingInput(symbol: $0.symbol, quantity: $0.quantity, costBasis: $0.costBasis, currency: $0.currency) },33 quotes: quotes, cash: portfolio.cash.map { ($0.currency, $0.amount) }, baseCurrency: portfolio.baseCurrency)34 }3536 var body: some View {37 let v = valuation38 ScrollView {39 VStack(alignment: .leading, spacing: VQTokens.Space.s5) {40 if let e = store.quoteError { NoticeBar(kind: .error, text: "Quotes: \(e)") { Task { await store.loadQuotes(symbols) } }.clipShape(RoundedRectangle(cornerRadius: VQTokens.Radius.sm)) }41 valuationBlock(v)42 if v.lines.contains(where: { ($0.marketValue ?? 0) != 0 }) { AllocationStrip(valuation: v, locale: locale) }43 table(v)44 addBar45 cashBlock46 footer47 }48 .padding(.horizontal, VQTokens.Space.s6).padding(.vertical, VQTokens.Space.s5)49 .frame(maxWidth: .infinity, alignment: .leading)50 }51 .overlay { if dropTargeted { RoundedRectangle(cornerRadius: VQTokens.Radius.md).strokeBorder(VQTokens.Palette.accent, style: StrokeStyle(lineWidth: 2, dash: [6, 4])).padding(8).allowsHitTesting(false) } }52 .dropDestination(for: URL.self) { urls, _ in53 guard let u = urls.first(where: { ["csv", "tsv", "txt"].contains($0.pathExtension.lowercased()) }) else { return false }54 dropped(u); return true55 } isTargeted: { dropTargeted = $0 }56 .task(id: symbols) {57 // polled, never streamed: refreshed at the person's cadence while the pane is on screen58 while !Task.isCancelled {59 await store.loadQuotes(symbols)60 let every = app.settings.quoteRefresh61 try? await Task.sleep(for: .seconds(every > 0 ? max(10, every) : 3600))62 }63 }64 }6566 // MARK: valuation6768 @ViewBuilder private func valuationBlock(_ v: HoldingsValuation) -> some View {69 VStack(alignment: .leading, spacing: VQTokens.Space.s3) {70 HStack(alignment: .firstTextBaseline, spacing: VQTokens.Space.s3) {71 Text("Valuation").font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1)72 freshnessChip(v)73 if store.loadingQuotes { ProgressView().controlSize(.mini) }74 Spacer()75 Button { importCSV() } label: { Label("Import CSV…", systemImage: "square.and.arrow.down") }.accessibilityIdentifier("portfolio.import")76 Button { exportCSV(v) } label: { Label("Export CSV", systemImage: "square.and.arrow.up") }.disabled(portfolio.positions.isEmpty)77 if id == VQObjectID.mainPortfolio { Button { model.show(.risk) } label: { Label("Risk Analytics", systemImage: "gauge.with.dots.needle.67percent") }.disabled(portfolio.positions.isEmpty) }78 }79 .controlSize(.small)80 if v.groups.isEmpty {81 Text(portfolio.positions.isEmpty ? "No position yet. Add one below, or import a CSV file (drop it here)." : "No quote received yet for these positions.")82 .font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text2)83 } else if v.isSingleCurrency, let g = v.groups.first {84 HStack(alignment: .top, spacing: 0) {85 figure("Market value · \(g.currency)", VQFormat.number(g.marketValue, decimals: 2, locale: locale), large: true)86 figure("Day change", g.dayChange.map { VQFormat.number($0, decimals: 2, signed: true, locale: locale) } ?? VQFormat.nullText, sub: g.dayChangePercent.map { VQFormat.percentValue($0, signed: true, locale: locale) }, color: app.settings.changeColor(g.dayChange))87 figure("Cost", g.cost.map { VQFormat.number($0, decimals: 2, locale: locale) } ?? VQFormat.nullText)88 figure("Unrealised P&L", g.pnl.map { VQFormat.number($0, decimals: 2, signed: true, locale: locale) } ?? VQFormat.nullText, sub: g.pnlPercent.map { VQFormat.percentValue($0, signed: true, locale: locale) }, color: app.settings.changeColor(g.pnl))89 figure("Cash", VQFormat.number(g.cash, decimals: 2, locale: locale))90 figure("Total with cash", VQFormat.number(g.total, decimals: 2, locale: locale))91 }92 if g.currency != portfolio.baseCurrency.uppercased() {93 note("Amounts are in \(g.currency), the currency of the quotes — not converted to the base currency \(portfolio.baseCurrency). The Analysis tab values the portfolio in \(portfolio.baseCurrency) with the exchange rate it states.")94 }95 } else {96 currencyTable(v)97 note("These positions are quoted in \(v.groups.count) currencies. Amounts are grouped by currency and never added together: this Mac applies no exchange rate. The Analysis tab values the whole portfolio in \(portfolio.baseCurrency) with the exchange rates it states.")98 }99 if !v.unpriced.isEmpty { note("No quote for \(v.unpriced.joined(separator: ", ")): unavailable, left out of every total.", color: VQTokens.Palette.warn) }100 if v.groups.contains(where: { $0.positions > 0 && $0.cost == nil }) { note("Cost and P&L totals are shown only when every priced position of a currency has a cost basis.") }101 }102 }103104 @ViewBuilder private func freshnessChip(_ v: HoldingsValuation) -> some View {105 let held = symbols.compactMap { store.quotes[$0] }106 if !held.isEmpty {107 let delayed = held.contains { $0.freshness?.known == .delayed }108 let providers = Array(Set(held.compactMap(\.provider))).sorted()109 VQProvenanceChip(kind: delayed ? .delayed : .polled, provider: providers.count == 1 ? providers[0] : nil, asOf: v.asOf)110 .help("The valuation is as recent as its oldest quote. Quotes are polled over HTTPS; this is not a streaming feed.")111 }112 }113114 private func figure(_ label: String, _ value: String, sub: String? = nil, color: Color = VQTokens.Palette.text1, large: Bool = false) -> some View {115 VStack(alignment: .leading, spacing: 3) {116 Overline(label)117 Text(value).font((large ? VQTokens.Typography.numLg : VQTokens.Typography.numMd).font).foregroundStyle(color).lineLimit(1).minimumScaleFactor(0.6)118 if let sub { Text(sub).font(VQTokens.Typography.numSm.font).foregroundStyle(color) }119 }120 .frame(maxWidth: .infinity, alignment: .leading)121 .accessibilityElement(children: .combine)122 }123124 private func note(_ text: String, color: Color = VQTokens.Palette.text3) -> some View {125 Text(text).font(VQTokens.Typography.caption.font).foregroundStyle(color).fixedSize(horizontal: false, vertical: true)126 }127128 private func currencyTable(_ v: HoldingsValuation) -> some View {129 VStack(spacing: 0) {130 HStack(spacing: 0) {131 head("Currency", 90, .leading); head("Positions", 80); head("Market value", nil); head("Day change", nil); head("Cost", nil); head("P&L", nil); head("Cash", nil); head("Total", nil)132 }133 .padding(.vertical, 5)134 Hairline(strong: true)135 ForEach(v.groups) { g in136 HStack(spacing: 0) {137 HStack(spacing: 6) {138 Text(g.currency).font(VQTokens.Typography.numMd.font)139 if g.currency == portfolio.baseCurrency.uppercased() { Text("BASE").font(VQTokens.Typography.overline.font).foregroundStyle(VQTokens.Palette.text3) }140 }.frame(width: 90, alignment: .leading)141 num(String(g.positions), 80)142 num(VQFormat.number(g.marketValue, decimals: 2, locale: locale), nil)143 num(g.dayChange.map { VQFormat.number($0, decimals: 2, signed: true, locale: locale) } ?? VQFormat.nullText, nil, app.settings.changeColor(g.dayChange))144 num(g.cost.map { VQFormat.number($0, decimals: 2, locale: locale) } ?? VQFormat.nullText, nil)145 num(g.pnl.map { VQFormat.number($0, decimals: 2, signed: true, locale: locale) } ?? VQFormat.nullText, nil, app.settings.changeColor(g.pnl))146 num(VQFormat.number(g.cash, decimals: 2, locale: locale), nil)147 num(VQFormat.number(g.total, decimals: 2, locale: locale), nil).fontWeight(.semibold)148 }149 .padding(.vertical, 6)150 Hairline()151 }152 }153 }154155 private func head(_ t: String, _ width: CGFloat?, _ a: Alignment = .trailing) -> some View {156 Overline(t).frame(width: width, alignment: a).frame(maxWidth: width == nil ? .infinity : nil, alignment: a)157 }158 private func num(_ t: String, _ width: CGFloat?, _ color: Color = VQTokens.Palette.text1) -> some View {159 Text(t).font(VQTokens.Typography.numSm.font).foregroundStyle(color).lineLimit(1).frame(width: width, alignment: .trailing).frame(maxWidth: width == nil ? .infinity : nil, alignment: .trailing)160 }161162 // MARK: positions table (edited in place)163164 private enum Col {165 static let symbol: CGFloat = 96, qty: CGFloat = 64, cost: CGFloat = 70, ccy: CGFloat = 40, price: CGFloat = 72, day: CGFloat = 78, value: CGFloat = 88, pnl: CGFloat = 88, weight: CGFloat = 64, opened: CGFloat = 86, remove: CGFloat = 24166 static let minWidth: CGFloat = symbol + qty + cost + ccy + price + day + value + pnl + weight + opened + 90 + remove167 }168169 private func table(_ v: HoldingsValuation) -> some View {170 VStack(alignment: .leading, spacing: VQTokens.Space.s2) {171 HStack(alignment: .firstTextBaseline) {172 Text("Positions").font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1)173 Text(v.isSingleCurrency ? "Quantity, cost, currency, date and note are edited in place · ⌘Z undoes" : "Edited in place · ⌘Z undoes · weights are shares of the positions of the same currency").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3)174 }175 ScrollView(.horizontal, showsIndicators: false) {176 VStack(spacing: 0) {177 HStack(spacing: 0) {178 head("Symbol", Col.symbol, .leading); head("Quantity", Col.qty); head("Cost", Col.cost); head("Ccy", Col.ccy, .center); head("Price", Col.price); head("Day %", Col.day)179 head("Value", Col.value); head("P&L", Col.pnl); head("Weight", Col.weight); head("Opened", Col.opened, .center)180 Overline("Note").padding(.leading, 8).frame(maxWidth: .infinity, alignment: .leading)181 Color.clear.frame(width: Col.remove, height: 1)182 }183 .padding(.vertical, 5)184 Hairline(strong: true)185 if v.lines.isEmpty {186 Text("No position.").font(VQTokens.Typography.bodySm.font).foregroundStyle(VQTokens.Palette.text3).frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 14)187 Hairline()188 }189 ForEach(v.lines) { line in190 row(line)191 Hairline()192 }193 }194 .frame(minWidth: Col.minWidth)195 .containerRelativeFrame(.horizontal) { w, _ in max(w, Col.minWidth) }196 }197 }198 }199200 private func row(_ l: HoldingsValuation.Line) -> some View {201 let s = l.holding.symbol202 let pos = portfolio.position(s)203 let quote = store.quotes[s]204 let unavailable = store.missing.contains(s)205 return HStack(spacing: 0) {206 VStack(alignment: .leading, spacing: 0) {207 Text(s).font(VQTokens.Typography.numMd.font).foregroundStyle(VQTokens.Palette.text1).lineLimit(1)208 Text(unavailable ? "Unavailable" : (quote?.name ?? " ")).font(.system(size: 10)).foregroundStyle(unavailable ? VQTokens.Palette.warn : VQTokens.Palette.text3).lineLimit(1)209 }210 .frame(width: Col.symbol, alignment: .leading)211 .help(unavailable ? "No provider quoted \(s): it is left out of every total." : (quote?.name ?? s))212 InlineField(value: PlainNumber.text(l.holding.quantity), alignment: .trailing, role: VQTokens.Typography.numSm, identifier: "position.qty.\(s)") { t in213 guard let q = PortfolioImport.number(t), q != 0 else { app.toasts.show("A quantity is a number other than zero. Remove the position to close it.", error: true); return false }214 edit(s, "Change Quantity") { $0.quantity = q }; return true215 }.frame(width: Col.qty)216 InlineField(value: PlainNumber.text(l.holding.costBasis), placeholder: "—", alignment: .trailing, role: VQTokens.Typography.numSm, identifier: "position.cost.\(s)") { t in217 if t.trimmingCharacters(in: .whitespaces).isEmpty { edit(s, "Clear Cost Basis") { $0.costBasis = nil }; return true }218 guard let c = PortfolioImport.number(t), c >= 0 else { app.toasts.show("The cost basis is a positive number per unit.", error: true); return false }219 edit(s, "Change Cost Basis") { $0.costBasis = c }; return true220 }.frame(width: Col.cost)221 InlineField(value: pos?.currency ?? "", placeholder: quote?.currency ?? "—", alignment: .center, role: VQTokens.Typography.numSm, color: VQTokens.Palette.text2, identifier: "position.ccy.\(s)") { t in222 let c = t.trimmingCharacters(in: .whitespaces).uppercased()223 if c.isEmpty { edit(s, "Clear Currency") { $0.currency = nil }; return true }224 guard c.count == 3, c.allSatisfy({ $0.isASCII && $0.isLetter }) else { app.toasts.show("A currency is a 3-letter code.", error: true); return false }225 edit(s, "Change Currency") { $0.currency = c }; return true226 }227 .frame(width: Col.ccy)228 .help(quote?.currency.map { "Quoted in \($0). A currency recorded here is passed to the analysis; the valuation uses the quote’s." } ?? "Currency of the position")229 num(quote?.price.map { VQFormat.number($0, decimals: abs($0) >= 1 ? 2 : 4, locale: locale) } ?? VQFormat.nullText, Col.price)230 Group { if let c = quote?.changePct { VQDelta(percentPoints: c) } else { Text(VQFormat.nullText).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3) } }.frame(width: Col.day, alignment: .trailing)231 num(l.marketValue.map { VQFormat.number($0, decimals: 2, locale: locale) } ?? VQFormat.nullText, Col.value)232 VStack(alignment: .trailing, spacing: 0) {233 Text(l.pnl.map { VQFormat.number($0, decimals: 2, signed: true, locale: locale) } ?? VQFormat.nullText).font(VQTokens.Typography.numSm.font)234 if let pc = l.pnlPercent { Text(VQFormat.percentValue(pc, decimals: 1, signed: true, locale: locale)).font(.system(size: 10, design: .monospaced)) }235 }236 .foregroundStyle(l.pnl == nil ? VQTokens.Palette.text3 : app.settings.changeColor(l.pnl)).lineLimit(1).frame(width: Col.pnl, alignment: .trailing)237 num(l.weight.map { VQFormat.percentValue($0, decimals: 1, locale: locale) } ?? VQFormat.nullText, Col.weight, VQTokens.Palette.text2)238 InlineField(value: PlainNumber.day(pos?.openedAt), placeholder: "—", alignment: .center, role: VQTokens.Typography.numSm, color: VQTokens.Palette.text2, identifier: "position.opened.\(s)") { t in239 if t.trimmingCharacters(in: .whitespaces).isEmpty { edit(s, "Clear Opened Date") { $0.openedAt = nil }; return true }240 guard let d = PortfolioImport.date(t) else { app.toasts.show("Write the date as YYYY-MM-DD.", error: true); return false }241 edit(s, "Change Opened Date") { $0.openedAt = d }; return true242 }.frame(width: Col.opened).help("Date the position was opened (YYYY-MM-DD)")243 InlineField(value: pos?.note ?? "", placeholder: "—", color: VQTokens.Palette.text2, identifier: "position.note.\(s)") { t in244 let n = t.trimmingCharacters(in: .whitespaces)245 edit(s, "Change Note") { $0.note = n.isEmpty ? nil : n }; return true246 }247 .frame(maxWidth: .infinity).padding(.leading, 2)248 Button { remove(s) } label: { Image(systemName: "minus.circle").font(.system(size: 12)) }249 .buttonStyle(.borderless).foregroundStyle(VQTokens.Palette.text3).help("Remove \(s) from this portfolio (nothing is sold)")250 .frame(width: Col.remove)251 .accessibilityIdentifier("position.remove.\(s)")252 }253 .frame(height: 34)254 .contentShape(Rectangle())255 .contextMenu {256 Button("Chart \(s)") { model.show(.charting, symbol: s) }257 Button("Statements of \(s)") { model.show(.statements, symbol: s) }258 Divider()259 Button("Remove Position", role: .destructive) { remove(s) }260 }261 .accessibilityElement(children: .contain)262 .accessibilityIdentifier("position.row.\(s)")263 }264265 // MARK: add, cash, footer266267 private var addBar: some View {268 HStack(spacing: VQTokens.Space.s2) {269 if let s = newSymbol {270 HStack(spacing: 4) {271 Text(s).font(VQTokens.Typography.numMd.font)272 Button { newSymbol = nil } label: { Image(systemName: "xmark.circle.fill").font(.system(size: 11)) }.buttonStyle(.borderless).foregroundStyle(VQTokens.Palette.text3)273 }274 .padding(.horizontal, 8).padding(.vertical, 4).background(RoundedRectangle(cornerRadius: 6).fill(VQTokens.Palette.ink3))275 .accessibilityElement(children: .contain)276 .accessibilityIdentifier("position.new.symbol")277 } else {278 SymbolSearchField(app: app, placeholder: "Add a position: symbol or company") { s in279 if portfolio.position(s) != nil { app.toasts.show("\(s) is already in this portfolio: edit its quantity in the table.", error: true) } else { newSymbol = s; quantityFocused = true }280 }281 .frame(width: 280)282 }283 TextField("Quantity", text: $newQuantity).textFieldStyle(.roundedBorder).frame(width: 96).focused($quantityFocused).onSubmit { add() }284 .accessibilityIdentifier("position.new.quantity")285 TextField("Cost per unit (optional)", text: $newCost).textFieldStyle(.roundedBorder).frame(width: 170).onSubmit { add() }286 .accessibilityIdentifier("position.new.cost")287 Button("Add Position") { add() }.disabled(newSymbol == nil || newQuantity.trimmingCharacters(in: .whitespaces).isEmpty)288 .accessibilityIdentifier("position.new.add")289 Spacer()290 }291 .controlSize(.small)292 }293294 private var cashBlock: some View {295 VStack(alignment: .leading, spacing: VQTokens.Space.s2) {296 Text("Cash").font(VQTokens.Typography.title.font).foregroundStyle(VQTokens.Palette.text1)297 HStack(spacing: VQTokens.Space.s2) {298 ForEach(Array(portfolio.cash.enumerated()), id: \.offset) { i, c in299 HStack(spacing: 0) {300 InlineField(value: c.currency, placeholder: "CCY", alignment: .center, role: VQTokens.Typography.numSm, color: VQTokens.Palette.text2, identifier: "cash.currency.\(i)") { t in301 let cur = t.trimmingCharacters(in: .whitespaces).uppercased()302 guard cur.count == 3, cur.allSatisfy({ $0.isASCII && $0.isLetter }) else { app.toasts.show("A currency is a 3-letter code.", error: true); return false }303 editCash("Change Cash Currency") { $0[i].currency = cur }; return true304 }.frame(width: 46)305 InlineField(value: PlainNumber.text(c.amount), placeholder: "0", alignment: .trailing, role: VQTokens.Typography.numSm, identifier: "cash.amount.\(i)") { t in306 guard let a = PortfolioImport.number(t) else { app.toasts.show("The cash balance is a number.", error: true); return false }307 editCash("Change Cash") { $0[i].amount = a }; return true308 }.frame(width: 96)309 Button { editCash("Remove Cash") { $0.remove(at: i) } } label: { Image(systemName: "xmark").font(.system(size: 9, weight: .semibold)) }310 .buttonStyle(.borderless).foregroundStyle(VQTokens.Palette.text3).padding(.trailing, 6).help("Remove this balance")311 }312 .overlay(RoundedRectangle(cornerRadius: 6).strokeBorder(VQTokens.Palette.line))313 }314 Button { addCash() } label: { Label("Add a balance", systemImage: "plus") }.controlSize(.small).accessibilityIdentifier("cash.add")315 Spacer()316 }317 }318 }319320 private var footer: some View {321 Text("Record of holdings only — no brokerage connection, no order placement. Quotes come from the VQuant data layer (polled, stamped by the provider); positions are saved in your account and synced across your devices.")322 .font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3).fixedSize(horizontal: false, vertical: true)323 }324325 // MARK: edits (the typed value is edited, the whole value is saved: unknown keys stay)326327 private func edit(_ symbol: String, _ action: String, _ change: (inout VQPortfolio.Position) -> Void) {328 var p = portfolio329 var list = p.positions330 guard let i = list.firstIndex(where: { $0.symbol == symbol }) else { return }331 change(&list[i]); p.positions = list332 store.write(p, id: id, action: action, undo: undo)333 }334335 private func editCash(_ action: String, _ change: (inout [VQPortfolio.Cash]) -> Void) {336 var p = portfolio337 var list = p.cash338 change(&list); p.cash = list339 store.write(p, id: id, action: action, undo: undo)340 }341342 private func addCash() {343 let used = Set(portfolio.cash.map(\.currency))344 let next = ([portfolio.baseCurrency.uppercased(), "USD", "CAD", "EUR", "GBP", "JPY", "CHF"].first { !used.contains($0) }) ?? "XXX"345 editCash("Add Cash") { $0.append(VQPortfolio.Cash(currency: next, amount: 0)) }346 }347348 private func remove(_ symbol: String) {349 var p = portfolio350 p.removePosition(symbol)351 store.write(p, id: id, action: "Remove \(symbol)", undo: undo)352 }353354 private func add() {355 guard let s = newSymbol else { return }356 guard let q = PortfolioImport.number(newQuantity), q != 0 else { app.toasts.show("Enter a quantity (a number other than zero).", error: true); return }357 var cb: Double?358 if !newCost.trimmingCharacters(in: .whitespaces).isEmpty {359 guard let c = PortfolioImport.number(newCost), c >= 0 else { app.toasts.show("The cost basis is a positive number per unit.", error: true); return }360 cb = c361 }362 var p = portfolio363 p.upsert(VQPortfolio.Position(symbol: s, quantity: q, costBasis: cb))364 store.write(p, id: id, action: "Add \(s)", undo: undo)365 newSymbol = nil; newQuantity = ""; newCost = ""366 }367368 private func exportCSV(_ v: HoldingsValuation) {369 var out = "symbol,quantity,cost_basis,currency,price,quote_time,market_value,unrealized_pnl,weight_percent_in_currency,opened,note\r\n"370 let iso = ISO8601DateFormatter()371 for l in v.lines {372 let pos = portfolio.position(l.holding.symbol)373 let fields: [String] = [l.holding.symbol, PlainNumber.text(l.holding.quantity), PlainNumber.text(l.holding.costBasis), l.currency == HoldingsValuation.unknownCurrency ? "" : l.currency,374 l.quote?.price.map { String($0) } ?? "", l.quote?.asOf.map { iso.string(from: $0) } ?? "", l.marketValue.map { String($0) } ?? "", l.pnl.map { String($0) } ?? "",375 l.weight.map { String($0) } ?? "", PlainNumber.day(pos?.openedAt), pos?.note ?? ""]376 out += fields.map(CSV.field).joined(separator: ",") + "\r\n"377 }378 let name = portfolio.name.isEmpty ? "portfolio" : portfolio.name.replacingOccurrences(of: "/", with: "-")379 SavePanel.save(Data(out.utf8), name: "vquant-\(name).csv", types: [.commaSeparatedText])380 }381}382383/// Allocation of the priced positions as one bar per currency (shares of that currency's gross market value).384private struct AllocationStrip: View {385 let valuation: HoldingsValuation386 let locale: VQNumberLocale387388 var body: some View {389 VStack(alignment: .leading, spacing: VQTokens.Space.s2) {390 ForEach(valuation.groups.filter { $0.positions > 0 }) { g in391 let lines = valuation.lines.filter { $0.currency == g.currency && ($0.weight ?? 0) > 0 }.sorted { ($0.weight ?? 0) > ($1.weight ?? 0) }392 VStack(alignment: .leading, spacing: 5) {393 HStack(spacing: 6) {394 Overline(valuation.isSingleCurrency ? "Allocation by market value" : "Allocation · \(g.currency) positions")395 Spacer()396 }397 GeometryReader { geo in398 HStack(spacing: 1) {399 ForEach(Array(lines.enumerated()), id: \.element.id) { i, l in400 Rectangle().fill(color(i)).frame(width: max(1, (geo.size.width - CGFloat(lines.count - 1)) * CGFloat((l.weight ?? 0) / 100)))401 .help("\(l.holding.symbol) · \(VQFormat.percentValue(l.weight, decimals: 1, locale: locale))")402 }403 }404 .clipShape(RoundedRectangle(cornerRadius: 3))405 }406 .frame(height: 10)407 FlowLegend(items: Array(lines.prefix(12).enumerated()).map { i, l in (color(i), l.holding.symbol, VQFormat.percentValue(l.weight, decimals: 1, locale: locale)) }, more: max(0, lines.count - 12))408 }409 .accessibilityElement(children: .combine)410 .accessibilityLabel("Allocation in \(g.currency): " + lines.prefix(8).map { "\($0.holding.symbol) \(Int(($0.weight ?? 0).rounded())) percent" }.joined(separator: ", "))411 }412 }413 }414415 private func color(_ i: Int) -> Color {416 let c = VQTokens.DataPalette.categorical417 return i < c.count ? c[i] : VQTokens.Palette.text3.opacity(0.5)418 }419}420421private struct FlowLegend: View {422 let items: [(Color, String, String)]423 let more: Int424 var body: some View {425 HStack(spacing: VQTokens.Space.s3) {426 ForEach(Array(items.enumerated()), id: \.offset) { _, it in427 HStack(spacing: 4) {428 RoundedRectangle(cornerRadius: 2).fill(it.0).frame(width: 8, height: 8)429 Text(it.1).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text1)430 Text(it.2).font(VQTokens.Typography.numSm.font).foregroundStyle(VQTokens.Palette.text3)431 }432 .fixedSize()433 }434 if more > 0 { Text("+ \(more) more").font(VQTokens.Typography.caption.font).foregroundStyle(VQTokens.Palette.text3) }435 Spacer(minLength: 0)436 }437 .lineLimit(1)438 .clipped()439 }440}441