SPB Git

Repository Public

Charts.swift 15.1 KB 351 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraUI/Charts.swift8// Module           : Qyvora UI9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import SwiftUI42import Charts4344/// One observation of a price series.45public struct ChartPoint: Sendable, Equatable, Identifiable {46    public let date: Date47    public let value: Double48    public var id: Date { date }4950    public init(date: Date, value: Double) {51        self.date = date52        self.value = value53    }54}5556/// Ranges offered by the price chart. The caller loads the series of the selected range.57public enum PriceRange: String, Sendable, CaseIterable, Identifiable {58    case day = "1D", week = "7D", month = "30D", year = "1Y"5960    public var id: String { rawValue }6162    public var spokenName: String {63        switch self {64        case .day: return "One day"65        case .week: return "Seven days"66        case .month: return "Thirty days"67        case .year: return "One year"68        }69    }70}7172/// Pure helpers of the chart views.73public enum SeriesMath {74    /// Relative change between the first and the last value; nil when it cannot be computed.75    public static func change(_ values: [Double]) -> Double? {76        guard values.count >= 2, let first = values.first, let last = values.last, first != 0, first.isFinite, last.isFinite else { return nil }77        return (last - first) / first78    }7980    /// Keeps finite values only. A series needs two points to be drawn.81    public static func drawable(_ values: [Double]) -> [Double]? {82        let finite = values.filter(\.isFinite)83        return finite.count >= 2 ? finite : nil84    }8586    /// "+2.41%", "−0.80%", "0.00%".87    public static func percentText(_ change: Double) -> String {88        let percent = change * 10089        let magnitude = String(format: "%.2f", abs(percent))90        if magnitude == "0.00" { return "0.00%" }91        return (percent > 0 ? "+" : "−") + magnitude + "%"92    }9394    /// Index of the point whose date is closest to `date`.95    public static func nearestIndex(in points: [ChartPoint], to date: Date) -> Int? {96        guard !points.isEmpty else { return nil }97        var best = 098        var bestDistance = Double.infinity99        for (i, p) in points.enumerated() {100            let d = abs(p.date.timeIntervalSince(date))101            if d < bestDistance {102                best = i103                bestDistance = d104            }105        }106        return best107    }108}109110/// Small trend line without axes. With fewer than two values it shows a dash and says that there is no data.111public struct SparklineView: View {112    let values: [Double]113    let color: Color?114115    /// - Parameter color: line colour; by default the line is green when the series rose and red when it fell116    ///   (the direction is also spoken, and callers normally print the change next to it).117    public init(values: [Double], color: Color? = nil) {118        self.values = values119        self.color = color120    }121122    public var body: some View {123        if let series = SeriesMath.drawable(values) {124            let change = SeriesMath.change(series) ?? 0125            let tint = color ?? (change >= 0 ? QColor.positive : QColor.negative)126            let low = series.min() ?? 0, high = series.max() ?? 1127            Chart(Array(series.enumerated()), id: \.offset) { item in128                LineMark(x: .value("Index", item.offset), y: .value("Value", item.element))129                    .interpolationMethod(.monotone)130                    .lineStyle(StrokeStyle(lineWidth: 1.6, lineCap: .round, lineJoin: .round))131                    .foregroundStyle(tint)132            }133            .chartXAxis(.hidden)134            .chartYAxis(.hidden)135            .chartLegend(.hidden)136            .chartYScale(domain: low == high ? (low - 1)...(high + 1) : low...high)137            .accessibilityElement(children: .ignore)138            .accessibilityLabel("Trend")139            .accessibilityValue(change > 0 ? "Up \(SeriesMath.percentText(change))" : (change < 0 ? "Down \(SeriesMath.percentText(change))" : "Flat"))140        } else {141            Text("–")142                .font(QFont.caption)143                .foregroundStyle(QColor.textTertiary)144                .frame(maxWidth: .infinity, maxHeight: .infinity)145                .accessibilityLabel("No trend data")146        }147    }148}149150/// Price chart with scrubbing and a range picker. It draws only the points it is given: while loading it shows151/// progress, and without data it says so with the reason supplied by the caller.152public struct PriceChartView: View {153    let points: [ChartPoint]154    @Binding var range: PriceRange155    let ranges: [PriceRange]156    let isLoading: Bool157    let unavailableReason: String?158    let format: (Double) -> String159    let onRetry: (() -> Void)?160161    @State private var selectedDate: Date?162    @State private var scrubFeedback = 0163    @Namespace private var rangeNamespace164    @Environment(\.accessibilityReduceMotion) private var reduceMotion165    @ScaledMetric(relativeTo: .body) private var chartHeight: CGFloat = 200166167    /// - Parameters:168    ///   - points: the series of the selected range, oldest first. Empty while unknown.169    ///   - range: selected range; the caller reloads `points` when it changes.170    ///   - unavailableReason: why there is no series (no price endpoint configured, request failed…).171    ///   - format: formats a value of the series for display (currency and precision are the caller's).172    public init(points: [ChartPoint], range: Binding<PriceRange>, ranges: [PriceRange] = PriceRange.allCases, isLoading: Bool = false,173                unavailableReason: String? = nil, format: @escaping (Double) -> String, onRetry: (() -> Void)? = nil) {174        self.points = points175        self._range = range176        self.ranges = ranges177        self.isLoading = isLoading178        self.unavailableReason = unavailableReason179        self.format = format180        self.onRetry = onRetry181    }182183    var drawable: [ChartPoint] { points.filter { $0.value.isFinite } }184185    var selected: ChartPoint? {186        guard let selectedDate, let i = SeriesMath.nearestIndex(in: drawable, to: selectedDate) else { return nil }187        return drawable[i]188    }189190    public var body: some View {191        VStack(alignment: .leading, spacing: 14) {192            let series = drawable193            if series.count >= 2 {194                header(series)195                chart(series)196                    .frame(height: chartHeight)197                    .opacity(isLoading ? 0.4 : 1)198            } else if isLoading {199                ProgressView("Loading price history")200                    .font(QFont.callout)201                    .frame(maxWidth: .infinity)202                    .frame(height: chartHeight)203            } else {204                UnavailableDataView(reason: unavailableReason ?? "No price history was returned for this range.",205                                    title: "Price history unavailable", retry: onRetry)206                    .frame(minHeight: chartHeight)207            }208            rangePicker209        }210        .sensoryFeedback(.selection, trigger: scrubFeedback)211    }212213    func header(_ series: [ChartPoint]) -> some View {214        let shown = selected ?? series[series.count - 1]215        let change = SeriesMath.change(series.prefix { $0.date <= shown.date }.map(\.value)) ?? SeriesMath.change(series.map(\.value))216        return VStack(alignment: .leading, spacing: 4) {217            Text(format(shown.value))218                .font(Font.system(.title, design: .rounded, weight: .semibold).monospacedDigit())219                .foregroundStyle(QColor.textPrimary)220                .contentTransition(.numericText())221                .lineLimit(1)222                .minimumScaleFactor(0.6)223            HStack(spacing: 8) {224                if let change {225                    Label(SeriesMath.percentText(change), systemImage: change > 0 ? "arrow.up.right" : (change < 0 ? "arrow.down.right" : "arrow.right"))226                        .font(QFont.callout.monospacedDigit().weight(.medium))227                        .foregroundStyle(change > 0 ? QColor.positive : (change < 0 ? QColor.negative : QColor.textSecondary))228                        .contentTransition(.numericText())229                }230                Text(selected == nil ? range.spokenName.lowercased() : shown.date.formatted(date: .abbreviated, time: range == .day || range == .week ? .shortened : .omitted))231                    .font(QFont.callout)232                    .foregroundStyle(QColor.textSecondary)233            }234        }235        .animation(reduceMotion ? nil : .snappy(duration: 0.15), value: shown)236        .accessibilityElement(children: .combine)237    }238239    func chart(_ series: [ChartPoint]) -> some View {240        let low = series.map(\.value).min() ?? 0, high = series.map(\.value).max() ?? 1241        let pad = low == high ? max(abs(low) * 0.01, 1) : (high - low) * 0.08242        return Chart {243            ForEach(series) { p in244                AreaMark(x: .value("Date", p.date), yStart: .value("Low", low - pad), yEnd: .value("Price", p.value))245                    .interpolationMethod(.monotone)246                    .foregroundStyle(LinearGradient(colors: [QColor.violet.opacity(0.16), QColor.violet.opacity(0)], startPoint: .top, endPoint: .bottom))247                LineMark(x: .value("Date", p.date), y: .value("Price", p.value))248                    .interpolationMethod(.monotone)249                    .lineStyle(StrokeStyle(lineWidth: 2, lineCap: .round, lineJoin: .round))250                    .foregroundStyle(QColor.violet)251            }252            if let selected {253                RuleMark(x: .value("Date", selected.date))254                    .lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 3]))255                    .foregroundStyle(QColor.textSecondary)256                PointMark(x: .value("Date", selected.date), y: .value("Price", selected.value))257                    .symbolSize(70)258                    .foregroundStyle(QColor.violet)259                PointMark(x: .value("Date", selected.date), y: .value("Price", selected.value))260                    .symbolSize(18)261                    .foregroundStyle(QColor.background)262            }263        }264        .chartYScale(domain: (low - pad)...(high + pad))265        .chartXAxis {266            AxisMarks(preset: .aligned, values: .automatic(desiredCount: 3)) { _ in267                AxisValueLabel(format: axisDateFormat, collisionResolution: .greedy(minimumSpacing: 12))268                    .font(QFont.caption)269                    .foregroundStyle(QColor.textTertiary)270            }271        }272        .chartYAxis {273            AxisMarks(position: .trailing, values: .automatic(desiredCount: 3)) { value in274                AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5)).foregroundStyle(QColor.stroke)275                AxisValueLabel {276                    if let v = value.as(Double.self) {277                        Text(format(v)).font(QFont.caption.monospacedDigit()).foregroundStyle(QColor.textTertiary)278                    }279                }280            }281        }282        .chartXSelection(value: $selectedDate)283        .onChange(of: selected?.date) { _, _ in scrubFeedback += 1 }284        .accessibilityLabel("Price chart, \(range.spokenName)")285        .accessibilityValue("From \(format(series[0].value)) to \(format(series[series.count - 1].value)), low \(format(low)), high \(format(high))")286    }287288    var axisDateFormat: Date.FormatStyle {289        switch range {290        case .day: return .dateTime.hour()291        case .week, .month: return .dateTime.month(.abbreviated).day()292        case .year: return .dateTime.month(.abbreviated).year(.twoDigits)293        }294    }295296    var rangePicker: some View {297        HStack(spacing: 6) {298            ForEach(ranges) { r in299                Button {300                    selectedDate = nil301                    withAnimation(reduceMotion ? nil : .snappy(duration: 0.25)) { range = r }302                } label: {303                    Text(r.rawValue)304                        .font(.footnote.weight(.semibold).monospacedDigit())305                        .foregroundStyle(r == range ? QColor.textPrimary : QColor.textSecondary)306                        .frame(maxWidth: .infinity, minHeight: 36)307                        .background {308                            if r == range {309                                Capsule().fill(QColor.surfaceRaised)310                                    .overlay(Capsule().strokeBorder(QColor.stroke, lineWidth: 1))311                                    .matchedGeometryEffect(id: "range", in: rangeNamespace)312                            }313                        }314                        .frame(minHeight: 44)315                        .contentShape(Rectangle())316                }317                .buttonStyle(.plain)318                .accessibilityLabel(r.spokenName)319                .accessibilityAddTraits(r == range ? [.isSelected] : [])320            }321        }322    }323}324325#if DEBUG326private struct ChartPreview: View {327    @State private var range: PriceRange = .week328    // Illustrative preview-only series (a sine wave), not market data.329    static let wave: [ChartPoint] = (0..<48).map { i in330        ChartPoint(date: Date(timeIntervalSinceReferenceDate: Double(i) * 3600), value: 100 + 8 * sin(Double(i) / 5))331    }332333    var body: some View {334        ScrollView {335            VStack(spacing: 28) {336                PriceChartView(points: Self.wave, range: $range, format: { String(format: "%.2f preview", $0) })337                PriceChartView(points: [], range: $range, unavailableReason: "Preview: no price endpoint configured.", format: { "\($0)" })338                HStack {339                    SparklineView(values: Self.wave.map(\.value)).frame(width: 72, height: 28)340                    SparklineView(values: []).frame(width: 72, height: 28)341                }342            }343            .padding()344        }345        .qScreen()346    }347}348349#Preview("Charts") { ChartPreview() }350#endif351
Files main
Menu

Theme