SPB Git

Repository Public

AnalyticsTests.swift 8.8 KB 143 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/AnalyticsTests.swift3// Description: Indicators, statistics, visual downsampling, tables and CSV against hand-computed values.4import Foundation5import Testing6@testable import VQuantCore78@Suite struct AnalyticsTests {9    func close(_ a: Double?, _ b: Double, _ tol: Double = 1e-9) -> Bool { a.map { abs($0 - b) < tol } ?? false }1011    @Test func smaEma() {12        let x: [Double] = [1, 2, 3, 4, 5, 6]13        #expect(Indicators.sma(x, 3) == [nil, nil, 2, 3, 4, 5])14        let e = Indicators.ema(x, 3)   // seed 2, k = 0.515        #expect(e[1] == nil && close(e[2], 2) && close(e[3], 3) && close(e[4], 4) && close(e[5], 5))16        #expect(Indicators.sma([1, 2], 3) == [nil, nil])17    }1819    @Test func bollinger() {20        let b = Indicators.bollinger([2, 4, 4, 4, 5, 5, 7, 9], 8, k: 2)   // mean 5, population sd 221        #expect(close(b.middle[7], 5) && close(b.upper[7], 9) && close(b.lower[7], 1) && b.upper[6] == nil)22    }2324    @Test func rsiBounds() {25        let up = Indicators.rsi((0...20).map(Double.init), 14)26        #expect(up[13] == nil && close(up[14], 100) && close(up[20], 100))27        let down = Indicators.rsi((0...20).map { 100 - Double($0) }, 14)28        #expect(close(down[20], 0))29        let flat = Indicators.rsi(Array(repeating: 5, count: 20), 14)30        #expect(close(flat[19], 50))31        // Wilder's worked example (first RSI of the classic 14-day table)32        let w: [Double] = [44.34, 44.09, 44.15, 43.61, 44.33, 44.83, 45.10, 45.42, 45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28]33        #expect(close(Indicators.rsi(w, 14)[14], 70.46, 0.1))34    }3536    @Test func macdDefinition() {37        let x = (0..<60).map { 100 + sin(Double($0) / 5) * 10 }38        let m = Indicators.macd(x)39        let f = Indicators.ema(x, 12), s = Indicators.ema(x, 26)40        #expect(m.macd[24] == nil && close(m.macd[40], f[40]! - s[40]!))41        #expect(m.signal[32] == nil && m.signal[33] != nil)   // 26 + 9 − 242        #expect(close(m.histogram[50], m.macd[50]! - m.signal[50]!))43    }4445    @Test func returnsDrawdownStats() {46        #expect(SeriesStats.returns([100, 110, 99]).map { ($0 * 1000).rounded() / 1000 } == [0.1, -0.1])47        #expect(SeriesStats.drawdown([100, 120, 90, 120, 60]) == [0, 0, -25, 0, -50])48        #expect(close(SeriesStats.stdev([2, 4, 4, 4, 5, 5, 7, 9]), 2.138089935, 1e-6))49        #expect(close(SeriesStats.correlation([1, 2, 3, 4], [2, 4, 6, 8]), 1))50        #expect(close(SeriesStats.correlation([1, 2, 3, 4], [8, 6, 4, 2]), -1))51        #expect(SeriesStats.correlation([1, 1, 1, 1], [1, 2, 3, 4]) == nil)52        let h = SeriesStats.histogram([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], bins: 5)!53        #expect(h.counts.reduce(0, +) == 11 && h.edges.count == 6 && h.counts.last == 3)54    }5556    @Test func alignedReturnsUseCommonDatesOnly() {57        func d(_ n: Int) -> Date { Date(timeIntervalSince1970: Double(n) * 86400) }58        func b(_ n: Int, _ c: Double) -> Bar { Bar(time: d(n), open: c, high: c, low: c, close: c, volume: 0) }59        let r = SeriesStats.alignedReturns([("A", [b(1, 100), b(2, 110), b(3, 121)]), ("B", [b(1, 50), b(3, 100), b(4, 1)])])60        #expect(r.dates == [d(3)])61        #expect(close(r.returns["A"]?[0], 0.21) && close(r.returns["B"]?[0], 1.0))62    }6364    @Test func downsamplingKeepsExtremesAndVolume() {65        var bars: [Bar] = []66        for i in 0..<1000 {67            let v = Double(i)68            let high: Double = v + (i == 517 ? 500 : 1)69            let low: Double = v - (i == 203 ? 400 : 1)70            bars.append(Bar(time: Date(timeIntervalSince1970: v * 60), open: v, high: high, low: low, close: v + 0.5, volume: 10))71        }72        let b: [Downsampler.Bucket] = Downsampler.ohlc(bars[...], maxBuckets: 120)73        let merged: Int = b.reduce(0) { $0 + $1.count }74        #expect(b.count <= 120 && merged == 1000)75        let maxHigh: Double = b.reduce(-Double.infinity) { max($0, $1.bar.high) }76        let minLow: Double = b.reduce(Double.infinity) { min($0, $1.bar.low) }77        #expect(maxHigh == 1017)78        #expect(minLow == -197)79        #expect(b.first?.bar.open == 0 && b.last?.bar.close == 999.5)80        let volume: Double = b.reduce(0) { $0 + $1.bar.volume }81        #expect(volume == 10_000)82        // nothing is merged when the bars already fit83        let small: [Downsampler.Bucket] = Downsampler.ohlc(bars[0..<50], maxBuckets: 120)84        #expect(small.count == 50 && small.allSatisfy { $0.count == 1 })85    }8687    @Test func tableSortFilterExport() throws {88        let t = DataTable(rows: [["date": "2026-01-02", "v": 3, "name": "b,c"], ["date": "2026-01-01", "v": nil, "name": "a\"q"], ["date": "2026-01-03", "v": 10.5, "name": "z"]])89        #expect(t.columns == ["date", "name", "v"] && t.isNumeric("v") && !t.isNumeric("name"))90        #expect(t.sorted(by: "v", ascending: false).rows.map { $0["date"]!.stringValue! } == ["2026-01-03", "2026-01-02", "2026-01-01"])91        #expect(t.sorted(by: "v", ascending: true).rows.last?["v"] == .null)   // missing values last both ways92        #expect(t.filtered("b,").rows.count == 1 && t.between("2026-01-02", nil).rows.count == 2)93        #expect(t.csv() == "date,name,v\r\n2026-01-02,\"b,c\",3\r\n2026-01-01,\"a\"\"q\",\r\n2026-01-03,z,10.5\r\n")94        // full precision of provider numbers survives the export95        let ratios = DataTable(rows: try JSONValue.parse(fixture("ratios")).arrayValue ?? [])96        #expect(ratios.csv().contains("0.48785591666423017"))97    }9899    @Test func barCSVUsesSourceBars() throws {100        let bars = BarParser.bars(try JSONValue.parse(fixture("chart-intraday")).arrayValue ?? []).bars101        let csv = CSV.bars(bars, intraday: true)102        #expect(csv.components(separatedBy: "\r\n").count == bars.count + 2)103        #expect(csv.contains("2026-11-18 15:55:00,352.68,353.18,352.22,352.3,"))104    }105106    @Test func portfolioValuation() {107        let pos = [Position(symbol: "AAA", quantity: 10, costBasis: 90, note: nil, updatedAt: 0), Position(symbol: "BBB", quantity: 5, costBasis: nil, note: nil, updatedAt: 0), Position(symbol: "ZZZ", quantity: 1, costBasis: 1, note: nil, updatedAt: 0)]108        let quotes = ["AAA": Quote(symbol: "AAA", name: "A", price: 100, change: 2, timestamp: 2000), "BBB": Quote(symbol: "BBB", name: "B", price: 20, change: -1, timestamp: 1000)]109        let v = PortfolioValuation(positions: pos, quotes: quotes)110        #expect(v.marketValue == 1100 && v.unpriced == ["ZZZ"] && v.dayChange == 15)111        #expect(v.cost == nil && v.unrealized == nil)   // BBB has no cost basis: no total P&L is claimed112        #expect(v.lines[0].unrealized == 100 && v.lines[0].weight.map { ($0 * 100).rounded() / 100 } == 90.91)113        #expect(v.asOf == Date(timeIntervalSince1970: 1000))   // as stale as its oldest quote114        let full = PortfolioValuation(positions: [pos[0]], quotes: quotes)115        #expect(full.cost == 900 && full.unrealized == 100)116    }117118    @Test func freshnessNeverCallsAnOldQuoteRecent() {119        let now = Date(timeIntervalSince1970: 10_000)120        #expect(Freshness.ofQuote(asOf: now.addingTimeInterval(-30), now: now) == .recent(asOf: now.addingTimeInterval(-30)))121        #expect(Freshness.ofQuote(asOf: now.addingTimeInterval(-3600), now: now) == .delayed(asOf: now.addingTimeInterval(-3600)))122        if case .unavailable = Freshness.ofQuote(asOf: nil, now: now) {} else { Issue.record("a quote without a timestamp must not be dated") }123    }124125    @Test func quantFormValidation() throws {126        let cat = try JSONDecoder().decode(QuantCatalogue.self, from: fixture("quant-tools"))127        let garch = cat.tools[0], opt = cat.tools.first { $0.id == "portfolio_optimization" }!128        #expect(try QuantForm.build(tool: garch, values: ["symbol": " aapl ", "p": "2"], flags: [:]).get() == ["symbol": "AAPL", "p": 2])129        #expect(throws: QuantForm.FormError.self) { try QuantForm.build(tool: garch, values: ["p": "2"], flags: [:]).get() }130        #expect(throws: QuantForm.FormError.self) { try QuantForm.build(tool: garch, values: ["symbol": "AAPL", "p": "9"], flags: [:]).get() }131        #expect(throws: QuantForm.FormError.self) { try QuantForm.build(tool: garch, values: ["symbol": "AAPL", "p": "1.5"], flags: [:]).get() }132        let o = try QuantForm.build(tool: opt, values: ["symbols": "aapl, msft aapl;nvda"], flags: ["generate_frontier": false]).get()133        #expect(o["symbols"] == ["AAPL", "MSFT", "NVDA"] && o["generate_frontier"] == false)134        #expect(throws: QuantForm.FormError.self) { try QuantForm.build(tool: opt, values: ["symbols": "AAPL"], flags: [:]).get() }135    }136137    @Test func watchlistSymbols() {138        var w = Watchlist(name: "x", symbols: [])139        #expect(w.add(" aapl ") && w.add("^gspc") && w.add("BRK-B") && w.add("ENB.TO") && !w.add("AAPL") && !w.add("not a symbol") && !w.add(""))140        #expect(w.symbols == ["AAPL", "^GSPC", "BRK-B", "ENB.TO"])141    }142}143
Files main
Menu

Theme