SPB Git

Repository Public

MeanVariance.swift 11.2 KB 192 lines swift

1import Foundation2import SheetCore3import Statistics45public struct FrontierPoint: Sendable, Hashable, Codable {6    public var expectedReturn: Double7    public var variance: Double8    public var volatility: Double9    public var weights: [Double]10}1112public struct EfficientFrontier: Sendable, Hashable, Codable, TableReport {13    /// True when weights were constrained to be non-negative.14    public var longOnly: Bool15    public var assetNames: [String]16    /// Points ordered by increasing expected return, from the minimum-variance portfolio upward.17    public var points: [FrontierPoint]18    public var minimumVariance: FrontierPoint1920    public func table() -> [[Value]] {21        var out: [[Value]] = [[.text("Expected return"), .text("Volatility")] + assetNames.map { Value.text($0) }]22        for p in points { out.append([Report.num(p.expectedReturn), Report.num(p.volatility)] + p.weights.map { Report.num($0) }) }23        return out24    }25}2627/// Markowitz mean–variance optimisation.28///29/// Unconstrained (short sales allowed, fully invested) portfolios use the closed forms with30/// A = 1ᵀΣ⁻¹1, B = 1ᵀΣ⁻¹μ, C = μᵀΣ⁻¹μ, D = AC − B². Long-only portfolios solve the quadratic31/// programme min wᵀΣw s.t. 1ᵀw = 1, (μᵀw = m), w ≥ 0 with a primal active-set method.32public enum MeanVariance {33    private static func point(_ w: [Double], _ mu: [Double], _ cov: Matrix) -> FrontierPoint {34        let v = Swift.max(0, PortfolioAnalytics.portfolioVariance(weights: w, covariance: cov))35        return FrontierPoint(expectedReturn: PortfolioAnalytics.portfolioReturn(weights: w, expectedReturns: mu), variance: v, volatility: v.squareRoot(), weights: w)36    }3738    private static func check(_ mu: [Double], _ cov: Matrix) throws {39        guard mu.count >= 2, cov.rows == mu.count, cov.cols == mu.count else { throw StatError.invalidInput("need ≥ 2 assets and a square covariance matrix of matching size") }40    }4142    private static func constants(_ mu: [Double], _ cov: Matrix) throws -> (sInvOne: [Double], sInvMu: [Double], a: Double, b: Double, c: Double) {43        try check(mu, cov)44        let ones = [Double](repeating: 1, count: mu.count)45        let s1 = try LinearAlgebra.solve(cov, ones), sm = try LinearAlgebra.solve(cov, mu)46        return (s1, sm, s1.reduce(0, +), sm.reduce(0, +), zip(mu, sm).reduce(0) { $0 + $1.0 * $1.1 })47    }4849    /// Global minimum-variance portfolio, short sales allowed: w = Σ⁻¹1 / (1ᵀΣ⁻¹1).50    public static func minimumVariancePortfolio(expectedReturns mu: [Double], covariance cov: Matrix) throws -> FrontierPoint {51        let k = try constants(mu, cov)52        return point(k.sInvOne.map { $0 / k.a }, mu, cov)53    }5455    /// Tangency (maximum Sharpe) portfolio, short sales allowed: w ∝ Σ⁻¹(μ − r_f). Throws when the56    /// minimum-variance return does not exceed r_f (no finite tangency portfolio on the efficient branch).57    public static func tangencyPortfolio(expectedReturns mu: [Double], covariance cov: Matrix, riskFree rf: Double) throws -> FrontierPoint {58        try check(mu, cov)59        let z = try LinearAlgebra.solve(cov, mu.map { $0 - rf })60        let total = z.reduce(0, +)61        guard total > 1e-14 else { throw StatError.invalidInput("no tangency portfolio: the risk-free rate is not below the minimum-variance return") }62        return point(z.map { $0 / total }, mu, cov)63    }6465    /// Minimum-variance portfolio for a target expected return, short sales allowed:66    /// w = Σ⁻¹[(C − mB)·1 + (mA − B)·μ] / D.67    public static func efficientPortfolio(expectedReturns mu: [Double], covariance cov: Matrix, targetReturn m: Double) throws -> FrontierPoint {68        let k = try constants(mu, cov)69        let d = k.a * k.c - k.b * k.b70        guard d > 1e-12 * abs(k.a * k.c) else { throw StatError.singular("all expected returns are equal: the frontier is a single point") }71        let w = (0..<mu.count).map { ((k.c - m * k.b) * k.sInvOne[$0] + (m * k.a - k.b) * k.sInvMu[$0]) / d }72        return point(w, mu, cov)73    }7475    /// Unconstrained efficient frontier: `count` portfolios with returns evenly spaced from the76    /// minimum-variance return to `maxReturn` (default: the largest asset return).77    public static func frontier(expectedReturns mu: [Double], covariance cov: Matrix, count: Int = 25, maxReturn: Double? = nil,78                                assetNames: [String]? = nil) throws -> EfficientFrontier {79        let gmv = try minimumVariancePortfolio(expectedReturns: mu, covariance: cov)80        let top = maxReturn ?? (mu.max() ?? gmv.expectedReturn)81        guard count >= 2, top > gmv.expectedReturn else { throw StatError.invalidInput("need at least 2 points and a maximum return above the minimum-variance return") }82        let pts = try (0..<count).map { k in83            try efficientPortfolio(expectedReturns: mu, covariance: cov, targetReturn: gmv.expectedReturn + (top - gmv.expectedReturn) * Double(k) / Double(count - 1))84        }85        return EfficientFrontier(longOnly: false, assetNames: assetNames ?? mu.indices.map { "Asset \($0 + 1)" }, points: pts, minimumVariance: gmv)86    }8788    // MARK: Long-only (quadratic programme)8990    /// Primal active-set solver for min ½wᵀQw s.t. A w = b, w ≥ 0 with Q positive definite and a91    /// feasible starting point. Each iteration solves the equality-constrained problem on the free92    /// variables through its KKT system, steps to the nearest bound when the solution is infeasible,93    /// and releases the bound with the most negative multiplier until all multipliers are ≥ 0.94    static func solveNonNegativeQP(q: Matrix, a: [[Double]], b: [Double], start: [Double]) throws -> [Double] {95        let n = q.rows, k = a.count96        var w = start97        let scale = Swift.max(q.diagonalValues.map { abs($0) }.max() ?? 1, 1e-300)98        var active = Set((0..<n).filter { w[$0] <= 0 })99        for i in active { w[i] = 0 }100        for _ in 0..<(50 * n + 100) {101            let free = (0..<n).filter { !active.contains($0) }102            let f = free.count103            guard f >= k else { throw StatError.singular("degenerate portfolio problem (fewer free assets than constraints)") }104            var kkt = Matrix(rows: f + k, cols: f + k)105            var rhs = [Double](repeating: 0, count: f + k)106            for (i, gi) in free.enumerated() {107                for (j, gj) in free.enumerated() { kkt[i, j] = q[gi, gj] / scale }108                for c in 0..<k { kkt[i, f + c] = a[c][gi]; kkt[f + c, i] = a[c][gi] }109            }110            for c in 0..<k { rhs[f + c] = b[c] }111            let sol = try LinearAlgebra.solve(kkt, rhs)112            let x = Array(sol[0..<f])113            let multipliers = Array(sol[f...])       // μ with (Q/scale)·w + Aᵀμ = ν on the bounds114            let tol = 1e-12115            if x.allSatisfy({ $0 >= -tol }) {116                for (i, gi) in free.enumerated() { w[gi] = Swift.max(x[i], 0) }117                // multipliers of the active bounds: ν_i = (Qw)_i/scale + Σ_c μ_c a_ci must be ≥ 0118                let qw = q * w119                var worst = -1e-10, release: Int?120                for i in active {121                    var nu = qw[i] / scale122                    for c in 0..<k { nu += multipliers[c] * a[c][i] }123                    if nu < worst { worst = nu; release = i }124                }125                guard let r = release else { return w }126                active.remove(r)127            } else {128                var alpha = 1.0, blocking: Int?129                for (i, gi) in free.enumerated() where x[i] < -tol {130                    let step = w[gi] / (w[gi] - x[i])       // in [0, 1): where this weight reaches zero131                    if blocking == nil || step < alpha { alpha = step; blocking = gi }132                }133                guard let hit = blocking else { throw StatError.notConverged("active-set step") }134                for (i, gi) in free.enumerated() { w[gi] += alpha * (x[i] - w[gi]) }135                w[hit] = 0136                active.insert(hit)137            }138        }139        throw StatError.notConverged("long-only optimisation did not settle on an active set")140    }141142    /// Long-only global minimum-variance portfolio (w ≥ 0, Σw = 1).143    public static func longOnlyMinimumVariance(expectedReturns mu: [Double], covariance cov: Matrix) throws -> FrontierPoint {144        try check(mu, cov)145        let n = mu.count146        let w = try solveNonNegativeQP(q: cov, a: [[Double](repeating: 1, count: n)], b: [1], start: [Double](repeating: 1 / Double(n), count: n))147        return point(w, mu, cov)148    }149150    /// Long-only minimum-variance portfolio with expected return exactly `targetReturn`151    /// (which must lie between the smallest and the largest asset return).152    public static func longOnlyEfficientPortfolio(expectedReturns mu: [Double], covariance cov: Matrix, targetReturn m: Double) throws -> FrontierPoint {153        try check(mu, cov)154        let n = mu.count155        guard let hi = mu.indices.max(by: { mu[$0] < mu[$1] }), let lo = mu.indices.min(by: { mu[$0] < mu[$1] }) else { throw StatError.invalidInput("no assets") }156        let span = mu[hi] - mu[lo]157        guard span > 0 else { throw StatError.singular("all expected returns are equal") }158        guard m >= mu[lo] - 1e-12 * abs(mu[lo]), m <= mu[hi] + 1e-12 * abs(mu[hi]) else {159            throw StatError.invalidInput("a long-only portfolio cannot reach this return: it must lie between the lowest and highest asset returns")160        }161        // The extremes are single-asset portfolios (the KKT system degenerates there).162        var w = [Double](repeating: 0, count: n)163        if m >= mu[hi] - 1e-13 * span {164            let ties = mu.indices.filter { mu[$0] >= mu[hi] - 1e-13 * span }165            w[ties.min { cov[$0, $0] < cov[$1, $1] } ?? hi] = 1166            return point(w, mu, cov)167        }168        if m <= mu[lo] + 1e-13 * span {169            let ties = mu.indices.filter { mu[$0] <= mu[lo] + 1e-13 * span }170            w[ties.min { cov[$0, $0] < cov[$1, $1] } ?? lo] = 1171            return point(w, mu, cov)172        }173        // feasible start: the two extreme assets mixed to hit the target174        w[hi] = (m - mu[lo]) / span175        w[lo] = 1 - w[hi]176        let sol = try solveNonNegativeQP(q: cov, a: [[Double](repeating: 1, count: n), mu], b: [1, m], start: w)177        return point(sol, mu, cov)178    }179180    /// Long-only efficient frontier: `count` portfolios with returns evenly spaced from the long-only181    /// minimum-variance return to the highest asset return.182    public static func longOnlyFrontier(expectedReturns mu: [Double], covariance cov: Matrix, count: Int = 25, assetNames: [String]? = nil) throws -> EfficientFrontier {183        let gmv = try longOnlyMinimumVariance(expectedReturns: mu, covariance: cov)184        guard count >= 2, let top = mu.max(), top > gmv.expectedReturn else { throw StatError.invalidInput("need at least 2 points and an asset with a return above the minimum-variance return") }185        var pts = [gmv]186        for k in 1..<count {187            pts.append(try longOnlyEfficientPortfolio(expectedReturns: mu, covariance: cov, targetReturn: gmv.expectedReturn + (top - gmv.expectedReturn) * Double(k) / Double(count - 1)))188        }189        return EfficientFrontier(longOnly: true, assetNames: assetNames ?? mu.indices.map { "Asset \($0 + 1)" }, points: pts, minimumVariance: gmv)190    }191}192
Files main
Menu

Theme