Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Analytics/Indicators.swift3// Description: Technical indicators and series statistics computed on this Mac from bars the server returned (display aids, not research results).4import Foundation56/// These are deterministic transforms of the bars shown on a chart. Each output has the length of its input, with7/// nil where the indicator is not defined yet (warm-up): the chart leaves those positions empty.8public enum Indicators {9 public static func sma(_ x: [Double], _ n: Int) -> [Double?] {10 guard n > 0, x.count >= n else { return Array(repeating: nil, count: x.count) }11 var out = [Double?](repeating: nil, count: x.count)12 var sum = 0.013 for i in x.indices {14 sum += x[i]15 if i >= n { sum -= x[i - n] }16 if i >= n - 1 { out[i] = sum / Double(n) }17 }18 return out19 }2021 /// Exponential average seeded with the simple average of the first n values.22 public static func ema(_ x: [Double], _ n: Int) -> [Double?] {23 guard n > 0, x.count >= n else { return Array(repeating: nil, count: x.count) }24 var out = [Double?](repeating: nil, count: x.count)25 let k = 2.0 / Double(n + 1)26 var e = x[0..<n].reduce(0, +) / Double(n)27 out[n - 1] = e28 for i in n..<x.count { e = x[i] * k + e * (1 - k); out[i] = e }29 return out30 }3132 public struct Bands: Sendable, Equatable {33 public var middle: [Double?]; public var upper: [Double?]; public var lower: [Double?]34 public init(middle: [Double?] = [], upper: [Double?] = [], lower: [Double?] = []) { self.middle = middle; self.upper = upper; self.lower = lower }35 }3637 /// Bollinger bands: SMA(n) ± k population standard deviations.38 public static func bollinger(_ x: [Double], _ n: Int = 20, k: Double = 2) -> Bands {39 let mid = sma(x, n)40 var up = [Double?](repeating: nil, count: x.count), lo = up41 guard n > 0, x.count >= n else { return Bands(middle: mid, upper: up, lower: lo) }42 for i in (n - 1)..<x.count {43 guard let m = mid[i] else { continue }44 var v = 0.045 for j in (i - n + 1)...i { v += (x[j] - m) * (x[j] - m) }46 let sd = (v / Double(n)).squareRoot()47 up[i] = m + k * sd; lo[i] = m - k * sd48 }49 return Bands(middle: mid, upper: up, lower: lo)50 }5152 /// Wilder's RSI.53 public static func rsi(_ x: [Double], _ n: Int = 14) -> [Double?] {54 var out = [Double?](repeating: nil, count: x.count)55 guard n > 0, x.count > n else { return out }56 var gain = 0.0, loss = 0.057 for i in 1...n { let d = x[i] - x[i - 1]; if d >= 0 { gain += d } else { loss -= d } }58 gain /= Double(n); loss /= Double(n)59 out[n] = loss == 0 ? (gain == 0 ? 50 : 100) : 100 - 100 / (1 + gain / loss)60 if x.count > n + 1 {61 for i in (n + 1)..<x.count {62 let d = x[i] - x[i - 1]63 gain = (gain * Double(n - 1) + max(d, 0)) / Double(n)64 loss = (loss * Double(n - 1) + max(-d, 0)) / Double(n)65 out[i] = loss == 0 ? (gain == 0 ? 50 : 100) : 100 - 100 / (1 + gain / loss)66 }67 }68 return out69 }7071 public struct MACD: Sendable, Equatable {72 public var macd: [Double?]; public var signal: [Double?]; public var histogram: [Double?]73 public init(macd: [Double?] = [], signal: [Double?] = [], histogram: [Double?] = []) { self.macd = macd; self.signal = signal; self.histogram = histogram }74 }7576 public static func macd(_ x: [Double], fast: Int = 12, slow: Int = 26, signal: Int = 9) -> MACD {77 let f = ema(x, fast), s = ema(x, slow)78 var line = [Double?](repeating: nil, count: x.count)79 for i in x.indices { if let a = f[i], let b = s[i] { line[i] = a - b } }80 var sig = [Double?](repeating: nil, count: x.count)81 if let first = line.firstIndex(where: { $0 != nil }) {82 let tail = line[first...].map { $0! }83 let e = ema(tail, signal)84 for (k, v) in e.enumerated() { sig[first + k] = v }85 }86 var hist = [Double?](repeating: nil, count: x.count)87 for i in x.indices { if let a = line[i], let b = sig[i] { hist[i] = a - b } }88 return MACD(macd: line, signal: sig, histogram: hist)89 }90}9192public enum SeriesStats {93 /// Simple returns r[i] = x[i]/x[i-1] − 1, one fewer than the input. Non-positive prices break the chain: the return is skipped.94 public static func returns(_ x: [Double]) -> [Double] {95 guard x.count > 1 else { return [] }96 var out: [Double] = []; out.reserveCapacity(x.count - 1)97 for i in 1..<x.count where x[i - 1] > 0 { out.append(x[i] / x[i - 1] - 1) }98 return out99 }100101 /// Drawdown from the running peak, in percent (≤ 0), same length as the input.102 public static func drawdown(_ x: [Double]) -> [Double] {103 var peak = -Double.infinity104 return x.map { v in peak = max(peak, v); return peak > 0 ? (v / peak - 1) * 100 : 0 }105 }106107 public static func mean(_ x: [Double]) -> Double? { x.isEmpty ? nil : x.reduce(0, +) / Double(x.count) }108109 /// Sample standard deviation (n − 1).110 public static func stdev(_ x: [Double]) -> Double? {111 guard x.count > 1, let m = mean(x) else { return nil }112 return (x.reduce(0) { $0 + ($1 - m) * ($1 - m) } / Double(x.count - 1)).squareRoot()113 }114115 public static func correlation(_ a: [Double], _ b: [Double]) -> Double? {116 let n = min(a.count, b.count)117 guard n > 2 else { return nil }118 let x = Array(a.suffix(n)), y = Array(b.suffix(n))119 guard let mx = mean(x), let my = mean(y) else { return nil }120 var sxy = 0.0, sxx = 0.0, syy = 0.0121 for i in 0..<n { sxy += (x[i] - mx) * (y[i] - my); sxx += (x[i] - mx) * (x[i] - mx); syy += (y[i] - my) * (y[i] - my) }122 guard sxx > 0, syy > 0 else { return nil }123 return sxy / (sxx * syy).squareRoot()124 }125126 public struct Histogram: Sendable, Equatable { public var edges: [Double]; public var counts: [Int] }127128 public static func histogram(_ x: [Double], bins: Int) -> Histogram? {129 guard bins > 0, let lo = x.min(), let hi = x.max(), hi > lo else { return nil }130 let w = (hi - lo) / Double(bins)131 var counts = [Int](repeating: 0, count: bins)132 for v in x { counts[min(bins - 1, Int((v - lo) / w))] += 1 }133 return Histogram(edges: (0...bins).map { lo + Double($0) * w }, counts: counts)134 }135136 /// Returns of several series aligned on the dates they all share (inner join), in date order.137 public static func alignedReturns(_ series: [(symbol: String, bars: [Bar])]) -> (dates: [Date], returns: [String: [Double]]) {138 guard !series.isEmpty else { return ([], [:]) }139 var common = Set(series[0].bars.map(\.time))140 for s in series.dropFirst() { common.formIntersection(s.bars.map(\.time)) }141 let dates = common.sorted()142 guard dates.count > 1 else { return ([], [:]) }143 var out: [String: [Double]] = [:]144 for s in series {145 let byDate = Dictionary(s.bars.map { ($0.time, $0.close) }, uniquingKeysWith: { $1 })146 let closes = dates.compactMap { byDate[$0] }147 var r: [Double] = []148 for i in 1..<closes.count { r.append(closes[i - 1] > 0 ? closes[i] / closes[i - 1] - 1 : 0) }149 out[s.symbol] = r150 }151 return (Array(dates.dropFirst()), out)152 }153}154155/// Visual reduction of a long series for drawing. The source bars are never modified: this only decides which156/// vertical extent a pixel column shows, and the result says how many source bars each drawn bar stands for.157public enum Downsampler {158 public struct Bucket: Sendable, Equatable {159 public var bar: Bar160 /// number of source bars merged into this one (1 = drawn as received)161 public var count: Int162 public var firstIndex: Int163 }164165 /// Merges consecutive bars into at most `maxBuckets` OHLC buckets (open of the first, close of the last, extreme166 /// high and low, summed volume). Extremes are preserved exactly, which a point-sampling reduction would lose.167 public static func ohlc(_ bars: ArraySlice<Bar>, maxBuckets: Int) -> [Bucket] {168 guard maxBuckets > 0, !bars.isEmpty else { return [] }169 if bars.count <= maxBuckets { return bars.indices.map { Bucket(bar: bars[$0], count: 1, firstIndex: $0) } }170 let per = Int((Double(bars.count) / Double(maxBuckets)).rounded(.up))171 var out: [Bucket] = []; out.reserveCapacity(maxBuckets)172 var i = bars.startIndex173 while i < bars.endIndex {174 let end = min(i + per, bars.endIndex)175 var b = bars[i]176 for j in (i + 1)..<end { let x = bars[j]; b.high = max(b.high, x.high); b.low = min(b.low, x.low); b.close = x.close; b.volume += x.volume }177 out.append(Bucket(bar: b, count: end - i, firstIndex: i))178 i = end179 }180 return out181 }182 // MARK: aligned reduction (the renderer's per-zoom-level cache)183184 /// Source bars per drawn mark when `visible` bars must fit in `maxBuckets` marks (1 = every bar is drawn).185 public static func per(visible: Int, maxBuckets: Int) -> Int {186 guard visible > 0, maxBuckets > 0, visible > maxBuckets else { return 1 }187 return Int((Double(visible) / Double(maxBuckets)).rounded(.up))188 }189190 /// The whole series merged `per` bars at a time, bucket k covering bars [k·per, (k+1)·per). Because the buckets191 /// are aligned on the series and not on the visible window, the same list serves every pan position at that zoom192 /// level (it is computed once and cached), and marks do not regroup while the chart scrolls.193 public static func ohlcAligned(_ bars: [Bar], per: Int) -> [Bucket] {194 guard per > 0, !bars.isEmpty else { return [] }195 var out: [Bucket] = []; out.reserveCapacity(bars.count / per + 1)196 var i = 0197 while i < bars.count {198 let end = min(i + per, bars.count)199 var b = bars[i]200 var j = i + 1201 while j < end { let x = bars[j]; if x.high > b.high { b.high = x.high }; if x.low < b.low { b.low = x.low }; b.close = x.close; b.volume += x.volume; j += 1 }202 out.append(Bucket(bar: b, count: end - i, firstIndex: i))203 i = end204 }205 return out206 }207208 /// The aligned buckets that intersect the visible bars.209 public static func bucketRange(_ visible: Range<Int>, per: Int, total: Int) -> Range<Int> {210 guard per > 0, !visible.isEmpty else { return 0..<0 }211 let a = max(0, visible.lowerBound / per), b = min(total, (visible.upperBound + per - 1) / per)212 return a..<max(a, b)213 }214215 /// What one mark of a reduced line shows: the first and last defined values of its bars and their extremes, so a216 /// line drawn through first → low → high → last covers exactly the pixels the full line would.217 public struct Envelope: Sendable, Equatable { public var first: Double, lo: Double, hi: Double, last: Double }218219 /// A series (an indicator: nil where it is undefined) reduced `per` values at a time, aligned like `ohlcAligned`.220 public static func envelope(_ s: [Double?], per: Int) -> [Envelope?] {221 guard per > 0, !s.isEmpty else { return [] }222 var out: [Envelope?] = []; out.reserveCapacity(s.count / per + 1)223 var i = 0224 while i < s.count {225 let end = min(i + per, s.count)226 var e: Envelope?227 var j = i228 while j < end {229 if let v = s[j] {230 if e == nil { e = Envelope(first: v, lo: v, hi: v, last: v) } else { if v < e!.lo { e!.lo = v }; if v > e!.hi { e!.hi = v }; e!.last = v }231 }232 j += 1233 }234 out.append(e)235 i = end236 }237 return out238 }239}240