SPB Git

Repository Public MIT

InvestmentOptionTests.swift 28.7 KB 376 lines swift

1// ORIX Calc2// File: Packages/ORIXFinancial/Tests/ORIXFinancialTests/InvestmentOptionTests.swift3// Description: Tests for investment analysis, options (BSM, Greeks, implied volatility, binomial trees, strategies) and Sensitivity Studio.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import Testing9import ORIXNumerics10@testable import ORIXFinancial1112@Suite struct InvestmentTests {13    @Test func moneyWeightedReturnMatchesReference() throws {14        let cases = Ref.list("xirr")15        #expect(cases.count >= 3)16        for c in cases {17            let flows = (c["flows"] as! [[Any]]).map { DatedCashFlow(date: date($0[0] as! String), amount: ($0[1] as! NSNumber).doubleValue) }18            let r = try Returns.moneyWeighted(flows)19            #expect(try abs(r.uniqueRate() - c.num("rate")) < 1e-11, "\(c.str("name"))")20            #expect(r.verification.isVerified, "\(c.str("name")): \(r.verification.warnings)")21            // order of the flows does not matter22            #expect(try Returns.moneyWeighted(flows.reversed()).uniqueRate() == (r.uniqueRate()))23        }24        // Microsoft Excel documentation example for XIRR: 0.373362535 (Excel stops iterating at a 1e-8 tolerance, hence 5e-9 here)25        let excel = Ref.list("xirr").first { $0.str("name") == "excel_xirr_example" }!26        #expect(abs(excel.num("rate") - 0.373362535) < 5e-9)27    }2829    @Test func moneyWeightedAmbiguousAndImpossibleCases() throws {30        // −1000, +2300 one year later, −1320 two years later (365-day years): 10% and 20%31        let multi = try Returns.moneyWeighted([DatedCashFlow(date: date("2022-01-01"), amount: -1000), DatedCashFlow(date: date("2023-01-01"), amount: 2300),32                                               DatedCashFlow(date: date("2024-01-01"), amount: -1320)])33        guard case .multiple(let rates) = multi.outcome else { Issue.record("expected two rates, got \(multi.outcome)"); return }34        #expect(rates.count == 2 && abs(rates[0] - 0.10) < 1e-10 && abs(rates[1] - 0.20) < 1e-10 && multi.descartesSignChanges == 2)35        expectFinancialError({ _ = try multi.uniqueRate() }) { if case .multipleIRR = $0 { true } else { false } }36        let none = try Returns.moneyWeighted([DatedCashFlow(date: date("2022-01-01"), amount: 100), DatedCashFlow(date: date("2023-01-01"), amount: 50)])37        guard case .none = none.outcome else { Issue.record("expected none"); return }38        expectFinancialError({ _ = try none.uniqueRate() }) { if case .noRealIRR = $0 { true } else { false } }39        expectFinancialError({ _ = try Returns.moneyWeighted([DatedCashFlow(date: date("2022-01-01"), amount: -1), DatedCashFlow(date: date("2022-01-01"), amount: 2)]) }) {40            if case .invalidInput = $0 { true } else { false }41        }42        // exactly one year, +10%43        let simple = try Returns.moneyWeighted([DatedCashFlow(date: date("2023-03-01"), amount: -500), DatedCashFlow(date: date("2024-02-29"), amount: 550)])44        #expect(try abs(simple.uniqueRate() - 0.10) < 1e-13)45    }4647    @Test func returnMeasures() throws {48        let ref = Ref.object("returns")49        let series = ref.nums("series")50        #expect(try close(Returns.arithmeticMean(series), ref.num("arithmetic"), 1e-14))51        #expect(try close(Returns.geometricMean(series), ref.num("geometric"), 1e-14))52        #expect(try Returns.geometricMean(series) < (Returns.arithmeticMean(series)))53        #expect(try close(Returns.cagr(beginValue: 10_000, endValue: 18_500, years: 7), ref.num("cagr_10000_18500_7y"), 1e-14))54        #expect(try close(Returns.annualized(totalReturn: 0.35, years: 2.5), ref.num("annualized_35pct_2_5y"), 1e-14))55        #expect(try close(Returns.realReturn(nominal: 0.07, inflation: 0.03), ref.num("real_7_nominal_3_inflation"), 1e-14))56        #expect(try abs(Returns.nominalReturn(real: Returns.realReturn(nominal: 0.07, inflation: 0.03), inflation: 0.03) - 0.07) < 1e-15)57        #expect(try close(Returns.inflationAdjusted(amount: 1000, inflation: 0.02, years: 25), ref.num("deflate_1000_25y_2pct"), 1e-13))58        #expect(try close(Returns.inflated(amount: Returns.inflationAdjusted(amount: 1000, inflation: 0.02, years: 25), inflation: 0.02, years: 25), 1000, 1e-13))59        #expect(try Returns.holdingPeriodReturn(beginValue: 50, endValue: 54, income: 1) == 0.1)60        #expect(try Returns.geometricMean([0.5, -1, 0.2]) == -1)61        #expect(try Returns.cagr(beginValue: 100, endValue: 0, years: 3) == -1)62        expectFinancialError({ _ = try Returns.geometricMean([0.1, -1.5]) }) { if case .invalidInput = $0 { true } else { false } }63        expectFinancialError({ _ = try Returns.arithmeticMean([]) }) { if case .invalidInput = $0 { true } else { false } }64        expectFinancialError({ _ = try Returns.cagr(beginValue: 0, endValue: 10, years: 1) }) { if case .invalidInput = $0 { true } else { false } }65        expectFinancialError({ _ = try Returns.realReturn(nominal: 0.05, inflation: -1) }) { if case .invalidInput = $0 { true } else { false } }66    }6768    @Test func timeWeightedReturn() throws {69        let ref = Ref.object("returns")70        // 100 000 → 105 000, +10 000 contributed → 115 000 → 118 000, −10 000 withdrawn → 108 000 → 102 00071        let r = try Returns.timeWeighted([SubPeriod(startValue: 100_000, endValue: 105_000), SubPeriod(startValue: 115_000, endValue: 118_000),72                                          SubPeriod(startValue: 108_000, endValue: 102_000)], years: 1.5)73        #expect(close(r.cumulativeReturn, ref.num("twr"), 1e-14) && r.subPeriodReturns.count == 3 && r.verification.isVerified)74        #expect(close(r.annualizedReturn!, pow(1 + ref.num("twr"), 1 / 1.5) - 1, 1e-13))75        let v = try Returns.timeWeighted(valuations: [(100_000, 0), (105_000, 10_000), (118_000, -10_000), (102_000, 0)])76        #expect(v.cumulativeReturn == r.cumulativeReturn && v.annualizedReturn == nil)77        // flows do not change a time-weighted return: doubling every contribution leaves it unchanged78        let big = try Returns.timeWeighted([SubPeriod(startValue: 100, endValue: 110), SubPeriod(startValue: 1_000_110, endValue: 1_100_121)])79        #expect(close(big.cumulativeReturn, 0.21, 1e-12))80        expectFinancialError({ _ = try Returns.timeWeighted([SubPeriod(startValue: 0, endValue: 5)]) }) { if case .invalidInput = $0 { true } else { false } }81    }8283    @Test func lumpSumsAnnuitiesAndPerpetuities() throws {84        let ref = Ref.object("returns")85        #expect(try close(Annuity.futureValue(presentValue: 1000, rate: 0.05, periods: 10), 1628.894626777442, 1e-14))86        #expect(try close(Annuity.presentValue(futureValue: 1628.894626777442, rate: 0.05, periods: 10), 1000, 1e-14))87        #expect(try close(Annuity.presentValue(payment: 500, rate: 0.06, periods: 15, timing: .begin), ref.num("pv_annuity_due_500_6pct_15"), 1e-13))88        #expect(try close(Annuity.futureValue(payment: 500, rate: 0.06, periods: 15), ref.num("fv_annuity_ord_500_6pct_15"), 1e-13))89        #expect(try close(Annuity.futureValue(payment: 500, rate: 0.06, periods: 15, timing: .begin), ref.num("fv_annuity_ord_500_6pct_15") * 1.06, 1e-13))90        #expect(try Annuity.presentValue(payment: 100, rate: 0, periods: 12) == 1200)91        #expect(try Annuity.futureValue(payment: 100, rate: 0, periods: 12) == 1200)92        #expect(try Annuity.perpetuityPresentValue(payment: 50, rate: 0.04) == 1250)93        #expect(try Annuity.perpetuityPresentValue(payment: 50, rate: 0.04, timing: .begin) == 1300)94        #expect(try abs(Annuity.growingPerpetuityPresentValue(firstPayment: 50, rate: 0.08, growth: 0.03) - 1000) < 1e-10)95        expectFinancialError({ _ = try Annuity.perpetuityPresentValue(payment: 50, rate: 0) }) { if case .invalidInput = $0 { true } else { false } }96        expectFinancialError({ _ = try Annuity.growingPerpetuityPresentValue(firstPayment: 50, rate: 0.03, growth: 0.03) }) { if case .invalidInput = $0 { true } else { false } }97        expectFinancialError({ _ = try Annuity.growingPerpetuityPresentValue(firstPayment: 50, rate: 0.03, growth: 0.05) }) { if case .invalidInput = $0 { true } else { false } }98        // a long annuity tends to the perpetuity99        #expect(try abs(Annuity.presentValue(payment: 50, rate: 0.04, periods: 5000) - 1250) < 1e-9)100    }101102    /// Growing annuities against brute-force summation, including g = r and g within 1e-10 of r.103    @Test func growingAnnuities() throws {104        let cases = Ref.list("growing_annuities")105        #expect(cases.count >= 6)106        for c in cases {107            let timing: PaymentTiming = c.bool("due") ? .begin : .end108            let pv = try Annuity.growingAnnuityPresentValue(firstPayment: c.num("c"), rate: c.num("r"), growth: c.num("g"), periods: c.num("n"), timing: timing)109            let fv = try Annuity.growingAnnuityFutureValue(firstPayment: c.num("c"), rate: c.num("r"), growth: c.num("g"), periods: c.num("n"), timing: timing)110            #expect(close(pv, c.num("pv"), 1e-12), "g=\(c.num("g")) r=\(c.num("r")): \(pv) vs \(c.num("pv"))")111            #expect(close(fv, c.num("fv"), 1e-12))112        }113        // g == r exactly: n·C/(1+r)114        #expect(try Annuity.growingAnnuityPresentValue(firstPayment: 1000, rate: 0.05, growth: 0.05, periods: 30) == 30 * 1000 / 1.05)115        // g = 0 is the level annuity116        #expect(try close(Annuity.growingAnnuityPresentValue(firstPayment: 500, rate: 0.06, growth: 0, periods: 15),117                      Annuity.presentValue(payment: 500, rate: 0.06, periods: 15), 1e-14))118    }119}120121@Suite struct OptionTests {122    static func inputs(_ c: JSON) -> OptionInputs {123        OptionInputs(spot: c.num("S"), strike: c.num("K"), rate: c.num("r"), dividendYield: c.num("q"), volatility: c.num("sigma"), time: c.num("T"))124    }125    static func kind(_ c: JSON) -> OptionKind { OptionKind(rawValue: c.str("kind"))! }126127    /// Prices against 50-digit mpmath; Greeks against high-precision numerical derivatives of the price (not the closed forms).128    @Test func blackScholesPricesAndGreeksMatchReference() throws {129        let cases = Ref.list("bsm")130        #expect(cases.count >= 16)131        for c in cases {132            let o = Self.inputs(c), k = Self.kind(c)133            let r = try BlackScholes.price(k, o)134            let label = "\(k) S=\(o.spot) K=\(o.strike)"135            #expect(abs(r.price - c.num("price")) <= 1e-12 * o.spot + 1e-10 * c.num("price"), "\(label): \(r.price) vs \(c.num("price"))")136            #expect(try BlackScholes.value(k, o) == r.price)137            #expect(abs(r.greeks.delta - c.num("delta")) < 1e-11, "\(label) delta")138            #expect(abs(r.greeks.gamma - c.num("gamma")) < 1e-11 * max(1, 1 / o.spot) + 1e-9 * abs(c.num("gamma")), "\(label) gamma")139            #expect(abs(r.greeks.vega - c.num("vega")) < 1e-10 * o.spot, "\(label) vega")140            #expect(abs(r.greeks.thetaPerYear - c.num("theta")) < 1e-10 * o.spot, "\(label) theta")141            #expect(abs(r.greeks.rho - c.num("rho")) < 1e-10 * o.spot, "\(label) rho")142            #expect(r.greeks.vegaPerPercent == r.greeks.vega / 100 && r.greeks.thetaPerDay == r.greeks.thetaPerYear / 365 && r.greeks.rhoPerPercent == r.greeks.rho / 100)143            #expect(r.verification.isVerified, "\(label): \(r.verification.warnings)")144        }145    }146147    @Test func hullTextbookExample() throws {148        // Hull: S = 42, K = 40, r = 10%, σ = 20%, T = 0.5 → call 4.76, put 0.81149        let o = OptionInputs(spot: 42, strike: 40, rate: 0.10, volatility: 0.20, time: 0.5)150        let c = try BlackScholes.price(.call, o), p = try BlackScholes.price(.put, o)151        #expect((c.price * 100).rounded() / 100 == 4.76 && (p.price * 100).rounded() / 100 == 0.81)152        #expect(abs(c.d1 - 0.7693) < 5e-5 && abs(c.d2 - 0.6278) < 5e-5)153        #expect(c.explanation.assumptions.contains { $0.contains("European exercise") } && c.explanation.assumptions.contains { $0.contains("lognormal") })154        #expect(abs(BlackScholes.normalCDF(0) - 0.5) < 1e-16 && abs(BlackScholes.normalCDF(1.96) - 0.9750021048517795) < 1e-15)155        #expect(BlackScholes.normalCDF(-30) > 0 && BlackScholes.normalCDF(-30) < 1e-190)156    }157158    @Test func greeksMatchFiniteDifferences() throws {159        let o = OptionInputs(spot: 105, strike: 100, rate: 0.04, dividendYield: 0.015, volatility: 0.28, time: 0.75)160        for k in OptionKind.allCases {161            let g = try BlackScholes.price(k, o).greeks162            func v(_ change: (inout OptionInputs) -> Void) -> Double { var x = o; change(&x); return try! BlackScholes.value(k, x) }163            let h = 1e-4164            #expect(abs((v { $0.spot += h } - v { $0.spot -= h }) / (2 * h) - g.delta) < 1e-7)165            #expect(abs((v { $0.spot += 0.01 } - 2 * v { _ in } + v { $0.spot -= 0.01 }) / 1e-4 - g.gamma) < 1e-6)166            #expect(abs((v { $0.volatility += h } - v { $0.volatility -= h }) / (2 * h) - g.vega) < 1e-5)167            #expect(abs(-(v { $0.time += h } - v { $0.time -= h }) / (2 * h) - g.thetaPerYear) < 1e-5)168            #expect(abs((v { $0.rate += h } - v { $0.rate -= h }) / (2 * h) - g.rho) < 1e-5)169            // documented units: +1 vol point and +1 rate point170            #expect(abs((v { $0.volatility += 0.01 } - v { _ in }) - g.vegaPerPercent) < 2e-3)171            #expect(abs((v { $0.rate += 0.01 } - v { _ in }) - g.rhoPerPercent) < 1e-2)172            #expect(abs((v { $0.time -= 1.0 / 365 } - v { _ in }) - g.thetaPerDay) < 1e-4)173        }174        let call = try BlackScholes.price(.call, o).greeks, put = try BlackScholes.price(.put, o).greeks175        #expect(call.gamma == put.gamma && call.vega == put.vega)176        #expect(abs(call.delta - put.delta - exp(-0.015 * 0.75)) < 1e-14)177    }178179    @Test func putCallParity() throws {180        for c in Ref.list("bsm") where Self.kind(c) == .call {181            let o = Self.inputs(c)182            let call = try BlackScholes.value(.call, o), put = try BlackScholes.value(.put, o)183            let parity = try BlackScholes.putCallParity(call: call, put: put, spot: o.spot, strike: o.strike, rate: o.rate, dividendYield: o.dividendYield, time: o.time)184            #expect(parity.holds && abs(parity.gap) < 1e-11 * max(o.spot, o.strike))185            #expect(try abs(BlackScholes.parityPrice(of: .put, otherPrice: call, o) - put) < 1e-11 * max(o.spot, o.strike))186            #expect(try abs(BlackScholes.parityPrice(of: .call, otherPrice: put, o) - call) < 1e-11 * max(o.spot, o.strike))187        }188        let broken = try BlackScholes.putCallParity(call: 5, put: 1, spot: 42, strike: 40, rate: 0.10, time: 0.5)189        #expect(!broken.holds && abs(broken.gap - (4 - (42 - 40 * exp(-0.05)))) < 1e-13)190    }191192    @Test func impliedVolatilityRoundTrip() throws {193        var tested = 0194        for c in Ref.list("bsm") {195            guard let reference = c.optionalNum("implied_vol") else { continue }196            let o = Self.inputs(c), k = Self.kind(c)197            var blind = o; blind.volatility = .nan    // the volatility field must be ignored198            let r = try BlackScholes.impliedVolatility(k, price: c.num("price"), blind)199            // tolerance scaled by the conditioning: an error ε in price moves σ by ε/vega200            let tol = max(1e-10, 1e-13 * o.spot / max(c.num("vega"), 1e-12))201            #expect(abs(r.volatility - o.volatility) < tol, "\(k) S=\(o.spot) K=\(o.strike): \(r.volatility)")202            #expect(abs(r.volatility - reference) < tol * 10)203            #expect(!r.verification.checks.contains { $0.status == .failed })204            tested += 1205        }206        #expect(tested >= 12)207        // a grid of volatilities from 1% to 300%208        let base = OptionInputs(spot: 100, strike: 110, rate: 0.03, dividendYield: 0.01, volatility: 0, time: 0.5)209        for vol in [0.01, 0.05, 0.2, 0.75, 1.5, 3.0] {210            for k in OptionKind.allCases {211                var o = base; o.volatility = vol212                let price = try BlackScholes.value(k, o)213                let intrinsic = max((k == .call ? 1 : -1) * (100 * exp(-0.005) - 110 * exp(-0.015)), 0)214                guard price - intrinsic > 1e-7 else { continue }     // no time value left in double precision: not invertible215                let iv = try BlackScholes.impliedVolatility(k, price: price, base).volatility216                #expect(abs(iv - vol) < 1e-7, "\(k) σ=\(vol): \(iv)")217            }218        }219    }220221    @Test func impliedVolatilityRejectsArbitragePrices() {222        let o = OptionInputs(spot: 100, strike: 90, rate: 0.05, volatility: 0, time: 1)223        let lower = 100 - 90 * exp(-0.05)224        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.call, price: lower - 0.01, o) }) { if case .outsideNoArbitrageBounds = $0 { true } else { false } }225        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.call, price: lower, o) }) { if case .outsideNoArbitrageBounds = $0 { true } else { false } }226        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.call, price: 100, o) }) { if case .outsideNoArbitrageBounds = $0 { true } else { false } }227        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.put, price: 90, o) }) { if case .outsideNoArbitrageBounds = $0 { true } else { false } }228        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.put, price: 0, o) }) { if case .outsideNoArbitrageBounds = $0 { true } else { false } }229        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.put, price: -1, o) }) { if case .outsideNoArbitrageBounds = $0 { true } else { false } }230        // non-convergence is surfaced when the iteration budget is too small231        expectFinancialError({ _ = try BlackScholes.impliedVolatility(.call, price: 17.3, o, maxIterations: 1) }) { if case .nonConvergence = $0 { true } else { false } }232        expectFinancialError({ _ = try BlackScholes.price(.call, OptionInputs(spot: 100, strike: 90, rate: 0.05, volatility: 0, time: 1)) }) { if case .invalidInput = $0 { true } else { false } }233        expectFinancialError({ _ = try BlackScholes.price(.call, OptionInputs(spot: 100, strike: 90, rate: 0.05, volatility: 0.2, time: 0)) }) { if case .invalidInput = $0 { true } else { false } }234        expectFinancialError({ _ = try BlackScholes.price(.call, OptionInputs(spot: -1, strike: 90, rate: 0.05, volatility: 0.2, time: 1)) }) { if case .invalidInput = $0 { true } else { false } }235    }236237    /// CRR trees against an independent numpy implementation, including Hull's 5-step American put (4.49).238    @Test func binomialTreesMatchReference() throws {239        let cases = Ref.list("crr")240        #expect(cases.count >= 12)241        for c in cases {242            let o = Self.inputs(c), k = Self.kind(c), n = c.int("steps")243            let e = try BinomialTree.price(k, style: .european, o, steps: n)244            let a = try BinomialTree.price(k, style: .american, o, steps: n)245            #expect(close(e.price, c.num("european"), 1e-10), "European \(k) \(n) steps")246            #expect(close(a.price, c.num("american"), 1e-10), "American \(k) \(n) steps")247            #expect(e.earlyExercisePremium == 0 && a.europeanPrice == e.price && close(a.earlyExercisePremium, c.num("american") - c.num("european"), 1e-8))248            #expect(close(a.blackScholesEuropeanReference, c.num("bsm"), 1e-10))249            #expect(a.price >= e.price - 1e-12)250            #expect(!a.verification.checks.contains { $0.status == .failed })251        }252        let hull = try BinomialTree.price(.put, style: .american, OptionInputs(spot: 50, strike: 50, rate: 0.10, volatility: 0.40, time: 5.0 / 12), steps: 5)253        #expect((hull.price * 100).rounded() / 100 == 4.49)254        #expect(abs(hull.up - 1.1224) < 5e-5 && abs(hull.probability - 0.5073) < 5e-5)255        #expect(hull.explanation.assumptions.contains { $0.contains("not the value of an American option") })256    }257258    @Test func europeanTreeConvergesToBlackScholes() throws {259        let o = OptionInputs(spot: 100, strike: 105, rate: 0.05, dividendYield: 0.02, volatility: 0.25, time: 1)260        for k in OptionKind.allCases {261            let exact = try BlackScholes.value(k, o)262            var previous = Double.infinity263            for n in [50, 400, 3200] {264                let r = try BinomialTree.price(k, style: .european, o, steps: n)265                let err = abs(r.price - exact)266                #expect(err < 4.0 / Double(n), "\(k) \(n) steps: error \(err)")   // O(1/n) convergence267                #expect(err < previous)268                previous = err269                #expect(r.verification.isVerified)270            }271            #expect(previous < 2e-3)272            #expect(try abs(BinomialTree.price(k, style: .european, o, steps: 2000).delta - (BlackScholes.price(k, o).greeks.delta)) < 1e-3)273        }274    }275276    @Test func americanExerciseProperties() throws {277        let o = OptionInputs(spot: 36, strike: 40, rate: 0.06, volatility: 0.20, time: 1)278        let put = try BinomialTree.price(.put, style: .american, o, steps: 1000)279        #expect(put.price > put.europeanPrice + 0.3 && put.earlyExercisePremium > 0.3)          // deep ITM put: early exercise matters280        // ≈ 4.487 (numpy reference with 2 000 steps: 4.48669). Longstaff & Schwartz (2001), Table 1, report 4.478 for the281        // same option restricted to 50 exercise dates per year, which is necessarily a little lower.282        #expect(put.price >= 4 && abs(put.price - 4.487) < 0.002 && put.price > 4.478)283        // without dividends an American call is never exercised early284        let call = try BinomialTree.price(.call, style: .american, o, steps: 1000)285        #expect(abs(call.earlyExercisePremium) < 1e-12)286        // with a high dividend yield the American call carries a premium287        var div = o; div.dividendYield = 0.10; div.spot = 45288        #expect(try BinomialTree.price(.call, style: .american, div, steps: 1000).earlyExercisePremium > 0.05)289        expectFinancialError({ _ = try BinomialTree.price(.put, style: .american, o, steps: 0) }) { if case .invalidInput = $0 { true } else { false } }290        // too few steps for the drift: p falls outside (0, 1) and the tree is refused instead of producing nonsense291        expectFinancialError({ _ = try BinomialTree.price(.call, style: .european, OptionInputs(spot: 100, strike: 100, rate: 0.5, volatility: 0.05, time: 4), steps: 2) }) {292            if case .invalidInput(let m) = $0 { m.contains("probability") } else { false }293        }294    }295296    @Test func singleLegPayoffsAndBreakEvens() throws {297        let longCall = OptionStrategy(legs: [OptionLeg(.call, .long, strike: 100, premium: 4)])298        #expect(longCall.payoff(at: 110) == 10 && longCall.profit(at: 110) == 6 && longCall.profit(at: 90) == -4)299        #expect(try longCall.breakEvens() == [104] && (longCall.maxProfit()) == nil && (longCall.maxLoss()) == -4)300        let shortCall = OptionStrategy(legs: [OptionLeg(.call, .short, strike: 100, premium: 4)])301        #expect(try shortCall.profit(at: 110) == -6 && (shortCall.breakEvens()) == [104] && (shortCall.maxProfit()) == 4 && (shortCall.maxLoss()) == nil)302        let longPut = OptionStrategy(legs: [OptionLeg(.put, .long, strike: 50, premium: 3, quantity: 2)])303        #expect(try longPut.profit(at: 40) == 14 && (longPut.breakEvens()) == [47] && (longPut.maxProfit()) == 94 && (longPut.maxLoss()) == -6)304        let shortPut = OptionStrategy(legs: [OptionLeg(.put, .short, strike: 50, premium: 3)])305        #expect(try shortPut.profit(at: 40) == -7 && (shortPut.breakEvens()) == [47] && (shortPut.maxProfit()) == 3 && (shortPut.maxLoss()) == -47)306        #expect(longCall.netPremium == 4 && shortPut.netPremium == -3)307    }308309    @Test func multiLegStrategies() throws {310        let straddle = OptionStrategy(legs: [OptionLeg(.call, .long, strike: 100, premium: 6), OptionLeg(.put, .long, strike: 100, premium: 5)])311        #expect(try straddle.breakEvens() == [89, 111] && (straddle.maxLoss()) == -11 && (straddle.maxProfit()) == nil)312        let bullSpread = OptionStrategy(legs: [OptionLeg(.call, .long, strike: 100, premium: 7), OptionLeg(.call, .short, strike: 110, premium: 3)])313        #expect(try bullSpread.breakEvens() == [104] && (bullSpread.maxProfit()) == 6 && (bullSpread.maxLoss()) == -4)314        let condor = OptionStrategy(legs: [OptionLeg(.put, .long, strike: 80, premium: 1), OptionLeg(.put, .short, strike: 90, premium: 3),315                                           OptionLeg(.call, .short, strike: 110, premium: 3), OptionLeg(.call, .long, strike: 120, premium: 1)])316        #expect(try condor.breakEvens() == [86, 114] && (condor.maxProfit()) == 4 && (condor.maxLoss()) == -6 && condor.netPremium == -4)317        let covered = OptionStrategy(legs: [OptionLeg(.underlying, .long, premium: 50), OptionLeg(.call, .short, strike: 55, premium: 2)])318        #expect(try covered.breakEvens() == [48] && (covered.maxProfit()) == 7 && (covered.maxLoss()) == -48)319        let shortStock = OptionStrategy(legs: [OptionLeg(.underlying, .short, premium: 50)])320        #expect(try shortStock.breakEvens() == [50] && (shortStock.maxLoss()) == nil && (shortStock.maxProfit()) == 50)321        // butterfly: profit is zero exactly at the wings' break-evens322        let fly = OptionStrategy(legs: [OptionLeg(.call, .long, strike: 90, premium: 12), OptionLeg(.call, .short, strike: 100, premium: 5, quantity: 2),323                                        OptionLeg(.call, .long, strike: 110, premium: 1)])324        #expect(try fly.breakEvens() == [93, 107] && (fly.maxProfit()) == 7 && (fly.maxLoss()) == -3)325        let curve = try straddle.curve(from: 50, to: 150, count: 11)326        #expect(curve.count == 11 && curve[5].price == 100 && curve[5].profit == -11 && curve[0].profit == 39 && curve[10].payoff == 50)327        #expect(try bullSpread.curve(from: 95, to: 115, count: 4).contains { $0.price == 100 })     // strikes are inserted so kinks are exact328        expectFinancialError({ _ = try OptionStrategy(legs: []).breakEvens() }) { if case .invalidInput = $0 { true } else { false } }329        expectFinancialError({ _ = try straddle.curve(from: 10, to: 5) }) { if case .invalidInput = $0 { true } else { false } }330    }331}332333@Suite struct SensitivityTests {334    @Test func genericSweepKeepsFailuresVisible() throws {335        struct Boom: Error {}336        let s = try Sensitivity.sweep(parameter: "x", output: "1/x", from: -1, to: 1, count: 5) { x in337            if x == 0.5 { throw Boom() }338            return 1 / x339        }340        #expect(s.points.map(\.x) == [-1, -0.5, 0, 0.5, 1])341        #expect(s.points[0].y == -1 && s.points[2].y == nil && s.points[2].failure != nil && s.points[3].y == nil && s.points[3].failure != nil)342        #expect(s.valid.count == 3 && s.failureCount == 2 && s.parameter == "x" && s.output == "1/x")343        #expect(throws: FinancialError.self) { try Sensitivity.sweep(from: 0, to: 0, count: 5, model: { (x: Double) -> Double in x }) }344        #expect(throws: FinancialError.self) { try Sensitivity.sweep(from: 0, to: 1, count: 1, model: { (x: Double) -> Double in x }) }345    }346347    @Test func readyMadeSweeps() throws {348        let flows = CashFlowSeries(flows: [-10_000, 3000, 4200, 6800])349        let npv = try Sensitivity.npvVsDiscountRate(flows, from: 0, to: 0.3, count: 31)350        #expect(try npv.failureCount == 0 && npv.points[0].y == 4000 && npv.points[10].y == (flows.npv(rate: npv.points[10].x)))351        #expect(zip(npv.valid, npv.valid.dropFirst()).allSatisfy { $0.y > $1.y })352        // a range that crosses −100% marks the invalid points instead of inventing values353        let bad = try Sensitivity.npvVsDiscountRate(flows, from: -1.5, to: 0.5, count: 5)354        #expect(bad.points[0].y == nil && bad.points[1].y == nil && bad.points[4].y != nil && bad.points[0].failure!.contains("−100%"))355356        let bond = BondSpec(couponRate: 0.05, frequency: 2)357        let simple = try Sensitivity.bondPriceVsYield(bond, periods: 20, from: 0.01, to: 0.09, count: 9)358        #expect(abs(simple.points[4].y! - 100) < 1e-11 && zip(simple.valid, simple.valid.dropFirst()).allSatisfy { $0.y > $1.y })359        let dated = try Sensitivity.bondPriceVsYield(bond, settlement: date("2025-03-10"), maturity: date("2035-06-15"), from: 0.01, to: 0.09, count: 9)360        #expect(dated.failureCount == 0 && dated.points[0].y! > dated.points[8].y!)361362        let loan = LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .canadianFixed)363        let pay = try Sensitivity.mortgagePaymentVsRate(loan, from: 0.03, to: 0.07, count: 5)364        #expect(pay.points[2].y == 1744.81 && zip(pay.valid, pay.valid.dropFirst()).allSatisfy { $0.y < $1.y })365366        let o = OptionInputs(spot: 42, strike: 40, rate: 0.10, volatility: 0.20, time: 0.5)367        let vol = try Sensitivity.optionValueVsVolatility(.call, o, from: 0, to: 0.4, count: 5)368        #expect(vol.points[0].y == nil && abs(vol.points[2].y! - 4.759422392871532) < 1e-12 && vol.failureCount == 1)369        let spot = try Sensitivity.optionValueVsSpot(.put, o, from: 30, to: 50, count: 21)370        #expect(spot.failureCount == 0 && zip(spot.valid, spot.valid.dropFirst()).allSatisfy { $0.y > $1.y })371372        let fv = try Sensitivity.futureValueVsTime(TVMInputs(iy: 5, pv: -1000), from: 0, to: 10, count: 11)373        #expect(fv.points[0].y == 1000 && abs(fv.points[10].y! - 1628.894626777442) < 1e-9)374    }375}376
Files main
Menu

Theme