SPB Git

Repository Public

Indicators.swift 13.1 KB 262 lines swift

1//2//  VQuant iOS3//  File: Core/Quant/Indicators.swift4//  Description: Descriptive statistics and technical indicators computed on device from the bars the server returned.5//               These are display transforms of real observations; models (GARCH, VaR, optimisation…) stay on the server.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import Foundation1213enum Indicators {14    /// Simple moving average. `nil` until `period` observations are available.15    static func sma(_ x: [Double], period: Int) -> [Double?] {16        guard period > 0 else { return x.map { _ in nil } }17        var out = [Double?](repeating: nil, count: x.count)18        var sum = 0.019        for i in x.indices {20            sum += x[i]21            if i >= period { sum -= x[i - period] }22            if i >= period - 1 { out[i] = sum / Double(period) }23        }24        return out25    }2627    /// Exponential moving average seeded with the SMA of the first `period` values.28    static func ema(_ x: [Double], period: Int) -> [Double?] {29        guard period > 0, x.count >= period else { return x.map { _ in nil } }30        var out = [Double?](repeating: nil, count: x.count)31        let k = 2.0 / Double(period + 1)32        var prev = x[0..<period].reduce(0, +) / Double(period)33        out[period - 1] = prev34        for i in period..<x.count { prev = x[i] * k + prev * (1 - k); out[i] = prev }35        return out36    }3738    /// Wilder's RSI.39    static func rsi(_ x: [Double], period: Int = 14) -> [Double?] {40        guard period > 0, x.count > period else { return x.map { _ in nil } }41        var out = [Double?](repeating: nil, count: x.count)42        var gain = 0.0, loss = 0.043        for i in 1...period { let d = x[i] - x[i - 1]; if d >= 0 { gain += d } else { loss -= d } }44        gain /= Double(period); loss /= Double(period)45        out[period] = loss == 0 ? 100 : 100 - 100 / (1 + gain / loss)46        guard x.count > period + 1 else { return out }47        for i in (period + 1)..<x.count {48            let d = x[i] - x[i - 1]49            gain = (gain * Double(period - 1) + max(d, 0)) / Double(period)50            loss = (loss * Double(period - 1) + max(-d, 0)) / Double(period)51            out[i] = loss == 0 ? 100 : 100 - 100 / (1 + gain / loss)52        }53        return out54    }5556    struct MACD: Equatable, Sendable { var macd: [Double?]; var signal: [Double?]; var histogram: [Double?] }57    static func macd(_ x: [Double], fast: Int = 12, slow: Int = 26, signal: Int = 9) -> MACD {58        let f = ema(x, period: fast), s = ema(x, period: slow)59        let line: [Double?] = zip(f, s).map { a, b in if let a, let b { return a - b } else { return nil } }60        let firstValid = line.firstIndex { $0 != nil } ?? line.count61        let sig = [Double?](repeating: nil, count: firstValid) + ema(line[firstValid...].compactMap { $0 }, period: signal)62        let hist: [Double?] = zip(line, sig).map { a, b in if let a, let b { return a - b } else { return nil } }63        return MACD(macd: line, signal: sig, histogram: hist)64    }6566    struct Bands: Equatable, Sendable { var middle: [Double?]; var upper: [Double?]; var lower: [Double?] }67    /// Bollinger bands with the population standard deviation, as charting packages do.68    static func bollinger(_ x: [Double], period: Int = 20, width: Double = 2) -> Bands {69        let mid = sma(x, period: period)70        var up = [Double?](repeating: nil, count: x.count), lo = up71        guard period > 0 else { return Bands(middle: mid, upper: up, lower: lo) }72        for i in x.indices where i >= period - 1 {73            guard let m = mid[i] else { continue }74            let v = x[(i - period + 1)...i].reduce(0) { $0 + ($1 - m) * ($1 - m) } / Double(period)75            up[i] = m + width * v.squareRoot(); lo[i] = m - width * v.squareRoot()76        }77        return Bands(middle: mid, upper: up, lower: lo)78    }7980    /// Simple returns `p[t] / p[t-1] - 1` (one fewer element than the input).81    static func returns(_ p: [Double]) -> [Double] {82        guard p.count > 1 else { return [] }83        return (1..<p.count).map { p[$0 - 1] == 0 ? 0 : p[$0] / p[$0 - 1] - 1 }84    }85    static func logReturns(_ p: [Double]) -> [Double] {86        guard p.count > 1 else { return [] }87        return (1..<p.count).compactMap { p[$0 - 1] > 0 && p[$0] > 0 ? log(p[$0] / p[$0 - 1]) : nil }88    }8990    static func mean(_ x: [Double]) -> Double? { x.isEmpty ? nil : x.reduce(0, +) / Double(x.count) }91    /// Sample standard deviation (n − 1).92    static func stdev(_ x: [Double]) -> Double? {93        guard x.count > 1, let m = mean(x) else { return nil }94        return (x.reduce(0) { $0 + ($1 - m) * ($1 - m) } / Double(x.count - 1)).squareRoot()95    }9697    /// Rolling realised volatility of log returns, annualised (`periodsPerYear` = 252 for daily bars).98    static func rollingVolatility(_ prices: [Double], window: Int = 21, periodsPerYear: Double = 252) -> [Double?] {99        var out = [Double?](repeating: nil, count: prices.count)100        guard window > 1, prices.count > window else { return out }101        let r = (1..<prices.count).map { prices[$0 - 1] > 0 && prices[$0] > 0 ? log(prices[$0] / prices[$0 - 1]) : 0 }102        for i in (window - 1)..<r.count {103            if let s = stdev(Array(r[(i - window + 1)...i])) { out[i + 1] = s * periodsPerYear.squareRoot() }104        }105        return out106    }107108    /// Drawdown from the running peak, as a non-positive fraction.109    static func drawdown(_ p: [Double]) -> [Double] {110        var peak = -Double.infinity111        return p.map { v in peak = max(peak, v); return peak > 0 ? v / peak - 1 : 0 }112    }113    static func maxDrawdown(_ p: [Double]) -> Double? { drawdown(p).min() }114115    static func correlation(_ a: [Double], _ b: [Double]) -> Double? {116        let n = min(a.count, b.count)117        guard n > 2, let ma = mean(Array(a.prefix(n))), let mb = mean(Array(b.prefix(n))) else { return nil }118        var sab = 0.0, saa = 0.0, sbb = 0.0119        for i in 0..<n { let x = a[i] - ma, y = b[i] - mb; sab += x * y; saa += x * x; sbb += y * y }120        guard saa > 0, sbb > 0 else { return nil }121        return sab / (saa * sbb).squareRoot()122    }123124    struct Bin: Equatable, Sendable, Identifiable { var lower: Double; var upper: Double; var count: Int; var id: Double { lower } }125    static func histogram(_ x: [Double], bins: Int = 31) -> [Bin] {126        guard bins > 0, let lo = x.min(), let hi = x.max(), hi > lo else { return [] }127        let w = (hi - lo) / Double(bins)128        var counts = [Int](repeating: 0, count: bins)129        for v in x { counts[min(bins - 1, Int((v - lo) / w))] += 1 }130        return counts.enumerated().map { Bin(lower: lo + Double($0.offset) * w, upper: lo + Double($0.offset + 1) * w, count: $0.element) }131    }132133    /// Exact OHLCV aggregation of consecutive bars into groups of `factor` (first open, highest high, lowest low,134    /// last close, summed volume). Used only for drawing when there are more bars than pixels, and the chart says so.135    static func aggregate(_ bars: [Bar], factor: Int) -> [Bar] {136        guard factor > 1, !bars.isEmpty else { return bars }137        var out: [Bar] = []; out.reserveCapacity(bars.count / factor + 1)138        var i = 0139        while i < bars.count {140            let chunk = bars[i..<min(i + factor, bars.count)]141            let vols = chunk.compactMap(\.volume)142            out.append(Bar(date: chunk.first!.date, open: chunk.first!.open, high: chunk.map(\.high).max()!, low: chunk.map(\.low).min()!,143                           close: chunk.last!.close, volume: vols.isEmpty ? nil : vols.reduce(0, +)))144            i += factor145        }146        return out147    }148149    struct Summary: Equatable, Sendable {150        var observations: Int151        var totalReturn: Double?152        var annualisedVolatility: Double?153        var maxDrawdown: Double?154        var bestDay: Double?155        var worstDay: Double?156        var skewness: Double?157        var excessKurtosis: Double?158    }159    static func summary(closes p: [Double], periodsPerYear: Double = 252) -> Summary {160        let r = logReturns(p), simple = returns(p)161        var skew: Double?, kurt: Double?162        if r.count > 3, let m = mean(r), let s = stdev(r), s > 0 {163            let n = Double(r.count)164            skew = r.reduce(0) { $0 + pow(($1 - m) / s, 3) } / n165            kurt = r.reduce(0) { $0 + pow(($1 - m) / s, 4) } / n - 3166        }167        return Summary(observations: p.count, totalReturn: (p.first ?? 0) > 0 && p.count > 1 ? p.last! / p.first! - 1 : nil,168                       annualisedVolatility: stdev(r).map { $0 * periodsPerYear.squareRoot() }, maxDrawdown: maxDrawdown(p),169                       bestDay: simple.max(), worstDay: simple.min(), skewness: skew, excessKurtosis: kurt)170    }171}172173// MARK: - Portfolio arithmetic174175enum PortfolioMath {176    struct Line: Equatable, Sendable, Identifiable {177        var symbol: String178        var quantity: Double179        var costBasis: Double?180        var price: Double?181        var dayChangePercent: Double?182        var id: String { symbol }183        var value: Double? { price.map { $0 * quantity } }184        var cost: Double? { costBasis.map { $0 * quantity } }185        var gain: Double? { if let value, let cost { return value - cost } else { return nil } }186        var gainPercent: Double? { if let gain, let cost, cost != 0 { return gain / abs(cost) } else { return nil } }187        var dayGain: Double? {188            guard let value, let d = dayChangePercent, d > -100 else { return nil }189            return value - value / (1 + d / 100)190        }191    }192193    struct Totals: Equatable, Sendable {194        var value: Double195        var cost: Double?196        var gain: Double?197        var gainPercent: Double?198        var dayGain: Double?199        var dayGainPercent: Double?200        /// Positions without a price: excluded from `value`, and reported rather than counted as zero.201        var unpriced: [String]202    }203204    static func lines(positions: [Position], quotes: [String: Quote]) -> [Line] {205        positions.map { p in206            let q = quotes[p.symbol]207            return Line(symbol: p.symbol, quantity: p.quantity, costBasis: p.costBasis, price: q?.price, dayChangePercent: q?.changePercent)208        }209    }210211    static func totals(_ lines: [Line]) -> Totals {212        let priced = lines.filter { $0.value != nil }213        let value = priced.reduce(0) { $0 + ($1.value ?? 0) }214        // Gain is only meaningful over the positions that have both a price and a cost basis.215        let both = priced.filter { $0.cost != nil }216        let cost = both.isEmpty ? nil : both.reduce(0) { $0 + ($1.cost ?? 0) }217        let gain = cost.map { c in both.reduce(0) { $0 + ($1.value ?? 0) } - c }218        let day = priced.compactMap(\.dayGain)219        let dayGain = day.isEmpty ? nil : day.reduce(0, +)220        return Totals(value: value, cost: cost, gain: gain, gainPercent: (gain != nil && (cost ?? 0) != 0) ? gain! / abs(cost!) : nil,221                      dayGain: dayGain, dayGainPercent: dayGain.flatMap { value - $0 != 0 ? $0 / (value - $0) : nil },222                      unpriced: lines.filter { $0.value == nil }.map(\.symbol))223    }224225    static func weights(_ lines: [Line]) -> [(symbol: String, weight: Double)] {226        let total = lines.reduce(0) { $0 + abs($1.value ?? 0) }227        guard total > 0 else { return [] }228        return lines.compactMap { l in l.value.map { (l.symbol, abs($0) / total) } }.sorted { $0.1 > $1.1 }229    }230231    struct ValuePoint: Equatable, Sendable, Identifiable { var date: Date; var value: Double; var id: Date { date } }232233    /// Value through time of today's holdings held constant (a what-if on current quantities, not a transaction234    /// history: VQuant records no trades). Only dates on which every held symbol has a close are kept.235    static func history(quantities: [String: Double], closes: [String: [Bar]]) -> [ValuePoint] {236        let symbols = quantities.keys.filter { !(closes[$0] ?? []).isEmpty }237        guard !symbols.isEmpty, symbols.count == quantities.count else { return [] }238        var byDay: [String: [String: Double]] = [:]239        var dates: [String: Date] = [:]240        for s in symbols { for b in closes[s] ?? [] { let d = MarketDate.day(b.date); byDay[d, default: [:]][s] = b.close; dates[d] = b.date } }241        return byDay.compactMap { day, px -> ValuePoint? in242            guard px.count == symbols.count, let date = dates[day] else { return nil }243            return ValuePoint(date: date, value: symbols.reduce(0) { $0 + (px[$1] ?? 0) * (quantities[$1] ?? 0) })244        }.sorted { $0.date < $1.date }245    }246247    /// Correlation matrix of daily log returns over the dates common to all symbols.248    static func correlationMatrix(symbols: [String], closes: [String: [Bar]]) -> [[Double?]] {249        var common: Set<String>?250        var maps: [String: [String: Double]] = [:]251        for s in symbols {252            var m: [String: Double] = [:]253            for b in closes[s] ?? [] { m[MarketDate.day(b.date)] = b.close }254            maps[s] = m255            common = common.map { $0.intersection(m.keys) } ?? Set(m.keys)256        }257        let days = (common ?? []).sorted()258        let series = symbols.map { s in Indicators.logReturns(days.compactMap { maps[s]?[$0] }) }259        return symbols.indices.map { i in symbols.indices.map { j in i == j ? 1 : Indicators.correlation(series[i], series[j]) } }260    }261}262
Files main
Menu

Theme