SPB Git

Repository Public

ChartSeries.swift 13.1 KB 209 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Models/ChartSeries.swift3// Description: A charted series with where it comes from (provider, fallback, adjustment, gaps), in a form the encrypted cache can keep; and the words the chart uses to describe itself to a person and to the research agent.4import Foundation56/// Provenance of a bar series as the server states it (`GET /api/v2/data/bars/:symbol`), or what is known when the7/// series had to come from the 1.x route.8public struct ChartProvenance: Sendable, Equatable, Codable {9    public enum Route: String, Sendable, Codable {10        /// `/api/v2/data/bars` — the server's data layer, with full provenance.11        case v212        /// The 1.x provider proxy, used only when the v2 route answered 404 or 502.13        case legacy14    }15    public struct Gaps: Sendable, Equatable, Codable {16        public var missingSessions: Int17        public var missingDates: [String]18        public var unexpectedSessions: Int19        public var unexpectedDates: [String]20        public var calendar: String?21        public var checkedFrom: String?22        public var checkedTo: String?23        public var note: String?24        public init(missingSessions: Int = 0, missingDates: [String] = [], unexpectedSessions: Int = 0, unexpectedDates: [String] = [], calendar: String? = nil, checkedFrom: String? = nil, checkedTo: String? = nil, note: String? = nil) {25            self.missingSessions = missingSessions; self.missingDates = missingDates; self.unexpectedSessions = unexpectedSessions; self.unexpectedDates = unexpectedDates26            self.calendar = calendar; self.checkedFrom = checkedFrom; self.checkedTo = checkedTo; self.note = note27        }28    }2930    public var route: Route31    /// Why the 1.x route was used (route == .legacy).32    public var routeReason: String?33    public var provider: String34    public var fallbackFrom: String?35    public var fallbackReason: String?36    public var retrievedAt: Date?37    /// The adjustment the series really has.38    public var adjust: String?39    public var adjustRequested: String?40    public var assetClass: String?41    public var exchange: String?42    public var timezone: String?43    public var currency: String?44    /// `polled|delayed|eod|historical|estimated` as the server says; nil on the 1.x route.45    public var freshnessKind: String?46    public var asOf: Date?47    public var observations: Int?48    public var firstDate: String?49    public var lastDate: String?50    public var truncated: Bool51    public var gaps: Gaps?52    public var notes: [String]5354    public init(route: Route = .v2, routeReason: String? = nil, provider: String, fallbackFrom: String? = nil, fallbackReason: String? = nil, retrievedAt: Date? = nil,55                adjust: String? = nil, adjustRequested: String? = nil, assetClass: String? = nil, exchange: String? = nil, timezone: String? = nil, currency: String? = nil,56                freshnessKind: String? = nil, asOf: Date? = nil, observations: Int? = nil, firstDate: String? = nil, lastDate: String? = nil, truncated: Bool = false,57                gaps: Gaps? = nil, notes: [String] = []) {58        self.route = route; self.routeReason = routeReason; self.provider = provider; self.fallbackFrom = fallbackFrom; self.fallbackReason = fallbackReason59        self.retrievedAt = retrievedAt; self.adjust = adjust; self.adjustRequested = adjustRequested; self.assetClass = assetClass; self.exchange = exchange60        self.timezone = timezone; self.currency = currency; self.freshnessKind = freshnessKind; self.asOf = asOf; self.observations = observations61        self.firstDate = firstDate; self.lastDate = lastDate; self.truncated = truncated; self.gaps = gaps; self.notes = notes62    }6364    public static func providerName(_ id: String) -> String {65        switch id.lowercased() { case "fmp": "FMP"; case "findata": "FinData"; case "eodhd": "EODHD"; case "": "unknown"; default: id }66    }67    public static func adjustName(_ a: String?) -> String {68        switch a { case "split_div"?: "Splits and dividends"; case "split"?: "Splits only"; case "none"?: "None (as traded)"; case let other?: other; case nil: "Not stated" }69    }7071    /// The rows of the provenance popover, in reading order. Nothing is filled in: a value the server did not state72    /// reads "Not stated".73    public func rows() -> [(label: String, value: String)] {74        var out: [(String, String)] = []75        out.append(("Route", route == .v2 ? "VQuant data layer (v2)" : "1.x provider proxy" + (routeReason.map { " — \($0)" } ?? "")))76        out.append(("Provider", Self.providerName(provider)))77        if let f = fallbackFrom { out.append(("Fallback from", Self.providerName(f) + (fallbackReason.map { " — \($0)" } ?? ""))) }78        var adj = Self.adjustName(adjust)79        if let r = adjustRequested, let a = adjust, r != a { adj += " (asked: \(Self.adjustName(r).lowercased()))" }80        out.append(("Adjustment applied", adj))81        if let a = assetClass { out.append(("Asset class", a + (exchange.map { " · \($0)" } ?? ""))) } else if let e = exchange { out.append(("Exchange", e)) }82        out.append(("Time zone", timezone ?? "Not stated"))83        out.append(("Currency", currency ?? "Not stated"))84        out.append(("Observations", observations.map { String($0) } ?? "Not stated"))85        out.append(("First bar", firstDate ?? "Not stated"))86        out.append(("Last bar", lastDate ?? "Not stated"))87        out.append(("Truncated", truncated ? "Yes — the most recent bars of the range were kept" : "No"))88        if let g = gaps {89            var s = g.calendar == "none" ? "Not checked" : "\(g.missingSessions) missing session\(g.missingSessions == 1 ? "" : "s")"90            if g.unexpectedSessions > 0 { s += ", \(g.unexpectedSessions) unexpected" }91            out.append(("Gaps", s))92            if !g.missingDates.isEmpty { out.append(("Missing dates", g.missingDates.joined(separator: ", ") + (g.missingSessions > g.missingDates.count ? " …" : ""))) }93            if !g.unexpectedDates.isEmpty { out.append(("Unexpected dates", g.unexpectedDates.joined(separator: ", "))) }94            if let f = g.checkedFrom, let t = g.checkedTo { out.append(("Checked", "\(f) → \(t)" + (g.calendar.map { " · \($0) calendar" } ?? ""))) }95        } else { out.append(("Gaps", "Not stated")) }96        return out97    }98}99100/// What the chart draws and the cache keeps: the source bars and their provenance, together.101public struct ChartSeries: Sendable, Equatable, Codable {102    public var bars: [Bar]103    public var provenance: ChartProvenance104    /// Rows the provider sent that had no usable close (dropped, never invented).105    public var dropped: Int106    public init(bars: [Bar], provenance: ChartProvenance, dropped: Int = 0) { self.bars = bars; self.provenance = provenance; self.dropped = dropped }107}108109/// The factual description of what a chart shows, in words, for the research agent. The server receives plain text:110/// everything the agent should know about the visible range is stated here.111public struct ChartAskContext: Sendable, Equatable {112    public var symbol: String113    /// "1m" … "1d"114    public var interval: String115    public var intraday: Bool116    public var timeZone: String?117    public var firstVisible: Date118    public var lastVisible: Date119    public var visibleBars: Int120    public var firstClose: Double?121    public var lastClose: Double?122    public var visibleHigh: Double?123    public var visibleLow: Double?124    public var chartType: String125    public var logScale: Bool126    /// Each with its parameters: "SMA(50)", "Bollinger bands(20, 2)".127    public var indicators: [String]128    public var compare: [String]129    public var drawings: [ChartDrawing]130    public var provider: String?131    public var adjust: String?132    public var currency: String?133134    public init(symbol: String, interval: String, intraday: Bool, timeZone: String?, firstVisible: Date, lastVisible: Date, visibleBars: Int, firstClose: Double? = nil, lastClose: Double? = nil,135                visibleHigh: Double? = nil, visibleLow: Double? = nil, chartType: String, logScale: Bool, indicators: [String], compare: [String] = [], drawings: [ChartDrawing] = [],136                provider: String? = nil, adjust: String? = nil, currency: String? = nil) {137        self.symbol = symbol; self.interval = interval; self.intraday = intraday; self.timeZone = timeZone; self.firstVisible = firstVisible; self.lastVisible = lastVisible138        self.visibleBars = visibleBars; self.firstClose = firstClose; self.lastClose = lastClose; self.visibleHigh = visibleHigh; self.visibleLow = visibleLow139        self.chartType = chartType; self.logScale = logScale; self.indicators = indicators; self.compare = compare; self.drawings = drawings140        self.provider = provider; self.adjust = adjust; self.currency = currency141    }142143    /// A bar date as the agent should read it: the session date for daily bars, date and time in the market's zone144    /// for intraday bars (UTC when the zone is not stated).145    public func stamp(_ d: Date) -> String {146        let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX")147        let zone = intraday ? (timeZone.flatMap(TimeZone.init(identifier:)) ?? TimeZone(identifier: "UTC")!) : TimeZone(identifier: "UTC")!148        f.timeZone = zone149        f.dateFormat = intraday ? "yyyy-MM-dd HH:mm" : "yyyy-MM-dd"150        return f.string(from: d) + (intraday ? " " + (timeZone ?? "UTC") : "")151    }152    private func stamp(_ t: Double) -> String { stamp(Date(timeIntervalSince1970: t)) }153154    static func num(_ v: Double) -> String {155        let a = abs(v)156        return String(format: a >= 1 ? "%.2f" : "%.4f", v)157    }158159    /// The question put in the composer (editable before sending).160    public var question: String {161        "What stands out on this \(symbol) chart (\(interval) bars) between \(stamp(firstVisible)) and \(stamp(lastVisible))?"162    }163164    /// The context appended to the question when it is sent.165    public var text: String {166        var lines: [String] = []167        lines.append("Chart context (what I am looking at in VQuant for macOS):")168        lines.append("- Symbol: \(symbol)" + (currency.map { " (\($0))" } ?? ""))169        lines.append("- Interval: \(interval) bars; chart type: \(chartType); price scale: \(logScale ? "logarithmic" : "linear")")170        lines.append("- Visible range: first bar \(stamp(firstVisible)), last bar \(stamp(lastVisible)) (\(visibleBars) bar\(visibleBars == 1 ? "" : "s"))")171        if let a = firstClose, let b = lastClose {172            var s = "- Closes over the visible range: first \(Self.num(a)), last \(Self.num(b))"173            if a > 0 { s += String(format: " (%+.2f %%)", (b / a - 1) * 100) }174            if let h = visibleHigh, let l = visibleLow { s += "; high \(Self.num(h)), low \(Self.num(l))" }175            lines.append(s)176        }177        if let p = provider { lines.append("- Data: \(ChartProvenance.providerName(p))" + (adjust.map { ", adjustment: \(ChartProvenance.adjustName($0).lowercased())" } ?? "")) }178        lines.append("- Indicators shown: " + (indicators.isEmpty ? "none" : indicators.joined(separator: ", ")))179        if !compare.isEmpty { lines.append("- Compared with (percentage change from the first visible bar): " + compare.joined(separator: ", ")) }180        let done = drawings.filter(\.isComplete)181        if done.isEmpty { lines.append("- Drawings: none") } else {182            lines.append("- Drawings I placed (\(done.count)):")183            for d in done {184                let a = d.points[0], b = d.points.count > 1 ? d.points[1] : nil185                switch d.kind {186                case .hline: lines.append("  - Horizontal line at \(Self.num(a.p))")187                case .trend: if let b { lines.append("  - Trend line from \(stamp(a.t)) at \(Self.num(a.p)) to \(stamp(b.t)) at \(Self.num(b.p))") }188                case .ray: if let b { lines.append("  - Ray from \(stamp(a.t)) at \(Self.num(a.p)) through \(stamp(b.t)) at \(Self.num(b.p))") }189                case .rect: if let b { lines.append("  - Rectangle from \(stamp(min(a.t, b.t))) to \(stamp(max(a.t, b.t))), prices \(Self.num(min(a.p, b.p))) to \(Self.num(max(a.p, b.p)))") }190                case .fib:191                    if let b {192                        let levels = DrawingMath.fibLevels(from: a.p, to: b.p).map { String(format: "%.1f %% = ", $0.ratio * 100) + Self.num($0.price) }193                        lines.append("  - Fibonacci retracement of the move from \(Self.num(a.p)) (\(stamp(a.t))) to \(Self.num(b.p)) (\(stamp(b.t))): " + levels.joined(separator: "; "))194                    }195                case .text: lines.append("  - Note at \(stamp(a.t)), \(Self.num(a.p)): “\(d.text ?? "")”")196                case .measure:197                    if let b {198                        var s = "  - Measure from \(stamp(a.t)) at \(Self.num(a.p)) to \(stamp(b.t)) at \(Self.num(b.p)): Δ \(Self.num(b.p - a.p))"199                        if a.p > 0 { s += String(format: " (%+.2f %%)", (b.p / a.p - 1) * 100) }200                        lines.append(s)201                    }202                }203            }204        }205        lines.append("Indicators are computed on the Mac from the bars shown; the levels above are the ones I drew.")206        return lines.joined(separator: "\n")207    }208}209
Files main
Menu

Theme