SPB Git

Repository Public MIT

API.md 17.9 KB 272 lines markdown

1<!--2ORIX Calc3File: Packages/ORIXFinancial/API.md4Description: Public API reference of the financial engine for the UI layer.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# ORIXFinancial — API reference910Pure Swift 6 package, no UI, Foundation only, depends on `../ORIXNumerics`. Every public type is a `Sendable` value type;11every function is pure and can be called from any actor. `import ORIXFinancial` (and `import ORIXNumerics` to name12`Explanation` / `VerificationReport`).1314## Conventions that apply everywhere1516| Topic | Convention |17|---|---|18| Errors | Every throwing function uses typed throws: `throws(FinancialError)`. Nothing returns NaN/∞ silently. |19| Rates | **Decimals** (`0.05` = 5%) everywhere, **except `TVMInputs.iy`, which is in percent** (BA II Plus style). |20| Rate basis | Stated per function: per period (cash flows, annuities), nominal annual (loans, bonds), continuous annual (options). |21| Signs | TVM worksheet and cash-flow series: money received `+`, money paid out `−`. Loans, bonds, annuity helpers, options: unsigned amounts. |22| Dates | `FinancialDate(year:month:day:)`, proleptic Gregorian, no time zone. |23| Money rounding | Only loan schedules round (`MoneyRounding.nearestCent`, default; `.none` to disable). Everything else is full `Double`. |24| Explain / Verified | Main solvers return `explanation: Explanation` and `verification: VerificationReport`. Show the "verified" badge only when `verification.isVerified`; `verification.warnings` lists what to show otherwise. |2526### `FinancialError`2728```swift29enum FinancialError: Error, Equatable, CustomStringConvertible, LocalizedError {30    case invalidInput(String)                                   // bad or out-of-domain input31    case noSolution(String)                                     // equation has no solution32    case multipleSolutions(candidates: [Double], message: String) // e.g. several I/Y (candidates in %)33    case noRealIRR(String)34    case multipleIRR([Double])                                  // decimal rates35    case nonConvergence(String)                                 // iteration limit or overflow36    case outsideNoArbitrageBounds(String)                       // implied volatility impossible37}38```39`error.description` (= `errorDescription`) is a complete user-facing sentence: `catch { label.text = "\(error)" }`.4041### Shared small types4243- `ExplainedValue { value: Double; explanation; verification }`44- `MoneyRounding { .none, .nearestCent }` — `.apply(_:)` rounds half away from zero in base 10 (`Decimal`).45- `PaymentTiming { .end, .begin }`4647## 1. Time value of money — `TVM`4849```swift50struct TVMInputs { var n, iy, pv, pmt, fv, py, cy: Double; var timing: PaymentTiming }   // iy in PERCENT51// init(n: 0, iy: 0, pv: 0, pmt: 0, fv: 0, py: 1, cy: nil /* = py */, timing: .end); subscript[TVMVariable]52enum TVMVariable { .n, .iy, .pv, .pmt, .fv }   // .label → "N", "I/Y", …53struct TVMResult { variable; value: Double; inputs: TVMInputs /* solved value filled in */; periodicRate; explanation; verification }5455TVM.solve(for: TVMVariable, _ inputs: TVMInputs) throws -> TVMResult56TVM.periodicRate(iy:py:cy:) throws -> Double          // i = (1 + iy/(100·cy))^(cy/py) − 157TVM.nominalRatePercent(periodicRate:py:cy:) -> Double58TVM.residual(_ inputs) throws -> Double               // left-hand side of the TVM equation (0 = consistent)59```60```swift61let pmt = try TVM.solve(for: .pmt, TVMInputs(n: 300, iy: 5, pv: 300_000, py: 12, cy: 2)).value   // −1744.81…62```63- The value stored for the solved variable is ignored. `N` may be fractional (then `verification.status == .warning`).64- Solving `I/Y` scans −99.99% … 99 900% per period; throws `.noSolution` (same-sign amounts, or nothing in range) or65  `.multipleSolutions(candidates:)` — it never picks one root.66- Rate conversion (decimals): `RateConversion.effectiveAnnual(nominal:compounding:)`, `.nominal(effectiveAnnual:compounding:)`,67  `.convert(nominal:from:to:)` with `Compounding.periodic(m)` or `.continuous`.68```swift69let ear = try RateConversion.effectiveAnnual(nominal: 0.05, compounding: .periodic(2))   // 0.05062570```7172## 2. Cash flows — `CashFlowSeries`7374```swift75CashFlowSeries(initial: -50_000, groups: [CashFlowGroup(amount: 12_000, count: 5), CashFlowGroup(amount: 20_000)])76CashFlowSeries(flows: [-1000, 2300, -1320])      // flows[0] at time 077series.flows -> [Double]                          // expanded; at most 20 000 periods7879series.npv(rate:) / nfv(rate:) throws -> Double   // rate per period, > −180series.npvExplained(rate:) throws -> ExplainedValue81series.irr() throws -> IRRResult82series.mirr(financeRate:reinvestmentRate:) throws -> Double83series.payback() / discountedPayback(rate:) throws -> Double?    // periods, fractional; nil = never recovered84series.profitabilityIndex(rate:) throws -> Double                // needs initial < 085```86```swift87struct IRRResult { outcome: IRROutcome; descartesSignChanges: Int; explanation; verification; var rates: [Double]; func uniqueRate() throws -> Double }88enum IRROutcome { case unique(Double), multiple([Double]), none(reason: String) }89```90```swift91switch try series.irr().outcome {92case .unique(let r): show(r)                     // decimal per period93case .multiple(let rs): warnAmbiguous(rs)        // sorted ascending94case .none(let reason): explain(reason)95}96```97`irr()` only throws for invalid input; ambiguity and absence are *results*. `uniqueRate()` converts them to98`.multipleIRR` / `.noRealIRR` errors when a single number is required.99100## 3. Loans and mortgages — `Loan`101102```swift103struct LoanTerms { principal; annualRate /* nominal, decimal */; amortizationYears; frequency: PaymentFrequency = .monthly;104                   compounding: CompoundingConvention = .usMonthly; rounding: MoneyRounding = .nearestCent }105enum PaymentFrequency { .monthly, .semiMonthly, .biweekly, .acceleratedBiweekly, .weekly, .acceleratedWeekly }  // .paymentsPerYear, .label106enum CompoundingConvention { .usMonthly, .canadianFixed /* semi-annual, not in advance */, .canadianVariable /* monthly */,107                             .periodic(perYear: Int), .continuous }                                              // .label108109Loan.payment(_ terms) throws -> LoanPaymentResult      // payment, unroundedPayment, periodicRate, effectiveAnnualRate, numberOfPayments, …110Loan.schedule(_ terms, options: ScheduleOptions = .init()) throws -> AmortizationSchedule111Loan.balance(_ terms, afterPayments:) throws -> Double // closed form; use the schedule for cent-exact balances112Loan.termSummary(_ terms, termYears:, options:) throws -> TermSummary113Loan.compareRefinance(_ RefinanceInputs) throws -> RefinanceComparison114Loan.affordability(_ AffordabilityInputs) throws -> AffordabilityResult115Loan.periodicRate(annualRate:compounding:paymentsPerYear:) throws -> Double116```117```swift118let terms = LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .canadianFixed)119let payment = try Loan.payment(terms).payment                       // 1744.81120let schedule = try Loan.schedule(terms)                             // 300 rows, last payment adjusted121let term = try Loan.termSummary(terms, termYears: 5)                // balanceAtEndOfTerm, interestPaidInTerm …122```123- `ScheduleRow { period (1-based), payment, interest, principal, prepayment, balance, annualRate }`; `Identifiable`.124- `AmortizationSchedule { rows, openingBalance, payment, finalPayment, totalInterest, totalPrincipal, totalPrepayments,125  totalPaid, endingBalance, isPaidOff, explanation, verification }`, `balance(after: k)`.126- `ScheduleOptions(paymentOverride:, prepayments:, rateChanges:, stopAfterPeriods:)`127  - `Prepayment(amount:, schedule: .lumpSum(period:) | .recurring(start:, end:, every:))` — applied to principal right128    after the period's regular payment, capped at the balance.129  - `RateChange(period:, annualRate:, compounding: nil, policy: .recalculatePayment | .keepPayment)` — applies from the130    interest of `period`. `.recalculatePayment` keeps the original end date; `.keepPayment` changes the duration.131- Accelerated frequencies: payment = monthly payment ÷ 2 (biweekly) or ÷ 4 (weekly); `numberOfPayments` is then fractional132  and the schedule is shorter than `amortizationYears`.133- `amortizationYears × paymentsPerYear` must be a whole number. Loan rates must be ≥ 0. Schedules stop with an error134  after 20 000 payments, or at once if a payment does not cover the interest (no negative amortization).135- Refinancing: `simpleBreakEvenPeriods/Months` = costs ÷ payment savings (nil when the payment does not drop);136  `netBreakEvenPeriod/Months` = first payment at which payments + remaining balance (+ cash costs) is no higher with137  the new loan; `lifetimeSavings` undiscounted, both loans held to maturity. `financeCosts: true` adds the costs to the new loan.138- Affordability: all ratios and costs are inputs (`housingRatioLimit`, `totalDebtRatioLimit`, `condoFeeShare`, qualifying139  `annualRate`); the engine embeds no regulatory rule. Output: `maxMonthlyPayment`, `maxLoan`, `maxPurchasePrice`,140  `bindingConstraint`, the ratios reached.141142## 4. Bonds — `Bond`143144```swift145struct BondSpec { faceValue = 100; couponRate; frequency = 2 /* 1, 2, 4, 12 */; redemption = faceValue;146                  dayCount: DayCountConvention = .thirty360US; endOfMonthRule = true }147enum BondQuote { case yield(Double), cleanPrice(Double), dirtyPrice(Double) }148enum DayCountConvention { .thirty360US, .thirtyE360, .actual360, .actual365Fixed, .actualActualICMA }   // .label, .dayCount(from:to:), .yearFraction(from:to:in:)149150Bond.analyze(_ spec, settlement:, maturity:, quote:, bump: 0.0001, maxIterations: 200) throws -> BondResult151Bond.analyze(_ spec, periods: Int, quote:, bump:, maxIterations:) throws -> BondResult        // N whole periods, no dates152Bond.yieldToCall(_ spec, settlement:, callDate:, callPrice:, cleanPrice:, bump:) throws -> BondResult153Bond.accruedInterest(_ spec, settlement:, maturity:) throws -> Double154Bond.couponSchedule(settlement:, maturity:, frequency:, endOfMonthRule:) throws -> (previous: FinancialDate, remaining: [FinancialDate])155```156```swift157let b = BondSpec(couponRate: 0.0575, frequency: 2, dayCount: .thirty360US)158let r = try Bond.analyze(b, settlement: try FinancialDate(year: 2008, month: 2, day: 15),159                         maturity: try FinancialDate(year: 2017, month: 11, day: 15), quote: .yield(0.065))   // r.cleanPrice 94.63436160let ytm = try Bond.analyze(b, periods: 20, quote: .cleanPrice(95)).yield161```162`BondResult`: `yield` (nominal annual, compounded at the coupon frequency), `cleanPrice`, `dirtyPrice`, `accruedInterest`163(all in the unit of `faceValue`), `currentYield`, `macaulayDuration` (years), `modifiedDuration` (years; % price change per1641.00 of yield), `convexity` (years²), `effectiveDuration`, `effectiveConvexity` (bump-and-reprice with ±`bump`; label them165as such), `remainingCoupons`, `couponDates`, `previousCouponDate`, `nextCouponDate`, `accruedDays`, `periodDays`,166`fractionToNextCoupon`, `explanation`, `verification`.167168Price change estimate: `ΔP/P ≈ −modifiedDuration·Δy + ½·convexity·Δy²`.169170## 5. Investment analysis — `Returns`, `Annuity`171172```swift173Returns.holdingPeriodReturn(beginValue:endValue:income:)   Returns.cagr(beginValue:endValue:years:)174Returns.annualized(totalReturn:years:)                     Returns.arithmeticMean(_:)   Returns.geometricMean(_:)175Returns.realReturn(nominal:inflation:)  /* exact Fisher */ Returns.nominalReturn(real:inflation:)176Returns.inflationAdjusted(amount:inflation:years:)         Returns.inflated(amount:inflation:years:)177Returns.moneyWeighted(_ flows: [DatedCashFlow]) throws -> MoneyWeightedResult     // XIRR-style, Actual/365, effective annual178Returns.timeWeighted(_ periods: [SubPeriod], years: Double? = nil) throws -> TimeWeightedResult179Returns.timeWeighted(valuations: [(valueBeforeFlow: Double, flow: Double)], years:) throws -> TimeWeightedResult180181Annuity.presentValue(futureValue:rate:periods:)            Annuity.futureValue(presentValue:rate:periods:)182Annuity.presentValue(payment:rate:periods:timing:)         Annuity.futureValue(payment:rate:periods:timing:)183Annuity.perpetuityPresentValue(payment:rate:timing:)       // rate > 0184Annuity.growingAnnuityPresentValue(firstPayment:rate:growth:periods:timing:)   // exact when growth == rate185Annuity.growingAnnuityFutureValue(firstPayment:rate:growth:periods:timing:)186Annuity.growingPerpetuityPresentValue(firstPayment:rate:growth:timing:)        // throws unless rate > growth187```188```swift189let mwr = try Returns.moneyWeighted([DatedCashFlow(date: d0, amount: -10_000), DatedCashFlow(date: d1, amount: 11_200)]).uniqueRate()190let twr = try Returns.timeWeighted(valuations: [(100_000, 0), (105_000, 10_000), (118_000, 0)]).cumulativeReturn191```192- `MoneyWeightedResult.outcome` is an `IRROutcome` like `irr()`; investor's view: contributions `−`, withdrawals and ending value `+`.193- `timeWeighted(valuations:)`: each entry is the value just *before* the external flow of that date (contribution `+`).194- `Annuity` functions take unsigned amounts and a rate **per period**; they are valuation formulas, not the signed TVM worksheet.195196## 6. Options — `BlackScholes`, `BinomialTree`, `OptionStrategy`197198```swift199struct OptionInputs { spot; strike; rate /* cont. */; dividendYield = 0 /* cont. */; volatility /* 0.20 = 20% */; time /* years */ }200enum OptionKind { .call, .put }      enum ExerciseStyle { .european, .american }201202BlackScholes.price(_ kind, _ inputs) throws -> BSMResult      // price, d1, d2, greeks, explanation, verification203BlackScholes.value(_ kind, _ inputs) throws -> Double         // price only (fast, for charts)204BlackScholes.impliedVolatility(_ kind, price:, _ inputs, maxIterations: 200) throws -> ImpliedVolatilityResult   // inputs.volatility ignored205BlackScholes.putCallParity(call:put:spot:strike:rate:dividendYield:time:tolerance:) throws -> PutCallParityResult  // left, right, gap, holds206BlackScholes.parityPrice(of:otherPrice:_:) throws -> Double207BinomialTree.price(_ kind, style:, _ inputs, steps: 500) throws -> BinomialResult208```209```swift210let o = OptionInputs(spot: 42, strike: 40, rate: 0.10, volatility: 0.20, time: 0.5)211let call = try BlackScholes.price(.call, o)                       // 4.7594212let iv = try BlackScholes.impliedVolatility(.call, price: 4.76, o).volatility213let am = try BinomialTree.price(.put, style: .american, o, steps: 1000)   // am.price, am.earlyExercisePremium214```215Greeks (`BSMResult.greeks`), per one unit of underlying:216217| Field | Unit |218|---|---|219| `delta`, `gamma` | per 1.00 of spot (and per 1.00² for gamma) |220| `vega` / `vegaPerPercent` | per 1.00 of volatility (100 vol points) / per +1 vol point (= vega ÷ 100) |221| `thetaPerYear` / `thetaPerDay` | per year of calendar time passing / per calendar day (÷ 365) |222| `rho` / `rhoPerPercent` | per 1.00 of rate / per +1 percentage point (÷ 100) |223224- Black-Scholes-Merton is **European only**. For American options use `BinomialTree`; its225  `blackScholesEuropeanReference` is a European figure and must be labelled as such.226- `BinomialResult`: `price`, `europeanPrice` (same tree), `earlyExercisePremium`, `delta` (tree), `up`, `down`,227  `probability`, `steps` (1 … 10 000). Throws `.invalidInput` if the risk-neutral probability leaves (0, 1) — raise `steps`.228- Implied volatility throws `.outsideNoArbitrageBounds` when the price is not strictly between229  `max(S·e^(−qT) − K·e^(−rT), 0)` and `S·e^(−qT)` (call) / `max(K·e^(−rT) − S·e^(−qT), 0)` and `K·e^(−rT)` (put).230- `explanation.assumptions` lists the model assumptions; display them with the result.231232Expiry payoffs:233```swift234let condor = OptionStrategy(legs: [OptionLeg(.put, .long, strike: 80, premium: 1), OptionLeg(.put, .short, strike: 90, premium: 3),235                                   OptionLeg(.call, .short, strike: 110, premium: 3), OptionLeg(.call, .long, strike: 120, premium: 1)])236try condor.breakEvens()      // [86, 114]237try condor.maxProfit()       // 4      (nil = unlimited)238try condor.maxLoss()         // −6     (negative profit; nil = unlimited)239try condor.curve(from: 60, to: 140, count: 81)   // [StrategyPoint(price, payoff, profit)], strikes inserted240```241`OptionLeg(_ instrument: .call | .put | .underlying, _ position: .long | .short, strike:, premium:, quantity: 1)`; for242`.underlying`, `premium` is the entry price. `payoff(at:)` is the value at expiry, `profit(at:)` nets the premiums243(undiscounted). `netPremium` > 0 is a net debit.244245## 7. Sensitivity Studio — `Sensitivity`246247```swift248Sensitivity.sweep(parameter: "x", output: "y", from:, to:, count:, model: (Double) throws -> Double) throws -> SensitivitySeries249Sensitivity.npvVsDiscountRate(_ series, from:to:count:)250Sensitivity.bondPriceVsYield(_ spec, settlement:maturity:from:to:count:)     Sensitivity.bondPriceVsYield(_ spec, periods:from:to:count:)251Sensitivity.mortgagePaymentVsRate(_ terms, from:to:count:)252Sensitivity.optionValueVsVolatility(_ kind, _ inputs, from:to:count:)        Sensitivity.optionValueVsSpot(_ kind, _ inputs, from:to:count:)253Sensitivity.futureValueVsTime(_ tvmInputs, from:to:count:)254```255```swift256let s = try Sensitivity.sweep(parameter: "Rate", output: "Payment", from: 0.02, to: 0.08, count: 61) { r in257    try Loan.payment(LoanTerms(principal: 400_000, annualRate: r, amortizationYears: 25, compounding: .canadianFixed)).payment258}259chart(s.valid)            // [(x, y)]; s.points keeps failed points with y == nil and a `failure` message260```261`count` default 101 (2 … 100 000), bounds included. A failing point is kept with `y == nil` and its reason; draw a gap, not a value.262263## Dates and day counts264265```swift266let d = try FinancialDate(year: 2025, month: 3, day: 31)       // throws on impossible dates267d.addingMonths(-6, endOfMonth: true); d.addingDays(30); d.days(to: other); d.serial; d.isEndOfMonth; FinancialDate(serial:)268try FinancialDate(dateComponents)   // from a DatePicker: Calendar(identifier: .gregorian).dateComponents([.year, .month, .day], from: date)269DayCountConvention.thirty360US.dayCount(from: a, to: b)                       // Int270try DayCountConvention.actualActualICMA.yearFraction(from: a, to: b, in: CouponPeriod(start:end:frequency:))271```272
Files main
Menu

Theme