SPB Git

Repository Public

Market.swift 13.6 KB 274 lines swift

1//2//  VQuant iOS3//  File: Core/Models/Market.swift4//  Description: Market data as served by the VQuant backend (`/api/fmp/*`, a proxy of Financial Modeling Prep).5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation1112/// A quote (`/api/fmp/quote/:symbol`, `/api/fmp/indices`, gainers / losers / actives). Every numeric field except13/// the price is optional: the upstream provider omits fields per asset class, and a missing value is shown as14/// missing, never as zero.15struct Quote: Codable, Hashable, Sendable, Identifiable {16    var symbol: String17    var name: String?18    var price: Double19    var change: Double?20    var changePercent: Double?21    var volume: Double?22    var dayLow: Double?23    var dayHigh: Double?24    var yearLow: Double?25    var yearHigh: Double?26    var marketCap: Double?27    var priceAvg50: Double?28    var priceAvg200: Double?29    var exchange: String?30    var open: Double?31    var previousClose: Double?32    /// Time of the last trade reported by the provider (epoch seconds upstream).33    var timestamp: Date?3435    var id: String { symbol }3637    private enum CodingKeys: String, CodingKey {38        case symbol, name, price, change, changePercentage, changesPercentage, changePercent, volume, dayLow, dayHigh, yearLow, yearHigh39        case marketCap, priceAvg50, priceAvg200, exchange, open, previousClose, timestamp40    }4142    init(symbol: String, name: String? = nil, price: Double, change: Double? = nil, changePercent: Double? = nil, volume: Double? = nil,43         dayLow: Double? = nil, dayHigh: Double? = nil, yearLow: Double? = nil, yearHigh: Double? = nil, marketCap: Double? = nil,44         priceAvg50: Double? = nil, priceAvg200: Double? = nil, exchange: String? = nil, open: Double? = nil, previousClose: Double? = nil, timestamp: Date? = nil) {45        self.symbol = symbol; self.name = name; self.price = price; self.change = change; self.changePercent = changePercent; self.volume = volume46        self.dayLow = dayLow; self.dayHigh = dayHigh; self.yearLow = yearLow; self.yearHigh = yearHigh; self.marketCap = marketCap47        self.priceAvg50 = priceAvg50; self.priceAvg200 = priceAvg200; self.exchange = exchange; self.open = open; self.previousClose = previousClose; self.timestamp = timestamp48    }4950    init(from decoder: Decoder) throws {51        let c = try decoder.container(keyedBy: CodingKeys.self)52        symbol = try c.decode(String.self, forKey: .symbol)53        guard let p = c.flexDouble(.price) else { throw DecodingError.dataCorruptedError(forKey: .price, in: c, debugDescription: "quote without a price") }54        price = p55        name = c.flexString(.name)56        change = c.flexDouble(.change)57        changePercent = c.flexDouble(.changePercentage) ?? c.flexDouble(.changesPercentage) ?? c.flexDouble(.changePercent)58        volume = c.flexDouble(.volume)59        dayLow = c.flexDouble(.dayLow); dayHigh = c.flexDouble(.dayHigh)60        yearLow = c.flexDouble(.yearLow); yearHigh = c.flexDouble(.yearHigh)61        marketCap = c.flexDouble(.marketCap)62        priceAvg50 = c.flexDouble(.priceAvg50); priceAvg200 = c.flexDouble(.priceAvg200)63        exchange = c.flexString(.exchange)64        open = c.flexDouble(.open); previousClose = c.flexDouble(.previousClose)65        if let t = c.flexDouble(.timestamp), t > 0 { timestamp = Date(timeIntervalSince1970: t > 1e12 ? t / 1000 : t) }66    }6768    func encode(to encoder: Encoder) throws {69        var c = encoder.container(keyedBy: CodingKeys.self)70        try c.encode(symbol, forKey: .symbol); try c.encodeIfPresent(name, forKey: .name); try c.encode(price, forKey: .price)71        try c.encodeIfPresent(change, forKey: .change); try c.encodeIfPresent(changePercent, forKey: .changePercentage)72        try c.encodeIfPresent(volume, forKey: .volume); try c.encodeIfPresent(dayLow, forKey: .dayLow); try c.encodeIfPresent(dayHigh, forKey: .dayHigh)73        try c.encodeIfPresent(yearLow, forKey: .yearLow); try c.encodeIfPresent(yearHigh, forKey: .yearHigh); try c.encodeIfPresent(marketCap, forKey: .marketCap)74        try c.encodeIfPresent(priceAvg50, forKey: .priceAvg50); try c.encodeIfPresent(priceAvg200, forKey: .priceAvg200); try c.encodeIfPresent(exchange, forKey: .exchange)75        try c.encodeIfPresent(open, forKey: .open); try c.encodeIfPresent(previousClose, forKey: .previousClose)76        try c.encodeIfPresent(timestamp?.timeIntervalSince1970, forKey: .timestamp)77    }78}7980/// One OHLCV observation exactly as the provider reported it.81struct Bar: Codable, Hashable, Sendable, Identifiable {82    var date: Date83    var open: Double84    var high: Double85    var low: Double86    var close: Double87    var volume: Double?88    var id: Date { date }8990    private enum CodingKeys: String, CodingKey { case date, open, high, low, close, volume }9192    init(date: Date, open: Double, high: Double, low: Double, close: Double, volume: Double? = nil) {93        self.date = date; self.open = open; self.high = high; self.low = low; self.close = close; self.volume = volume94    }9596    init(from decoder: Decoder) throws {97        let c = try decoder.container(keyedBy: CodingKeys.self)98        if let s = c.flexString(.date) {99            guard let d = MarketDate.parse(s) else { throw DecodingError.dataCorruptedError(forKey: .date, in: c, debugDescription: "unreadable bar date \(s)") }100            date = d101        } else if let t = c.flexDouble(.date) { date = Date(timeIntervalSince1970: t) }102        else { throw DecodingError.dataCorruptedError(forKey: .date, in: c, debugDescription: "bar without a date") }103        guard let o = c.flexDouble(.open), let h = c.flexDouble(.high), let l = c.flexDouble(.low), let cl = c.flexDouble(.close) else {104            throw DecodingError.dataCorruptedError(forKey: .close, in: c, debugDescription: "incomplete bar")105        }106        open = o; high = h; low = l; close = cl107        volume = c.flexDouble(.volume)108    }109110    func encode(to encoder: Encoder) throws {111        var c = encoder.container(keyedBy: CodingKeys.self)112        try c.encode(date.timeIntervalSince1970, forKey: .date)113        try c.encode(open, forKey: .open); try c.encode(high, forKey: .high); try c.encode(low, forKey: .low); try c.encode(close, forKey: .close)114        try c.encodeIfPresent(volume, forKey: .volume)115    }116}117118/// Dates of market data are exchange-local wall-clock strings (`2026-11-18` or `2026-11-18 15:55:00`, US/Eastern).119enum MarketDate {120    static let zone = TimeZone(identifier: "America/New_York") ?? .gmt121    static var calendar: Calendar { var c = Calendar(identifier: .gregorian); c.timeZone = zone; return c }122123    static func parse(_ s: String) -> Date? {124        let parts = s.split(whereSeparator: { $0 == " " || $0 == "T" })125        guard let day = parts.first else { return nil }126        let ymd = day.split(separator: "-").compactMap { Int($0) }127        guard ymd.count == 3 else { return ISO8601.parse(s) }128        var comps = DateComponents(year: ymd[0], month: ymd[1], day: ymd[2])129        if parts.count > 1 {130            let hms = parts[1].prefix(8).split(separator: ":").compactMap { Int($0) }131            if hms.count >= 2 { comps.hour = hms[0]; comps.minute = hms[1]; comps.second = hms.count > 2 ? hms[2] : 0 }132        }133        return calendar.date(from: comps)134    }135136    /// `yyyy-MM-dd` in exchange time, the format of the `from` / `to` query parameters.137    static func day(_ date: Date) -> String {138        let c = calendar.dateComponents([.year, .month, .day], from: date)139        return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)140    }141}142143/// Intraday resolutions accepted by `/api/fmp/chart/intraday/:symbol`.144enum IntradayInterval: String, CaseIterable, Codable, Sendable, Identifiable {145    case m1 = "1min", m5 = "5min", m15 = "15min", m30 = "30min", h1 = "1hour", h4 = "4hour"146    var id: String { rawValue }147    var seconds: TimeInterval {148        switch self { case .m1: 60; case .m5: 300; case .m15: 900; case .m30: 1800; case .h1: 3600; case .h4: 14400 }149    }150    var label: String {151        switch self { case .m1: "1 min"; case .m5: "5 min"; case .m15: "15 min"; case .m30: "30 min"; case .h1: "1 h"; case .h4: "4 h" }152    }153}154155/// What a chart asks the server for: a window and a resolution (the server aggregates; the device never resamples156/// behind the user's back).157enum ChartRange: String, CaseIterable, Codable, Sendable, Identifiable {158    case day = "1J", week = "5J", month = "1M", quarter = "3M", halfYear = "6M", year = "1A", fiveYears = "5A", max = "Max"159    var id: String { rawValue }160161    /// Intraday resolution, or `nil` for end-of-day bars.162    var interval: IntradayInterval? {163        switch self { case .day: .m5; case .week: .m15; case .month: .h1; default: nil }164    }165    /// Calendar days requested before `to`.166    var lookbackDays: Int {167        switch self { case .day: 4; case .week: 8; case .month: 31; case .quarter: 92; case .halfYear: 183; case .year: 366; case .fiveYears: 1827; case .max: 365 * 45 }168    }169    var isIntraday: Bool { interval != nil }170}171172struct CompanyProfile: Codable, Hashable, Sendable {173    var symbol: String174    var companyName: String?175    var currency: String?176    var exchange: String?177    var exchangeFullName: String?178    var industry: String?179    var sector: String?180    var country: String?181    var ceo: String?182    var website: String?183    var description: String?184    var image: String?185    var ipoDate: String?186    var fullTimeEmployees: String?187    var beta: Double?188    var marketCap: Double?189    var lastDividend: Double?190    var averageVolume: Double?191    var range: String?192    var isin: String?193    var isEtf: Bool?194195    private enum CodingKeys: String, CodingKey {196        case symbol, companyName, currency, exchange, exchangeFullName, industry, sector, country, ceo, website, description, image, ipoDate197        case fullTimeEmployees, beta, marketCap, lastDividend, averageVolume, range, isin, isEtf198    }199    init(symbol: String) { self.symbol = symbol }200    init(from decoder: Decoder) throws {201        let c = try decoder.container(keyedBy: CodingKeys.self)202        symbol = try c.decode(String.self, forKey: .symbol)203        companyName = c.flexString(.companyName); currency = c.flexString(.currency); exchange = c.flexString(.exchange)204        exchangeFullName = c.flexString(.exchangeFullName); industry = c.flexString(.industry); sector = c.flexString(.sector)205        country = c.flexString(.country); ceo = c.flexString(.ceo); website = c.flexString(.website); description = c.flexString(.description)206        image = c.flexString(.image); ipoDate = c.flexString(.ipoDate)207        fullTimeEmployees = c.flexString(.fullTimeEmployees) ?? c.flexInt(.fullTimeEmployees).map(String.init)208        beta = c.flexDouble(.beta); marketCap = c.flexDouble(.marketCap); lastDividend = c.flexDouble(.lastDividend)209        averageVolume = c.flexDouble(.averageVolume); range = c.flexString(.range); isin = c.flexString(.isin); isEtf = c.flexBool(.isEtf)210    }211}212213struct NewsItem: Codable, Hashable, Sendable, Identifiable {214    var symbol: String?215    var publishedDate: String?216    var publisher: String?217    var title: String218    var image: String?219    var site: String?220    var text: String?221    var url: String222    var id: String { url }223    var published: Date? { publishedDate.flatMap(MarketDate.parse) }224}225226struct ExchangeHours: Codable, Hashable, Sendable, Identifiable {227    var exchange: String228    var name: String?229    var openingHour: String?230    var closingHour: String?231    var timezone: String?232    var isMarketOpen: Bool233    var id: String { exchange }234}235236/// A result of `/api/fmp/search`.237struct SymbolMatch: Codable, Hashable, Sendable, Identifiable {238    var symbol: String239    var name: String?240    var currency: String?241    var exchangeName: String?242    var exchangeCode: String?243    var id: String { symbol }244245    private enum CodingKeys: String, CodingKey { case symbol, name, currency, stockExchange, exchangeShortName, exchangeFullName, exchange }246    init(symbol: String, name: String? = nil, currency: String? = nil, exchangeName: String? = nil, exchangeCode: String? = nil) {247        self.symbol = symbol; self.name = name; self.currency = currency; self.exchangeName = exchangeName; self.exchangeCode = exchangeCode248    }249    init(from decoder: Decoder) throws {250        let c = try decoder.container(keyedBy: CodingKeys.self)251        symbol = try c.decode(String.self, forKey: .symbol)252        name = c.flexString(.name); currency = c.flexString(.currency)253        exchangeName = c.flexString(.stockExchange) ?? c.flexString(.exchangeFullName)254        exchangeCode = c.flexString(.exchangeShortName) ?? c.flexString(.exchange)255    }256    func encode(to encoder: Encoder) throws {257        var c = encoder.container(keyedBy: CodingKeys.self)258        try c.encode(symbol, forKey: .symbol); try c.encodeIfPresent(name, forKey: .name); try c.encodeIfPresent(currency, forKey: .currency)259        try c.encodeIfPresent(exchangeName, forKey: .stockExchange); try c.encodeIfPresent(exchangeCode, forKey: .exchangeShortName)260    }261}262263/// Fundamental tables (income statement, balance sheet, cash flow, key metrics, ratios, estimates…) are arrays of264/// provider-defined records. They are kept generic so the app shows every field the server returns and invents none.265typealias FundamentalRecord = [String: JSONValue]266267enum FundamentalTable: String, CaseIterable, Sendable, Identifiable {268    case income = "income-statement", balance = "balance-sheet", cashFlow = "cash-flow", metrics = "key-metrics", ratios = "financial-ratios"269    case estimates = "analyst-estimates", earnings = "earnings-surprises", dividends = "dividend-history", holders = "institutional-holders"270    case insiders = "insider-trading", grades = "upgrades-downgrades", targets = "price-target-summary"271    var id: String { rawValue }272    var path: String { "/api/fmp/\(rawValue)" }273}274
Files main
Menu

Theme