SPB Git

Repository Public

RsIndicators.swift 7.2 KB 134 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Research/RsIndicators.swift3// Description: The observed bars of the server's consolidated series, and the basic indicators the app DERIVES from them locally (moving averages, RSI, realized volatility, drawdown). Pure functions: bars in, numbers out. Everything computed here is a derived figure and is labelled as such on screen with its window length; none of it is market data served by the wallet.4import Foundation5import SPWalletCore67/// One closed bar as served. Every field comes from the single source the bar names.8struct RsBar: Identifiable, Sendable, Equatable {9    let date: Date10    let open: Double, high: Double, low: Double, close: Double11    let volume: Double?12    let source: String?13    var id: Date { date }14    var isUp: Bool { close >= open }1516    /// nil when a field is missing or not a finite number: such a bar is not drawn rather than guessed.17    init?(_ v: JSONValue) {18        func num(_ k: String) -> Double? {19            guard let x = v[k] else { return nil }20            let d = x.doubleValue ?? x.stringValue.flatMap(Double.init)21            return d.flatMap { $0.isFinite ? $0 : nil }22        }23        guard let ts = num("ts"), let o = num("open"), let h = num("high"), let l = num("low"), let c = num("close"), ts > 0 else { return nil }24        date = Date(timeIntervalSince1970: ts > 1e11 ? ts / 1000 : ts)25        open = o; high = h; low = l; close = c; volume = num("volume"); source = v["source"]?.stringValue26    }27}2829struct RsPoint: Identifiable, Sendable, Equatable {30    let date: Date31    let value: Double32    var id: Date { date }33}3435enum RsIndicators {36    /// Simple moving average of the closes over `window` bars; the first point is at bar `window`.37    static func sma(_ bars: [RsBar], window: Int) -> [RsPoint] {38        guard window > 0, bars.count >= window else { return [] }39        var out: [RsPoint] = []; out.reserveCapacity(bars.count - window + 1)40        var sum = bars[0..<window].reduce(0) { $0 + $1.close }41        out.append(RsPoint(date: bars[window - 1].date, value: sum / Double(window)))42        for i in window..<bars.count {43            sum += bars[i].close - bars[i - window].close44            out.append(RsPoint(date: bars[i].date, value: sum / Double(window)))45        }46        return out47    }4849    /// Exponential moving average (smoothing 2 / (window + 1)), seeded with the simple average of the first `window` closes.50    static func ema(_ bars: [RsBar], window: Int) -> [RsPoint] {51        guard window > 0, bars.count >= window else { return [] }52        let k = 2.0 / Double(window + 1)53        var value = bars[0..<window].reduce(0) { $0 + $1.close } / Double(window)54        var out = [RsPoint(date: bars[window - 1].date, value: value)]55        for i in window..<bars.count { value = bars[i].close * k + value * (1 - k); out.append(RsPoint(date: bars[i].date, value: value)) }56        return out57    }5859    /// Relative strength index with Wilder's smoothing over `window` bars (0…100).60    static func rsi(_ bars: [RsBar], window: Int) -> [RsPoint] {61        guard window > 0, bars.count > window else { return [] }62        var gain = 0.0, loss = 0.063        for i in 1...window { let d = bars[i].close - bars[i - 1].close; if d >= 0 { gain += d } else { loss -= d } }64        gain /= Double(window); loss /= Double(window)65        func value() -> Double { loss == 0 ? (gain == 0 ? 50 : 100) : 100 - 100 / (1 + gain / loss) }66        var out = [RsPoint(date: bars[window].date, value: value())]67        if bars.count > window + 1 {68            for i in (window + 1)..<bars.count {69                let d = bars[i].close - bars[i - 1].close70                gain = (gain * Double(window - 1) + max(d, 0)) / Double(window)71                loss = (loss * Double(window - 1) + max(-d, 0)) / Double(window)72                out.append(RsPoint(date: bars[i].date, value: value()))73            }74        }75        return out76    }7778    /// Sample standard deviation of the last `window` close-to-close log returns, annualized with `periodsPerYear`. nil when there are not enough bars.79    static func realizedVolatility(_ bars: [RsBar], window: Int, periodsPerYear: Double) -> Double? {80        guard window > 1, bars.count > window else { return nil }81        let tail = bars.suffix(window + 1).map(\.close)82        guard tail.allSatisfy({ $0 > 0 }) else { return nil }83        var returns: [Double] = []84        for i in 1..<tail.count { returns.append(Foundation.log(tail[i] / tail[i - 1])) } // `log` alone is the app's Logger85        let mean: Double = returns.reduce(0, +) / Double(returns.count)86        var squares = 0.087        for r in returns { squares += (r - mean) * (r - mean) }88        let variance: Double = squares / Double(returns.count - 1)89        return (variance * periodsPerYear).squareRoot()90    }9192    /// Decline of each close from the highest close seen so far in the displayed window (0 or negative fraction).93    static func drawdown(_ bars: [RsBar]) -> [RsPoint] {94        var peak = -Double.infinity95        return bars.compactMap { b in96            peak = max(peak, b.close)97            return peak > 0 ? RsPoint(date: b.date, value: b.close / peak - 1) : nil98        }99    }100101    /// Bars per year for a market that trades around the clock, every day (the server's consolidated crypto series).102    static func periodsPerYear(interval: String) -> Double? {103        switch interval { case "5m": 105_120; case "1h": 8_760; case "4h": 2_190; case "1d": 365; default: nil }104    }105    static func intervalSeconds(_ interval: String) -> TimeInterval? {106        switch interval { case "5m": 300; case "1h": 3_600; case "4h": 14_400; case "1d": 86_400; default: nil }107    }108}109110enum RsFmt {111    /// A decimal string of the server parsed for DISPLAY of market data only (never an amount to sign).112    static func double(_ s: String?) -> Double? { s.flatMap(Double.init).flatMap { $0.isFinite ? $0 : nil } }113    static func price(_ v: Double?) -> String {114        guard let v else { return "—" }115        let digits = abs(v) >= 1000 ? 2 : abs(v) >= 1 ? 4 : 8116        return v.formatted(.number.precision(.fractionLength(2...digits)))117    }118    static func price(_ s: String?) -> String { s == nil ? "—" : (double(s).map { price($0) } ?? s!) }119    static func compactUsd(_ s: String?) -> String {120        guard let v = double(s) else { return "—" }121        return v.formatted(.currency(code: "USD").notation(.compactName).precision(.fractionLength(0...2)))122    }123    /// A fraction served as a decimal string (0.0123) → signed percentage.124    static func fraction(_ s: String?, digits: Int = 2) -> String { OpsFmt.fraction(double(s), digits: digits) }125    static func bps(_ s: String?) -> String { double(s).map { "\($0.formatted(.number.precision(.fractionLength(0...1)))) pb" } ?? "—" }126    static func age(ms: Int?) -> String { OpsFmt.duration(ms: ms.map(Double.init)) }127    static func date(ms: JSONValue?) -> Date? {128        guard let v = ms else { return nil }129        if let d = v.doubleValue, d > 0 { return Date(timeIntervalSince1970: d > 1e11 ? d / 1000 : d) }130        return v.stringValue.flatMap(ISO8601.parse)131    }132    static func metric(_ v: Double?, digits: Int = 2) -> String { v.map { $0.formatted(.number.precision(.fractionLength(digits))) } ?? "—" }133}134
Files main
Menu

Theme