SPB Git

Repository Public

AnalyticsCharts.swift 18.1 KB 416 lines swift

1//2//  VQuant iOS3//  File: VQuant/Charts/AnalyticsCharts.swift4//  Description: Analytical charts built with Swift Charts on the bars the server returned: sparkline, distribution of5//               returns, drawdown, rolling volatility, correlation matrix, allocation, portfolio value, generic series.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Charts12import SwiftUI13import VQuantUI1415/// The empty state shared by the analytical charts.16private struct ChartPlaceholder: View {17    var message: String18    var body: some View {19        VStack(spacing: 6) {20            Image(systemName: "chart.xyaxis.line").font(.title3).foregroundStyle(Theme.textSecondary)21            Text(message).font(.footnote).foregroundStyle(Theme.textSecondary).multilineTextAlignment(.center)22        }23        .frame(maxWidth: .infinity, minHeight: 120)24        .accessibilityElement(children: .combine)25    }26}2728private struct ChartCaption: View {29    var text: String30    var body: some View {31        Text(text).font(.caption.monospacedDigit()).foregroundStyle(Theme.textSecondary).frame(maxWidth: .infinity, alignment: .leading)32    }33}3435// MARK: - Sparkline3637/// A tiny line of the values as given, coloured by the direction from the first to the last.38struct Sparkline: View {39    private let values: [Double]40    init(values: [Double]) { self.values = values.filter(\.isFinite) }4142    var body: some View {43        Canvas { ctx, size in44            guard values.count > 1, let lo = values.min(), let hi = values.max(), size.width > 0, size.height > 0 else { return }45            let range = ChartMath.paddedRange(low: lo, high: hi, padding: 0.08)46            var path = Path()47            for (i, v) in values.enumerated() {48                let p = CGPoint(x: CGFloat(i) / CGFloat(values.count - 1) * size.width, y: CGFloat(ChartMath.y(v, in: range, height: Double(size.height))))49                if i == 0 { path.move(to: p) } else { path.addLine(to: p) }50            }51            ctx.stroke(path, with: .color(Theme.direction(values[values.count - 1] - values[0])), style: StrokeStyle(lineWidth: 1.4, lineCap: .round, lineJoin: .round))52        }53        .accessibilityElement()54        .accessibilityLabel(label)55    }5657    private var label: String {58        guard values.count > 1, let first = values.first, let last = values.last, first != 0 else { return "Tendance indisponible" }59        return "Tendance sur \(values.count) points : \(Fmt.percent((last / first - 1) * 100))"60    }61}6263// MARK: - Distribution of returns6465struct ReturnsHistogramChart: View {66    private let bins: [Indicators.Bin]67    private let mean: Double?68    private let sigma: Double?69    private let observations: Int7071    init(closes: [Double]) {72        let r = Indicators.logReturns(closes)73        observations = r.count74        bins = Indicators.histogram(r, bins: 31)75        mean = Indicators.mean(r)76        sigma = Indicators.stdev(r)77    }7879    var body: some View {80        if bins.isEmpty {81            ChartPlaceholder(message: "Pas assez d’observations pour une distribution des rendements.")82        } else {83            VStack(spacing: 6) {84                Chart {85                    ForEach(bins) { b in86                        RectangleMark(xStart: .value("Rendement", b.lower * 100), xEnd: .value("Rendement", b.upper * 100), yStart: .value("Jours", 0), yEnd: .value("Jours", b.count))87                            .foregroundStyle((b.lower + b.upper) / 2 >= 0 ? Theme.up.opacity(0.8) : Theme.down.opacity(0.8))88                    }89                    if let mean {90                        RuleMark(x: .value("Moyenne", mean * 100))91                            .foregroundStyle(Theme.textSecondary)92                            .lineStyle(StrokeStyle(lineWidth: 1, dash: [4, 3]))93                            .annotation(position: .top, alignment: .center) { Text("μ").font(.caption2).foregroundStyle(Theme.textSecondary) }94                    }95                }96                .chartXAxisLabel("Rendement logarithmique quotidien (%)")97                .chartYAxisLabel("Nombre de jours")98                .frame(minHeight: 180)99                ChartCaption(text: caption)100            }101            .accessibilityElement(children: .ignore)102            .accessibilityLabel("Distribution des rendements quotidiens")103            .accessibilityValue(caption)104        }105    }106107    private var caption: String {108        "\(observations) rendements · moyenne \(Fmt.fraction(mean, digits: 3)) · écart-type \(Fmt.fraction(sigma, digits: 3))"109    }110}111112// MARK: - Drawdown113114struct DrawdownChart: View {115    private struct Point: Identifiable { var date: Date; var value: Double; var id: Date { date } }116    private let points: [Point]117    private let worst: Point?118119    init(bars: [Bar]) {120        let dd = Indicators.drawdown(bars.map(\.close))121        points = zip(bars, dd).map { Point(date: $0.date, value: $1 * 100) }122        worst = points.min { $0.value < $1.value }123    }124125    var body: some View {126        if points.count < 2 {127            ChartPlaceholder(message: "Pas assez d’observations pour le drawdown.")128        } else {129            VStack(spacing: 6) {130                Chart(points) { p in131                    AreaMark(x: .value("Date", p.date), y: .value("Drawdown", p.value))132                        .foregroundStyle(Theme.down.opacity(0.25))133                    LineMark(x: .value("Date", p.date), y: .value("Drawdown", p.value))134                        .foregroundStyle(Theme.down)135                        .lineStyle(StrokeStyle(lineWidth: 1.2))136                }137                .chartYAxisLabel("Repli depuis le sommet (%)")138                .environment(\.timeZone, MarketDate.zone)139                .frame(minHeight: 160)140                ChartCaption(text: caption)141            }142            .accessibilityElement(children: .ignore)143            .accessibilityLabel("Drawdown")144            .accessibilityValue(caption)145        }146    }147148    private var caption: String {149        guard let worst, let last = points.last else { return "" }150        return "Repli maximal \(Fmt.percent(worst.value)) le \(ChartDates.full(worst.date, intraday: false)) · repli actuel \(Fmt.percent(last.value))"151    }152}153154// MARK: - Rolling volatility155156struct RollingVolatilityChart: View {157    private struct Point: Identifiable { var date: Date; var value: Double; var id: Date { date } }158    private let points: [Point]159    private let window: Int160161    init(bars: [Bar], window: Int = 21) {162        self.window = window163        let vol = Indicators.rollingVolatility(bars.map(\.close), window: window)164        points = zip(bars, vol).compactMap { bar, v in v.map { Point(date: bar.date, value: $0 * 100) } }165    }166167    var body: some View {168        if points.count < 2 {169            ChartPlaceholder(message: "Pas assez d’observations pour une volatilité glissante sur \(window) séances.")170        } else {171            VStack(spacing: 6) {172                Chart(points) { p in173                    LineMark(x: .value("Date", p.date), y: .value("Volatilité", p.value))174                        .foregroundStyle(Theme.orange)175                        .lineStyle(StrokeStyle(lineWidth: 1.4, lineJoin: .round))176                }177                .chartYAxisLabel("Volatilité réalisée annualisée (%)")178                .chartYScale(domain: .automatic(includesZero: false))179                .environment(\.timeZone, MarketDate.zone)180                .frame(minHeight: 160)181                ChartCaption(text: caption)182            }183            .accessibilityElement(children: .ignore)184            .accessibilityLabel("Volatilité réalisée glissante sur \(window) séances")185            .accessibilityValue(caption)186        }187    }188189    private var caption: String {190        let values = points.map(\.value)191        guard let last = values.last, let lo = values.min(), let hi = values.max() else { return "" }192        return "Fenêtre \(window) séances, base 252 · actuelle \(Fmt.price(last)) % · min \(Fmt.price(lo)) % · max \(Fmt.price(hi)) %"193    }194}195196// MARK: - Correlation matrix197198struct CorrelationHeatmap: View {199    private let symbols: [String]200    private let matrix: [[Double?]]201    @ScaledMetric(relativeTo: .caption2) private var cell: CGFloat = 46202203    init(symbols: [String], matrix: [[Double?]]) {204        self.symbols = symbols205        self.matrix = matrix206    }207208    private var isValid: Bool { symbols.count >= 2 && matrix.count == symbols.count && matrix.allSatisfy { $0.count == symbols.count } }209210    var body: some View {211        if !isValid {212            ChartPlaceholder(message: "Il faut au moins deux titres avec un historique commun pour une matrice de corrélation.")213        } else {214            VStack(alignment: .leading, spacing: 6) {215                ScrollView(.horizontal) {216                    Grid(horizontalSpacing: 2, verticalSpacing: 2) {217                        GridRow {218                            Color.clear.frame(width: cell, height: 1)219                            ForEach(symbols, id: \.self) { s in header(s) }220                        }221                        ForEach(Array(symbols.enumerated()), id: \.offset) { i, s in222                            GridRow {223                                header(s)224                                ForEach(Array(symbols.indices), id: \.self) { j in value(matrix[i][j], row: s, column: symbols[j]) }225                            }226                        }227                    }228                    .padding(.vertical, 2)229                }230                .scrollIndicators(.hidden)231                HStack(spacing: 6) {232                    Text("−1")233                    LinearGradient(colors: [Self.color(-1), Self.color(0), Self.color(1)], startPoint: .leading, endPoint: .trailing)234                        .frame(width: 90, height: 6).clipShape(Capsule())235                    Text("+1")236                    Spacer()237                    Text("Rendements logarithmiques quotidiens, dates communes")238                }239                .font(.caption2).foregroundStyle(Theme.textSecondary).lineLimit(1).minimumScaleFactor(0.7)240            }241            .dynamicTypeSize(.xSmall ... .xxLarge)242            .accessibilityElement(children: .contain)243            .accessibilityLabel("Matrice de corrélation de \(symbols.count) titres")244        }245    }246247    private func header(_ s: String) -> some View {248        Text(s).font(.caption2.weight(.semibold)).lineLimit(1).minimumScaleFactor(0.6).frame(width: cell, height: cell * 0.6)249            .accessibilityHidden(true)250    }251252    private func value(_ v: Double?, row: String, column: String) -> some View {253        let text = v.map { $0.formatted(.number.precision(.fractionLength(2)).locale(Fmt.locale)) } ?? "—"254        return Text(text)255            .font(.caption2.monospacedDigit())256            .foregroundStyle(v.map { abs($0) > 0.55 ? Color.white : Color.primary } ?? Theme.textSecondary)257            .frame(width: cell, height: cell * 0.72)258            .background(v.map(Self.color) ?? Theme.surface2, in: RoundedRectangle(cornerRadius: 4))259            .accessibilityElement()260            .accessibilityLabel("\(row) et \(column)")261            .accessibilityValue(v == nil ? "corrélation indisponible" : "corrélation \(text)")262    }263264    /// Diverging scale that does not reuse the gain / loss colours: blue for −1, neutral at 0, orange for +1.265    private static func color(_ v: Double) -> Color {266        let t = min(1, abs(v))267        let end: (Double, Double, Double) = v >= 0 ? (0.91, 0.36, 0.05) : (0.15, 0.39, 0.92)268        let mid = 0.55269        return Color(red: mid + (end.0 - mid) * t, green: mid + (end.1 - mid) * t, blue: mid + (end.2 - mid) * t).opacity(0.25 + 0.75 * t)270    }271}272273// MARK: - Allocation274275struct AllocationChart: View {276    private struct Slice: Identifiable { var symbol: String; var weight: Double; var id: String { symbol } }277    private let slices: [Slice]278    /// The categorical data palette of the design system (data colours are separate from the brand accent).279    private static let palette: [Color] = VQTokens.DataPalette.categorical + [VQTokens.Palette.text3]280281    init(weights: [(symbol: String, weight: Double)]) {282        let positive = weights.filter { $0.weight.isFinite && $0.weight > 0 }.sorted { $0.weight > $1.weight }283        var list = positive.prefix(8).map { Slice(symbol: $0.symbol, weight: $0.weight) }284        let rest = positive.dropFirst(8).reduce(0) { $0 + $1.weight }285        if rest > 0 { list.append(Slice(symbol: "Autres (\(positive.count - 8))", weight: rest)) }286        slices = list287    }288289    private var total: Double { slices.reduce(0) { $0 + $1.weight } }290    private func share(_ s: Slice) -> Double { total > 0 ? s.weight / total * 100 : 0 }291    private func color(_ s: Slice) -> Color { Self.palette[(slices.firstIndex { $0.id == s.id } ?? 0) % Self.palette.count] }292293    var body: some View {294        if slices.isEmpty {295            ChartPlaceholder(message: "Aucune position valorisée à répartir.")296        } else {297            ViewThatFits(in: .horizontal) {298                HStack(alignment: .center, spacing: 16) { donut.frame(width: 170, height: 170); legend }299                VStack(spacing: 12) { donut.frame(height: 170); legend }300            }301            .accessibilityElement(children: .ignore)302            .accessibilityLabel("Répartition du portefeuille")303            .accessibilityValue(slices.map { "\($0.symbol) \(Fmt.price(share($0))) %" }.joined(separator: ", "))304        }305    }306307    private var donut: some View {308        Chart(slices) { s in309            SectorMark(angle: .value("Poids", s.weight), innerRadius: .ratio(0.62), angularInset: 1)310                .cornerRadius(2)311                .foregroundStyle(color(s))312        }313        .chartLegend(.hidden)314    }315316    private var legend: some View {317        VStack(alignment: .leading, spacing: 5) {318            ForEach(slices) { s in319                HStack(spacing: 6) {320                    RoundedRectangle(cornerRadius: 2).fill(color(s)).frame(width: 10, height: 10)321                    Text(s.symbol).font(.footnote).lineLimit(1)322                    Spacer(minLength: 8)323                    Text("\(share(s).formatted(.number.precision(.fractionLength(1)).locale(Fmt.locale))) %").font(.footnote.monospacedDigit()).foregroundStyle(Theme.textSecondary)324                }325            }326        }327        .frame(minWidth: 130, maxWidth: 260)328    }329}330331// MARK: - Portfolio value332333struct ValueHistoryChart: View {334    private let points: [PortfolioMath.ValuePoint]335    init(points: [PortfolioMath.ValuePoint]) { self.points = points }336337    var body: some View {338        if points.count < 2 {339            ChartPlaceholder(message: "Pas assez de dates communes à toutes les positions pour tracer la valeur.")340        } else {341            let lo = points.map(\.value).min() ?? 0, hi = points.map(\.value).max() ?? 1342            let range = ChartMath.paddedRange(low: lo, high: hi, padding: 0.08)343            VStack(spacing: 6) {344                Chart(points) { p in345                    AreaMark(x: .value("Date", p.date), yStart: .value("Valeur", range.lowerBound), yEnd: .value("Valeur", p.value))346                        .foregroundStyle(LinearGradient(colors: [Theme.orange.opacity(0.30), Theme.orange.opacity(0.02)], startPoint: .top, endPoint: .bottom))347                    LineMark(x: .value("Date", p.date), y: .value("Valeur", p.value))348                        .foregroundStyle(Theme.orange)349                        .lineStyle(StrokeStyle(lineWidth: 1.6, lineJoin: .round))350                }351                .chartYScale(domain: range)352                .chartYAxisLabel("Valeur des positions actuelles")353                .chartYAxis { AxisMarks { v in AxisGridLine(); AxisValueLabel { if let d = v.as(Double.self) { Text(Fmt.compact(d)) } } } }354                .environment(\.timeZone, MarketDate.zone)355                .frame(minHeight: 180)356                ChartCaption(text: caption)357            }358            .accessibilityElement(children: .ignore)359            .accessibilityLabel("Valeur dans le temps des positions actuelles, quantités constantes")360            .accessibilityValue(caption)361        }362    }363364    private var caption: String {365        guard let first = points.first, let last = points.last else { return "" }366        let change: Double? = first.value != 0 ? (last.value / first.value - 1) * 100 : nil367        return "Du \(ChartDates.full(first.date, intraday: false)) au \(ChartDates.full(last.date, intraday: false)) · \(Fmt.compact(first.value)) → \(Fmt.compact(last.value)) (\(Fmt.percent(change)))"368    }369}370371// MARK: - Generic series (results of the server engines)372373struct SeriesChart: View {374    private let points: [QuantResult.Point]375    private let title: String376377    init(points: [QuantResult.Point], title: String) {378        self.points = points.sorted { $0.date < $1.date }379        self.title = title380    }381382    var body: some View {383        if points.isEmpty {384            ChartPlaceholder(message: "Série vide.")385        } else {386            VStack(spacing: 6) {387                Chart(points) { p in388                    LineMark(x: .value("Date", p.date), y: .value(title, p.value))389                        .foregroundStyle(Theme.orange)390                        .lineStyle(StrokeStyle(lineWidth: 1.5, lineJoin: .round))391                    if points.count <= 40 {392                        PointMark(x: .value("Date", p.date), y: .value(title, p.value))393                            .symbolSize(14)394                            .foregroundStyle(Theme.orange)395                    }396                }397                .chartYScale(domain: .automatic(includesZero: false))398                .chartYAxisLabel(title)399                .environment(\.timeZone, MarketDate.zone)400                .frame(minHeight: 160)401                ChartCaption(text: caption)402            }403            .accessibilityElement(children: .ignore)404            .accessibilityLabel(title)405            .accessibilityValue(caption)406        }407    }408409    private var caption: String {410        guard let first = points.first, let last = points.last else { return "" }411        let values = points.map(\.value)412        let f: (Double) -> String = { QuantResult.format(.number($0)) }413        return "\(points.count) points, du \(ChartDates.full(first.date, intraday: false)) au \(ChartDates.full(last.date, intraday: false)) · début \(f(first.value)) · fin \(f(last.value)) · min \(f(values.min() ?? 0)) · max \(f(values.max() ?? 0))"414    }415}416
Files main
Menu

Theme