SPB Git

Repository Public

Market.swift 9.2 KB 193 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Models/Market.swift3// Description: Market data as the backend's FMP proxy returns it: quotes, movers, bars, company profile, search results.4import Foundation56/// A number that the provider sometimes sends as a string, sometimes omits.7struct LenientDouble: Decodable {8    var value: Double?9    init(from decoder: Decoder) throws {10        let c = try decoder.singleValueContainer()11        if c.decodeNil() { value = nil }12        else if let d = try? c.decode(Double.self) { value = d }13        else if let s = try? c.decode(String.self) { value = Double(s) }14        else { value = nil }15    }16}1718extension KeyedDecodingContainer {19    func number(_ keys: Key...) -> Double? {20        for k in keys { if let v = (try? decodeIfPresent(LenientDouble.self, forKey: k))??.value { return v } }21        return nil22    }23    func text(_ keys: Key...) -> String? {24        for k in keys { if let v = try? decodeIfPresent(String.self, forKey: k), !v.isEmpty { return v } }25        return nil26    }27}2829public struct Quote: Sendable, Equatable, Identifiable, Codable {30    public var symbol: String31    public var name: String32    public var price: Double33    public var change: Double?34    public var changePercent: Double?35    public var dayLow: Double?36    public var dayHigh: Double?37    public var yearLow: Double?38    public var yearHigh: Double?39    public var open: Double?40    public var previousClose: Double?41    public var volume: Double?42    public var marketCap: Double?43    public var priceAvg50: Double?44    public var priceAvg200: Double?45    public var exchange: String?46    /// The provider's own timestamp of the quote (seconds). The app never substitutes the time of the request for it.47    public var timestamp: Double?4849    public var id: String { symbol }50    public var asOf: Date? { timestamp.map { Date(timeIntervalSince1970: $0) } }5152    enum CodingKeys: String, CodingKey { case symbol, name, price, change, changePercentage, changesPercentage, changePercent, dayLow, dayHigh, yearLow, yearHigh, open, previousClose, volume, marketCap, priceAvg50, priceAvg200, exchange, timestamp }5354    public init(symbol: String, name: String, price: Double, change: Double? = nil, changePercent: Double? = nil, timestamp: Double? = nil) {55        self.symbol = symbol; self.name = name; self.price = price; self.change = change; self.changePercent = changePercent; self.timestamp = timestamp56    }5758    public init(from decoder: Decoder) throws {59        let c = try decoder.container(keyedBy: CodingKeys.self)60        symbol = try c.decode(String.self, forKey: .symbol)61        guard let p = c.number(.price) else { throw DecodingError.dataCorruptedError(forKey: .price, in: c, debugDescription: "quote without a price") }62        price = p63        name = c.text(.name) ?? symbol64        change = c.number(.change)65        changePercent = c.number(.changePercentage, .changesPercentage, .changePercent)66        dayLow = c.number(.dayLow); dayHigh = c.number(.dayHigh); yearLow = c.number(.yearLow); yearHigh = c.number(.yearHigh)67        open = c.number(.open); previousClose = c.number(.previousClose); volume = c.number(.volume); marketCap = c.number(.marketCap)68        priceAvg50 = c.number(.priceAvg50); priceAvg200 = c.number(.priceAvg200)69        exchange = c.text(.exchange)70        timestamp = c.number(.timestamp)71    }7273    public func encode(to encoder: Encoder) throws {74        var c = encoder.container(keyedBy: CodingKeys.self)75        try c.encode(symbol, forKey: .symbol); try c.encode(name, forKey: .name); try c.encode(price, forKey: .price)76        try c.encodeIfPresent(change, forKey: .change); try c.encodeIfPresent(changePercent, forKey: .changePercentage)77        try c.encodeIfPresent(dayLow, forKey: .dayLow); try c.encodeIfPresent(dayHigh, forKey: .dayHigh)78        try c.encodeIfPresent(yearLow, forKey: .yearLow); try c.encodeIfPresent(yearHigh, forKey: .yearHigh)79        try c.encodeIfPresent(open, forKey: .open); try c.encodeIfPresent(previousClose, forKey: .previousClose)80        try c.encodeIfPresent(volume, forKey: .volume); try c.encodeIfPresent(marketCap, forKey: .marketCap)81        try c.encodeIfPresent(priceAvg50, forKey: .priceAvg50); try c.encodeIfPresent(priceAvg200, forKey: .priceAvg200)82        try c.encodeIfPresent(exchange, forKey: .exchange); try c.encodeIfPresent(timestamp, forKey: .timestamp)83    }84}8586public struct ExchangeHours: Sendable, Equatable, Identifiable, Codable {87    public var exchange: String88    public var name: String89    public var openingHour: String?90    public var closingHour: String?91    public var timezone: String?92    public var isMarketOpen: Bool93    public var id: String { exchange }94}9596/// One price bar. `date` is the provider's exchange-local timestamp ("yyyy-MM-dd" or "yyyy-MM-dd HH:mm:ss").97public struct Bar: Sendable, Equatable, Codable {98    public var time: Date99    public var open: Double100    public var high: Double101    public var low: Double102    public var close: Double103    public var volume: Double104    public init(time: Date, open: Double, high: Double, low: Double, close: Double, volume: Double) { self.time = time; self.open = open; self.high = high; self.low = low; self.close = close; self.volume = volume }105}106107public enum BarInterval: String, Sendable, CaseIterable, Codable, Identifiable {108    case m1 = "1min", m5 = "5min", m15 = "15min", m30 = "30min", h1 = "1hour", h4 = "4hour", d1 = "1day"109    public var id: String { rawValue }110    public var isIntraday: Bool { self != .d1 }111    public var label: String {112        switch self { case .m1: "1m"; case .m5: "5m"; case .m15: "15m"; case .m30: "30m"; case .h1: "1h"; case .h4: "4h"; case .d1: "1D" }113    }114    public var seconds: TimeInterval {115        switch self { case .m1: 60; case .m5: 300; case .m15: 900; case .m30: 1800; case .h1: 3600; case .h4: 14400; case .d1: 86400 }116    }117}118119public enum BarParser {120    /// Exchange-local wall time is kept as if it were UTC: bars are positioned and labelled in market time, whatever the Mac's zone.121    public static let calendar: Calendar = { var c = Calendar(identifier: .gregorian); c.timeZone = TimeZone(identifier: "UTC")!; return c }()122123    public static func date(_ s: String) -> Date? {124        // "2026-11-18", "2026-11-18 15:55:00"125        let b = Array(s.utf8)126        func n(_ from: Int, _ len: Int) -> Int? {127            guard b.count >= from + len else { return nil }128            var v = 0129            for i in from..<(from + len) { guard b[i] >= 48, b[i] <= 57 else { return nil }; v = v * 10 + Int(b[i] - 48) }130            return v131        }132        guard let y = n(0, 4), let m = n(5, 2), let d = n(8, 2) else { return nil }133        var comps = DateComponents(year: y, month: m, day: d)134        if b.count >= 16, let h = n(11, 2), let mi = n(14, 2) { comps.hour = h; comps.minute = mi; comps.second = n(17, 2) ?? 0 }135        return calendar.date(from: comps)136    }137138    /// Parses an array of bar objects (newest first, as the provider sends them) into ascending bars. Rows without a139    /// date or a close are dropped and counted, never invented.140    public static func bars(_ rows: [JSONValue]) -> (bars: [Bar], dropped: Int) {141        var out: [Bar] = []; out.reserveCapacity(rows.count)142        var dropped = 0143        for r in rows {144            guard let ds = r["date"]?.stringValue, let t = date(ds), let close = r["close"]?.doubleValue ?? r["price"]?.doubleValue, close.isFinite else { dropped += 1; continue }145            let o = r["open"]?.doubleValue ?? close, h = r["high"]?.doubleValue ?? max(o, close), l = r["low"]?.doubleValue ?? min(o, close)146            out.append(Bar(time: t, open: o, high: h, low: l, close: close, volume: r["volume"]?.doubleValue ?? 0))147        }148        out.sort { $0.time < $1.time }149        // the provider occasionally repeats a bar: the last one wins150        var dedup: [Bar] = []; dedup.reserveCapacity(out.count)151        for b in out { if let last = dedup.last, last.time == b.time { dedup[dedup.count - 1] = b; dropped += 1 } else { dedup.append(b) } }152        return (dedup, dropped)153    }154}155156public struct SymbolMatch: Sendable, Equatable, Identifiable, Codable {157    public var symbol: String158    public var name: String159    public var currency: String?160    public var exchange: String?161    public var exchangeFullName: String?162    public var id: String { symbol }163}164165public struct CompanyProfile: Sendable, Equatable, Codable {166    public var symbol: String167    public var companyName: String?168    public var currency: String?169    public var exchange: String?170    public var exchangeFullName: String?171    public var industry: String?172    public var sector: String?173    public var country: String?174    public var website: String?175    public var description: String?176    public var ceo: String?177    public var fullTimeEmployees: String?178    public var ipoDate: String?179    public var marketCap: Double?180    public var beta: Double?181    public var lastDividend: Double?182    public var range: String?183    public var averageVolume: Double?184    public var isin: String?185    public var cik: String?186}187188public enum Mover: String, Sendable, CaseIterable, Identifiable {189    case gainers, losers, actives190    public var id: String { rawValue }191    public var title: String { switch self { case .gainers: "Gainers"; case .losers: "Losers"; case .actives: "Most active" } }192}193
Files main
Menu

Theme