SPB Git

Repository Public

Performance.swift 13.8 KB 259 lines swift

1import Foundation2import SheetCore3import Statistics45public enum ReturnKind: String, Sendable, Codable, CaseIterable {6    /// P_t / P_{t−1} − 17    case simple8    /// ln(P_t / P_{t−1})9    case log10}1112public struct DrawdownResult: Sendable, Hashable, Codable {13    /// Largest peak-to-trough decline as a positive fraction of the peak (0.25 = −25 %).14    public var maxDrawdown: Double15    /// Index (into the value series) of the peak before the worst decline, and of its trough.16    public var peakIndex: Int17    public var troughIndex: Int18    /// First index after the trough at which the value regains the peak; nil if it never does.19    public var recoveryIndex: Int?20}2122public struct BenchmarkStatistics: Sendable, Hashable, Codable, TableReport {23    /// cov(r − r_f, m − r_f) / var(m − r_f) (sample moments).24    public var beta: Double25    /// Jensen's alpha per period: mean(r − r_f) − β·mean(m − r_f).26    public var alphaPerPeriod: Double27    /// Alpha per period × periods per year (arithmetic annualisation).28    public var alphaAnnualized: Double29    public var correlation: Double30    public var rSquared: Double31    /// Sample standard deviation of (r − m), annualised by √periods.32    public var trackingError: Double33    /// Annualised mean active return ÷ tracking error.34    public var informationRatio: Double3536    public func table() -> [[Value]] {37        [Report.row("Beta", beta), Report.row("Alpha (per period)", alphaPerPeriod), Report.row("Alpha (annualised)", alphaAnnualized),38         Report.row("Correlation", correlation), Report.row("R²", rSquared), Report.row("Tracking error (annualised)", trackingError),39         Report.row("Information ratio", informationRatio)]40    }41}4243public enum VaRMethod: String, Sendable, Codable, CaseIterable {44    /// Empirical quantile of the observed returns.45    case historical46    /// Normal distribution with the sample mean and sample standard deviation.47    case parametricNormal48}4950public struct RiskMeasure: Sendable, Hashable, Codable {51    public var confidence: Double52    public var method: VaRMethod53    /// Value at risk as a positive loss fraction for one period.54    public var valueAtRisk: Double55    /// Conditional VaR (expected shortfall): mean loss beyond the VaR, positive.56    public var conditionalVaR: Double57}5859public struct PerformanceSummary: Sendable, Hashable, Codable, TableReport {60    public var observations: Int61    public var periodsPerYear: Double62    public var meanReturn: Double63    public var cumulativeReturn: Double64    public var annualizedReturn: Double65    public var annualizedVolatility: Double66    public var sharpeRatio: Double67    public var sortinoRatio: Double68    public var maxDrawdown: Double69    public var historicalVaR95: Double70    public var historicalCVaR95: Double71    public var bestPeriod: Double72    public var worstPeriod: Double7374    public func table() -> [[Value]] {75        [Report.row("Observations", observations), Report.row("Periods per year", periodsPerYear), Report.row("Mean return (per period)", meanReturn),76         Report.row("Cumulative return", cumulativeReturn), Report.row("Annualised return (geometric)", annualizedReturn),77         Report.row("Annualised volatility", annualizedVolatility), Report.row("Sharpe ratio", sharpeRatio), Report.row("Sortino ratio", sortinoRatio),78         Report.row("Maximum drawdown", maxDrawdown), Report.row("Historical VaR 95 %", historicalVaR95), Report.row("Historical CVaR 95 %", historicalCVaR95),79         Report.row("Best period", bestPeriod), Report.row("Worst period", worstPeriod)]80    }81}8283/// Return, risk and performance statistics. Every annualised figure states its `periodsPerYear`84/// (252 trading days, 52 weeks, 12 months…) — nothing is assumed.85public enum PortfolioAnalytics {86    // MARK: Returns8788    /// Period returns from a price series (n prices → n − 1 returns).89    public static func returns(prices: [Double], kind: ReturnKind = .simple) -> [Double] {90        guard prices.count > 1 else { return [] }91        return (1..<prices.count).map { kind == .simple ? prices[$0] / prices[$0 - 1] - 1 : Foundation.log(prices[$0] / prices[$0 - 1]) }92    }9394    /// Compounded return over the whole sample: Π(1 + r) − 1 (simple) or exp(Σ r) − 1 (log).95    public static func cumulativeReturn(_ r: [Double], kind: ReturnKind = .simple) -> Double {96        kind == .simple ? expm1(r.reduce(0) { $0 + log1p($1) }) : expm1(Descriptive.sum(r))97    }9899    /// Geometric annualised return: (1 + cumulative)^(periodsPerYear / n) − 1.100    public static func annualizedReturn(_ r: [Double], periodsPerYear: Double, kind: ReturnKind = .simple) -> Double {101        guard !r.isEmpty else { return .nan }102        let logTotal = kind == .simple ? r.reduce(0) { $0 + log1p($1) } : Descriptive.sum(r)103        return expm1(logTotal * periodsPerYear / Double(r.count))104    }105106    /// Arithmetic annualised return: mean × periodsPerYear.107    public static func annualizedMeanReturn(_ r: [Double], periodsPerYear: Double) -> Double { Descriptive.mean(r) * periodsPerYear }108109    /// Sample standard deviation (n − 1) × √periodsPerYear.110    public static func annualizedVolatility(_ r: [Double], periodsPerYear: Double) -> Double {111        Descriptive.standardDeviation(r) * periodsPerYear.squareRoot()112    }113114    // MARK: Co-movement115116    /// Sample covariance matrix (n − 1) of several return series (one inner array per asset, equal lengths).117    public static func covarianceMatrix(_ series: [[Double]]) throws -> Matrix {118        guard let n = series.first?.count, n > 1, series.allSatisfy({ $0.count == n }) else {119            throw StatError.invalidInput("return series must have the same length (at least 2 observations)")120        }121        var m = Matrix(rows: series.count, cols: series.count)122        for i in series.indices { for j in i..<series.count {123            let c = Descriptive.covariance(series[i], series[j])124            m[i, j] = c; m[j, i] = c125        } }126        return m127    }128129    /// Pearson correlation matrix of several return series.130    public static func correlationMatrix(_ series: [[Double]]) throws -> Matrix {131        let cov = try covarianceMatrix(series)132        var m = cov133        for i in 0..<cov.rows { for j in 0..<cov.cols { m[i, j] = i == j ? 1 : cov[i, j] / (cov[i, i] * cov[j, j]).squareRoot() } }134        return m135    }136137    /// wᵀμ138    public static func portfolioReturn(weights w: [Double], expectedReturns mu: [Double]) -> Double {139        zip(w, mu).reduce(0) { $0 + $1.0 * $1.1 }140    }141142    /// wᵀΣw143    public static func portfolioVariance(weights w: [Double], covariance cov: Matrix) -> Double {144        let sw = cov * w145        return zip(w, sw).reduce(0) { $0 + $1.0 * $1.1 }146    }147148    /// Period returns of a portfolio rebalanced to constant weights every period.149    public static func portfolioReturns(weights w: [Double], series: [[Double]]) -> [Double] {150        guard let n = series.first?.count, series.count == w.count else { return [] }151        return (0..<n).map { t in zip(w, series).reduce(0) { $0 + $1.0 * $1.1[t] } }152    }153154    // MARK: Risk-adjusted performance155156    /// Sharpe ratio: mean(r − r_f) / sd(r − r_f) × √periodsPerYear, sample standard deviation;157    /// `riskFreePerPeriod` is the risk-free return for one period (not annual).158    public static func sharpeRatio(_ r: [Double], riskFreePerPeriod rf: Double = 0, periodsPerYear: Double) -> Double {159        let ex = r.map { $0 - rf }160        let sd = Descriptive.standardDeviation(ex)161        return sd > 0 ? Descriptive.mean(ex) / sd * periodsPerYear.squareRoot() : .nan162    }163164    /// Downside deviation relative to a minimum acceptable return (MAR) per period:165    /// √( Σ min(r − MAR, 0)² / n ) — the sum runs over ALL n observations (Sortino's target semideviation).166    public static func downsideDeviation(_ r: [Double], minimumAcceptableReturn mar: Double = 0) -> Double {167        guard !r.isEmpty else { return .nan }168        return (r.reduce(0) { $0 + pow(Swift.min($1 - mar, 0), 2) } / Double(r.count)).squareRoot()169    }170171    /// Sortino ratio: (mean(r) − MAR) / downside deviation × √periodsPerYear.172    public static func sortinoRatio(_ r: [Double], minimumAcceptableReturn mar: Double = 0, periodsPerYear: Double) -> Double {173        let dd = downsideDeviation(r, minimumAcceptableReturn: mar)174        return dd > 0 ? (Descriptive.mean(r) - mar) / dd * periodsPerYear.squareRoot() : .nan175    }176177    /// Maximum drawdown of a value (price / wealth) series.178    public static func maxDrawdown(values: [Double]) -> DrawdownResult? {179        guard !values.isEmpty else { return nil }180        var peak = values[0], peakIdx = 0181        var worst = 0.0, worstPeak = 0, worstTrough = 0182        for (i, v) in values.enumerated() {183            if v > peak { peak = v; peakIdx = i }184            let dd = peak > 0 ? (peak - v) / peak : 0185            if dd > worst { worst = dd; worstPeak = peakIdx; worstTrough = i }186        }187        var recovery: Int?188        if worst > 0 { recovery = values.indices.first { $0 > worstTrough && values[$0] >= values[worstPeak] } }189        return DrawdownResult(maxDrawdown: worst, peakIndex: worstPeak, troughIndex: worstTrough, recoveryIndex: recovery)190    }191192    /// Maximum drawdown of the wealth index 1, (1+r₁), (1+r₁)(1+r₂), … built from simple returns193    /// (indices refer to that index series, i.e. index k = after k returns).194    public static func maxDrawdown(returns r: [Double]) -> DrawdownResult? {195        var wealth = [1.0]196        for x in r { wealth.append(wealth[wealth.count - 1] * (1 + x)) }197        return maxDrawdown(values: wealth)198    }199200    /// Beta, Jensen's alpha and tracking statistics against a benchmark (equal-length period returns).201    public static func benchmarkStatistics(_ r: [Double], benchmark m: [Double], riskFreePerPeriod rf: Double = 0, periodsPerYear: Double) throws -> BenchmarkStatistics {202        guard r.count == m.count, r.count > 2 else { throw StatError.invalidInput("asset and benchmark need the same number (≥ 3) of returns") }203        let er = r.map { $0 - rf }, em = m.map { $0 - rf }204        let varM = Descriptive.variance(em)205        guard varM > 0 else { throw StatError.singular("the benchmark has no variance") }206        let beta = Descriptive.covariance(er, em) / varM207        let alpha = Descriptive.mean(er) - beta * Descriptive.mean(em)208        let corr = Descriptive.pearson(er, em)209        let active = zip(r, m).map { $0 - $1 }210        let te = Descriptive.standardDeviation(active) * periodsPerYear.squareRoot()211        return BenchmarkStatistics(beta: beta, alphaPerPeriod: alpha, alphaAnnualized: alpha * periodsPerYear, correlation: corr,212                                   rSquared: corr * corr, trackingError: te,213                                   informationRatio: te > 0 ? Descriptive.mean(active) * periodsPerYear / te : .nan)214    }215216    // MARK: Value at risk217218    /// Quantile with linear interpolation between order statistics (Hyndman–Fan type 7, the NumPy/Excel PERCENTILE.INC default).219    static func quantile7(_ sorted: [Double], _ p: Double) -> Double {220        let h = Double(sorted.count - 1) * p221        let lo = Int(h.rounded(.down)), hi = Swift.min(lo + 1, sorted.count - 1)222        return sorted[lo] + (h - Double(lo)) * (sorted[hi] - sorted[lo])223    }224225    /// One-period value at risk and conditional VaR at a confidence level (e.g. 0.95), as positive loss fractions.226    ///227    /// Historical: VaR = −q where q is the (1 − c) type-7 quantile of the returns; CVaR = −mean of the228    /// returns ≤ q. Parametric normal: VaR = −(μ̂ + σ̂·z₁₋c), CVaR = −μ̂ + σ̂·φ(z₁₋c)/(1 − c), with the229    /// sample mean and the sample (n − 1) standard deviation.230    public static func valueAtRisk(_ r: [Double], confidence c: Double = 0.95, method: VaRMethod = .historical) throws -> RiskMeasure {231        guard r.count >= 2 else { throw StatError.insufficientData("VaR needs at least two returns") }232        guard c > 0, c < 1 else { throw StatError.invalidInput("confidence must be between 0 and 1") }233        switch method {234        case .historical:235            let q = quantile7(r.sorted(), 1 - c)236            let tail = r.filter { $0 <= q }237            return RiskMeasure(confidence: c, method: method, valueAtRisk: -q, conditionalVaR: -Descriptive.mean(tail))238        case .parametricNormal:239            let mu = Descriptive.mean(r), sd = Descriptive.standardDeviation(r)240            let z = NormalDistribution.standard.quantile(1 - c)241            return RiskMeasure(confidence: c, method: method, valueAtRisk: -(mu + sd * z),242                               conditionalVaR: -mu + sd * NormalDistribution.standard.pdf(z) / (1 - c))243        }244    }245246    /// One-table summary of a simple-return series.247    public static func summary(_ r: [Double], riskFreePerPeriod: Double = 0, periodsPerYear: Double) throws -> PerformanceSummary {248        guard r.count >= 2 else { throw StatError.insufficientData("at least two returns are needed") }249        let hist = try valueAtRisk(r, confidence: 0.95, method: .historical)250        return PerformanceSummary(observations: r.count, periodsPerYear: periodsPerYear, meanReturn: Descriptive.mean(r),251                                  cumulativeReturn: cumulativeReturn(r), annualizedReturn: annualizedReturn(r, periodsPerYear: periodsPerYear),252                                  annualizedVolatility: annualizedVolatility(r, periodsPerYear: periodsPerYear),253                                  sharpeRatio: sharpeRatio(r, riskFreePerPeriod: riskFreePerPeriod, periodsPerYear: periodsPerYear),254                                  sortinoRatio: sortinoRatio(r, minimumAcceptableReturn: riskFreePerPeriod, periodsPerYear: periodsPerYear),255                                  maxDrawdown: maxDrawdown(returns: r)?.maxDrawdown ?? 0, historicalVaR95: hist.valueAtRisk,256                                  historicalCVaR95: hist.conditionalVaR, bestPeriod: r.max() ?? .nan, worstPeriod: r.min() ?? .nan)257    }258}259
Files main
Menu

Theme