SPB Git

Repository Public

ChartDrawingTests.swift 12.4 KB 159 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/ChartDrawingTests.swift3// Description: Chart drawings as data: time ↔ bar index, snapping across intervals, Fibonacci levels, measure, hit-testing, moves; aligned visual downsampling; the provenance rows; the text handed to the research agent about the visible range.4import Foundation5import Testing6@testable import VQuantCore78@Suite struct ChartDrawingTests {9    let day = 86_400.010    /// Five daily bars, Mon 2026-11-16 … Fri 2026-11-20 (00:00 UTC), then Mon 2026-11-23.11    var daily: [Double] { [1_794_787_200, 1_794_873_600, 1_794_960_000, 1_795_046_400, 1_795_132_800, 1_795_392_000] }1213    @Test func indexAndTimeAreInverse() {14        let t = daily15        #expect(DrawingMath.index(of: t[2], in: t, step: day) == 2)16        #expect(DrawingMath.index(of: t[2] + day / 2, in: t, step: day) == 2.5)17        // across the weekend the position is interpolated over three days18        #expect(abs(DrawingMath.index(of: t[4] + day, in: t, step: day) - (4 + 1.0 / 3)) < 1e-9)19        // outside the series: one bar per step20        #expect(DrawingMath.index(of: t[0] - 2 * day, in: t, step: day) == -2)21        #expect(DrawingMath.index(of: t[5] + 3 * day, in: t, step: day) == 8)22        for i in [-2.0, 0, 1.25, 4.5, 5, 7] {23            #expect(abs(DrawingMath.index(of: DrawingMath.time(at: i, in: t, step: day), in: t, step: day) - i) < 1e-9)24        }25        #expect(DrawingMath.index(of: 5, in: [], step: day) == 0)26    }2728    @Test func snappingPutsAnAnchorOnABar() {29        let t = daily30        // an intraday anchor (15:30 UTC on the 18th) seen on the daily chart: the bar of the 18th31        #expect(DrawingMath.snappedIndex(of: t[2] + 15.5 * 3600, in: t, step: day) == 2)32        // Saturday falls in a gap: the next bar (Monday)33        #expect(DrawingMath.snappedIndex(of: t[4] + 1.2 * day, in: t, step: day) == 5)34        // a daily anchor (00:00 UTC) seen on 5-minute bars: the first bar of that session, not the previous evening35        let m5 = [t[1] + 20 * 3600 + 3300, t[2] + 14 * 3600 + 1800, t[2] + 14 * 3600 + 2100]36        #expect(DrawingMath.snappedIndex(of: t[2], in: m5, step: 300) == 1)37        // outside: whole bars38        #expect(DrawingMath.snappedIndex(of: t[5] + 2.4 * day, in: t, step: day) == 7)39        #expect(DrawingMath.snappedIndex(of: t[0] - 1.6 * day, in: t, step: day) == -2)40        // stored time of a new anchor: the nearest bar's time41        #expect(DrawingMath.snappedTime(at: 2.4, in: t, step: day) == t[2])42        #expect(DrawingMath.snappedTime(at: 6.6, in: t, step: day) == t[5] + 2 * day)43    }4445    @Test func fibonacciAndMeasure() {46        let f = DrawingMath.fibLevels(from: 100, to: 200)47        #expect(f.first?.price == 200 && f.last?.price == 100)48        #expect(abs(f[2].price - 161.8) < 1e-9 && abs(f[4].price - 138.2) < 1e-9 && f[3].price == 150)49        let t = daily50        let m = DrawingMath.measure(DrawingPoint(t: t[0], p: 200), DrawingPoint(t: t[4], p: 210), times: t, step: day)51        #expect(m.deltaPrice == 10 && abs((m.deltaFraction ?? 0) - 0.05) < 1e-12 && m.bars == 4 && m.seconds == 4 * day)52        #expect(DrawingMath.measure(DrawingPoint(t: t[4], p: 0), DrawingPoint(t: t[0], p: 5), times: t, step: day).deltaFraction == nil)53        #expect(DrawingMath.durationText(4 * day) == "4 d" && DrawingMath.durationText(5400) == "1 h 30 min" && DrawingMath.durationText(-900) == "15 min" && DrawingMath.durationText(400 * day) == "1 y 35 d")54    }5556    @Test func hitTesting() {57        let a = ScreenPoint(x: 100, y: 100), b = ScreenPoint(x: 200, y: 200)58        #expect(DrawingMath.hit(.trend, [a, b], ScreenPoint(x: 150, y: 153), width: 800, height: 400))59        #expect(!DrawingMath.hit(.trend, [a, b], ScreenPoint(x: 150, y: 170), width: 800, height: 400))60        #expect(!DrawingMath.hit(.trend, [a, b], ScreenPoint(x: 260, y: 260), width: 800, height: 400))61        #expect(DrawingMath.hit(.ray, [a, b], ScreenPoint(x: 260, y: 260), width: 800, height: 400))62        #expect(DrawingMath.hit(.hline, [a], ScreenPoint(x: 700, y: 104), width: 800, height: 400))63        // a rectangle is taken by its border, so bars inside it stay reachable64        #expect(DrawingMath.hit(.rect, [a, b], ScreenPoint(x: 100, y: 150), width: 800, height: 400))65        #expect(!DrawingMath.hit(.rect, [a, b], ScreenPoint(x: 150, y: 150), width: 800, height: 400))66        // Fibonacci: on a level (50 % = y 150), within the horizontal extent67        #expect(DrawingMath.hit(.fib, [a, b], ScreenPoint(x: 120, y: 151), width: 800, height: 400))68        #expect(!DrawingMath.hit(.fib, [a, b], ScreenPoint(x: 120, y: 169), width: 800, height: 400))69        #expect(!DrawingMath.hit(.fib, [a, b], ScreenPoint(x: 300, y: 150), width: 800, height: 400))70        #expect(DrawingMath.hit(.text, [a], ScreenPoint(x: 180, y: 105), width: 800, height: 400))71        #expect(DrawingMath.handle([a, b], at: ScreenPoint(x: 203, y: 198)) == 1 && DrawingMath.handle([a, b], at: ScreenPoint(x: 150, y: 150)) == nil)72        #expect(DrawingMath.rayEnd(a, b, width: 800, height: 400) == ScreenPoint(x: 400, y: 400))73    }7475    @Test func movingKeepsBarDistances() {76        let t = daily77        let d = ChartDrawing(id: "d1", kind: .trend, points: [DrawingPoint(t: t[0], p: 10), DrawingPoint(t: t[2], p: 20)])78        let m = DrawingMath.translate(d, bars: 2, price: 5, times: t, step: day)79        #expect(m.points == [DrawingPoint(t: t[2], p: 15), DrawingPoint(t: t[4], p: 25)] && m.id == "d1")80        let r = DrawingMath.translate(d, bars: 0, priceRatio: 1.1, times: t, step: day)81        #expect(abs(r.points[0].p - 11) < 1e-9 && abs(r.points[1].p - 22) < 1e-9 && r.points[0].t == t[0])82        #expect(DrawingKind.hline.pointsNeeded == 1 && DrawingKind.fib.pointsNeeded == 2)83        #expect(!ChartDrawing(id: "x", kind: .rect, points: [DrawingPoint(t: 0, p: 1)]).isComplete)84    }8586    @Test func alignedDownsamplingKeepsExtremesAndDoesNotDependOnTheWindow() {87        let bars = (0..<10).map { i in Bar(time: Date(timeIntervalSince1970: Double(i) * 60), open: Double(i), high: Double(i) + 2, low: Double(i) - 1, close: Double(i) + 1, volume: 10) }88        let b = Downsampler.ohlcAligned(bars, per: 4)89        #expect(b.count == 3 && b.map(\.count) == [4, 4, 2] && b.map(\.firstIndex) == [0, 4, 8])90        #expect(b[1].bar.open == 4 && b[1].bar.close == 8 && b[1].bar.high == 9 && b[1].bar.low == 3 && b[1].bar.volume == 40)91        #expect(Downsampler.per(visible: 10, maxBuckets: 4) == 3 && Downsampler.per(visible: 4, maxBuckets: 4) == 1 && Downsampler.per(visible: 0, maxBuckets: 4) == 1)92        // the buckets a window uses are a slice of the same list wherever the window starts93        #expect(Downsampler.bucketRange(3..<9, per: 4, total: 3) == 0..<3 && Downsampler.bucketRange(4..<8, per: 4, total: 3) == 1..<2)94        let e = Downsampler.envelope([1, nil, 5, 3, 2, 8, nil, nil, 4, 4], per: 4)95        #expect(e.count == 3 && e[0]?.lo == 1 && e[0]?.hi == 5 && e[1]?.lo == 2 && e[1]?.hi == 8 && e[1]?.first == 2 && e[2]?.last == 4)96        #expect(Downsampler.envelope([nil, nil], per: 2) == [nil])97    }9899    @Test func provenanceRowsSayWhatTheServerSaid() {100        var p = ChartProvenance(provider: "findata", fallbackFrom: "fmp", fallbackReason: "no data", adjust: "split", adjustRequested: "split_div", assetClass: "equity", exchange: "NASDAQ",101                                timezone: "America/New_York", currency: "USD", observations: 252, firstDate: "2025-11-20", lastDate: "2026-11-20", truncated: false,102                                gaps: .init(missingSessions: 2, missingDates: ["2026-01-05", "2026-02-10"], calendar: "exchange", checkedFrom: "2025-11-20", checkedTo: "2026-11-20"))103        let rows = Dictionary(uniqueKeysWithValues: p.rows().map { ($0.label, $0.value) })104        #expect(rows["Provider"] == "FinData" && rows["Fallback from"] == "FMP — no data")105        #expect(rows["Adjustment applied"] == "Splits only (asked: splits and dividends)")106        #expect(rows["Gaps"] == "2 missing sessions" && rows["Missing dates"] == "2026-01-05, 2026-02-10" && rows["Truncated"] == "No")107        #expect(rows["Route"] == "VQuant data layer (v2)" && rows["Observations"] == "252")108        p = ChartProvenance(route: .legacy, routeReason: "v2 answered 502", provider: "fmp")109        let legacy = Dictionary(uniqueKeysWithValues: p.rows().map { ($0.label, $0.value) })110        #expect(legacy["Route"] == "1.x provider proxy — v2 answered 502" && legacy["Currency"] == "Not stated" && legacy["Gaps"] == "Not stated")111        // the cache keeps the provenance with the bars112        let s = ChartSeries(bars: [Bar(time: Date(timeIntervalSince1970: 60), open: 1, high: 2, low: 0.5, close: 1.5, volume: 3)], provenance: p)113        #expect(try! JSONDecoder().decode(ChartSeries.self, from: JSONEncoder().encode(s)) == s)114    }115116    @Test func askContextStatesTheVisibleRangeExactly() {117        let t = daily118        let drawings = [119            ChartDrawing(id: "h", kind: .hline, points: [DrawingPoint(t: t[1], p: 350)]),120            ChartDrawing(id: "t", kind: .trend, points: [DrawingPoint(t: t[0], p: 340), DrawingPoint(t: t[4], p: 352.5)]),121            ChartDrawing(id: "f", kind: .fib, points: [DrawingPoint(t: t[0], p: 300), DrawingPoint(t: t[4], p: 400)]),122            ChartDrawing(id: "n", kind: .text, points: [DrawingPoint(t: t[2], p: 345)], text: "earnings"),123            ChartDrawing(id: "m", kind: .measure, points: [DrawingPoint(t: t[0], p: 200), DrawingPoint(t: t[4], p: 210)]),124            ChartDrawing(id: "half", kind: .rect, points: [DrawingPoint(t: t[0], p: 1)]),125        ]126        let c = ChartAskContext(symbol: "AAPL", interval: "1d", intraday: false, timeZone: "America/New_York", firstVisible: Date(timeIntervalSince1970: t[0]), lastVisible: Date(timeIntervalSince1970: t[4]),127                                visibleBars: 5, firstClose: 340, lastClose: 342.56, visibleHigh: 356.42, visibleLow: 338, chartType: "candles", logScale: true,128                                indicators: ["SMA(50)", "RSI(14)"], compare: ["MSFT"], drawings: drawings, provider: "fmp", adjust: "split_div", currency: "USD")129        let s = c.text130        #expect(c.question == "What stands out on this AAPL chart (1d bars) between 2026-11-16 and 2026-11-20?")131        #expect(s.contains("- Symbol: AAPL (USD)"))132        #expect(s.contains("- Interval: 1d bars; chart type: candles; price scale: logarithmic"))133        #expect(s.contains("- Visible range: first bar 2026-11-16, last bar 2026-11-20 (5 bars)"))134        #expect(s.contains("first 340.00, last 342.56 (+0.75 %); high 356.42, low 338.00"))135        #expect(s.contains("- Data: FMP, adjustment: splits and dividends"))136        #expect(s.contains("- Indicators shown: SMA(50), RSI(14)"))137        #expect(s.contains("- Compared with (percentage change from the first visible bar): MSFT"))138        #expect(s.contains("- Drawings I placed (5):"))139        #expect(s.contains("  - Horizontal line at 350.00"))140        #expect(s.contains("  - Trend line from 2026-11-16 at 340.00 to 2026-11-20 at 352.50"))141        #expect(s.contains("0.0 % = 400.00; 23.6 % = 376.40; 38.2 % = 361.80; 50.0 % = 350.00; 61.8 % = 338.20; 78.6 % = 321.40; 100.0 % = 300.00"))142        #expect(s.contains("  - Note at 2026-11-18, 345.00: “earnings”"))143        #expect(s.contains("  - Measure from 2026-11-16 at 200.00 to 2026-11-20 at 210.00: Δ 10.00 (+5.00 %)"))144        // intraday: time in the market's zone, named145        let i = ChartAskContext(symbol: "^GSPC", interval: "5m", intraday: true, timeZone: "America/New_York", firstVisible: Date(timeIntervalSince1970: 1_795_207_800), lastVisible: Date(timeIntervalSince1970: 1_795_208_100),146                                visibleBars: 2, chartType: "line", logScale: false, indicators: [])147        #expect(i.text.contains("first bar 2026-11-20 15:50 America/New_York, last bar 2026-11-20 15:55 America/New_York (2 bars)"))148        #expect(i.text.contains("- Indicators shown: none") && i.text.contains("- Drawings: none") && i.text.contains("price scale: linear"))149    }150151    @Test func workingChartObjectIdMatchesTheWebClient() {152        #expect(ChartObjectID.working("AAPL") == "sym-AAPL" && ChartObjectID.working("aapl") == "sym-AAPL")153        #expect(ChartObjectID.working("^GSPC") == "sym-_5eGSPC")154        #expect(ChartObjectID.working("BRK.B") == "sym-BRK_2eB" && ChartObjectID.working("EURUSD=X") == "sym-EURUSD_3dX" && ChartObjectID.working("BTC-USD") == "sym-BTC_2dUSD")155        let long = ChartObjectID.working(String(repeating: "^", count: 40))156        #expect(long.count == 64 && long.allSatisfy { $0.isLetter || $0.isNumber || $0 == "_" || $0 == "-" })157    }158}159
Files main
Menu

Theme