SPB Git

Repository Public MIT

financial-engine.md 16.6 KB 257 lines markdown

1<!--2ORIX Calc3File: docs/architecture/financial-engine.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# Financial engine (`ORIXFinancial`)89A pure Swift package with no UI: Foundation plus `ORIXNumerics` (root finding, Ridders differentiation, the `Explanation`10and `VerificationReport` types). Every public type is a `Sendable` value type and every function is pure. The public11surface is listed in [`Packages/ORIXFinancial/API.md`](../../Packages/ORIXFinancial/API.md); reference cases, tolerances12and limitations are in [`Packages/ORIXFinancial/VALIDATION.md`](../../Packages/ORIXFinancial/VALIDATION.md); the13conventions seen by the user are in [`docs/mathematics/financial-conventions.md`](../mathematics/financial-conventions.md).1415```mermaid16flowchart LR17    subgraph Inputs18        TVMI["TVMInputs<br/>N · I/Y % · PV · PMT · FV · P/Y · C/Y · END/BEGIN"]19        CF["CashFlowSeries · DatedCashFlow"]20        LT["LoanTerms · ScheduleOptions"]21        BS["BondSpec · BondQuote · FinancialDate"]22        OI["OptionInputs · OptionStrategy"]23    end24    Val["Validation<br/>requireFinite · domain guards"]25    subgraph Solvers26        Closed["Closed forms<br/>log1p / expm1 · Horner · erfc"]27        Scan["Sign-change scan + Brent<br/>RootFinder.allRoots"]28        Brent["Bracket expansion + Brent<br/>RootFinder.brent"]29        Sched["Period-by-period schedule<br/>Decimal cent rounding"]30        Tree["CRR binomial tree"]31    end32    subgraph Output33        Value["Value(s) or typed outcome<br/>IRROutcome · BondResult · BSMResult …"]34        Expl["Explanation<br/>formula · inputs · steps · assumptions"]35        Ver["VerificationReport<br/>residual · crossCheck · domain · convergence"]36    end37    Err["FinancialError (typed throws)"]3839    TVMI --> Val40    CF --> Val41    LT --> Val42    BS --> Val43    OI --> Val44    Val -->|invalid| Err45    Val --> Closed46    Val --> Scan47    Val --> Brent48    Val --> Sched49    Val --> Tree50    Scan -->|"no root / several roots"| Err51    Brent -->|"not bracketed / no convergence"| Err52    Closed --> Value53    Scan --> Value54    Brent --> Value55    Sched --> Value56    Tree --> Value57    Value --> Expl58    Value --> Ver59    Sens["Sensitivity.sweep"] -. "calls any model point by point" .-> Solvers60```6162## Source files6364| File | Lines | Public entry points |65|---|--:|---|66| `FinancialError.swift` | 110 | `FinancialError`, `ExplainedValue`, `MoneyRounding` |67| `FinancialDate.swift` | 149 | `FinancialDate`, `CouponPeriod`, `DayCountConvention` |68| `TVM.swift` | 324 | `TVM`, `TVMInputs`, `TVMResult`, `RateConversion`, `Compounding` |69| `CashFlows.swift` | 281 | `CashFlowSeries`, `CashFlowGroup`, `IRRResult`, `IRROutcome` |70| `Loans.swift` | 715 | `Loan`, `LoanTerms`, `ScheduleOptions`, `AmortizationSchedule`, refinancing and affordability types |71| `Bonds.swift` | 312 | `Bond`, `BondSpec`, `BondQuote`, `BondResult` |72| `Investment.swift` | 319 | `Returns`, `Annuity`, `DatedCashFlow`, `SubPeriod` |73| `Options.swift` | 482 | `BlackScholes`, `BinomialTree`, `OptionStrategy`, `OptionLeg` |74| `Sensitivity.swift` | 108 | `Sensitivity`, `SensitivitySeries` |7576All paths are under `Packages/ORIXFinancial/Sources/ORIXFinancial/`.7778## `FinancialError.swift` — error model and money rounding7980Every throwing function uses typed throws, `throws(FinancialError)`. Nothing returns NaN or infinity.8182| Case | Meaning |83|---|---|84| `invalidInput(String)` | Non-finite or out-of-domain input |85| `noSolution(String)` | The equation has no solution in the search range |86| `multipleSolutions(candidates:message:)` | Several I/Y satisfy a TVM worksheet (candidates in percent) |87| `noRealIRR(String)` / `multipleIRR([Double])` | Raised by `uniqueRate()` when a single IRR is demanded |88| `nonConvergence(String)` | Iteration limit reached, or a result overflows |89| `outsideNoArbitrageBounds(String)` | No volatility can reproduce an option price |9091Internal helpers: `requireFinite` (input guard), `requireFiniteResult` (overflow guard on outputs) and `bridge`, which runs92an `ORIXNumerics` root finder and maps `RootFindingError.notBracketed` to `.noSolution` and `.nonFiniteFunctionValue` /93`.didNotConverge` to `.nonConvergence`.9495`MoneyRounding.nearestCent` works in base 10: the `Double` is converted to its shortest round-trip decimal text, parsed as a96Foundation `Decimal`, rounded to two decimals half away from zero (`NSDecimalRound`, `.plain`) and converted back through97decimal text. This avoids binary artefacts such as 1.005 rounding to 1.00. `.none` disables rounding.9899## `FinancialDate.swift` — dates and day counts100101`FinancialDate` is a proleptic Gregorian year/month/day with no time zone. Arithmetic uses a serial day number (days since1021970-01-01); the conversion from a serial is Howard Hinnant's `civil_from_days`. `addingMonths(_:endOfMonth:)` clamps the103day to the month length and, with `endOfMonth`, keeps a month-end date on month ends.104105| Convention | `dayCount(from:to:)` | Year fraction |106|---|---|---|107| `thirty360US` | If D1 is the last day of February, D1 → 30, and if D2 is also the last day of February, D2 → 30; then D2 = 31 with D1 ≥ 30 → 30; D1 = 31 → 30 | days / 360 |108| `thirtyE360` | D1 = 31 → 30; D2 = 31 → 30 | days / 360 |109| `actual360` | actual days | days / 360 |110| `actual365Fixed` | actual days | days / 365 |111| `actualActualICMA` | actual days | days / (frequency × actual days in the `CouponPeriod`) |112113## `TVM.swift` — time value of money114115Governing equation, with `i` the effective rate per payment period, `v = (1+i)^(−N)` and `b = 1` in BEGIN mode:116117```118PV + PMT·(1 + i·b)·(1 − v)/i + FV·v = 0      (i ≠ 0)119PV + PMT·N + FV = 0                           (i = 0)120i = (1 + (I/Y)/(100·C/Y))^(C/Y ÷ P/Y) − 1121```122123- **Rates.** `periodicRate` evaluates `expm1(cy/py · log1p(j))`, so very small rates keep full precision; the zero rate is124  handled exactly.125- **PV, FV, PMT** are closed forms on the discount factor and the annuity factor (`-expm1(-n·l)/i`).126- **N** is `log1p(z)/log1p(i)` with `z = −(PV + FV)·i / (PMT·(1 + i·b) + PV·i)`; `z ≤ −1`, a zero denominator or a negative127  result throws `.noSolution`. A fractional N is accepted and flagged by a warning check.128- **I/Y.** Same-sign amounts throw `.noSolution` at once. Otherwise the equation is rewritten in `x = ln(1+i)` in an129  overflow-free form (present-value form for `x ≥ 0`, future-value form for `x < 0`), and `RootFinder.allRoots` scans130  `x ∈ [ln 10⁻⁴, ln 10³]` (i from −99.99 % to 99 900 % per period) on 6 000 intervals, refining each sign change with131  Brent's method (tolerance 1e-15). An exact zero-rate solution is reported as exactly 0. Zero roots throw `.noSolution`;132  more than one throws `.multipleSolutions` with every candidate. The solver never picks one root.133134`RateConversion` converts nominal ↔ effective rates for `Compounding.periodic(m)` or `.continuous` with the same135`log1p`/`expm1` forms.136137## `CashFlows.swift` — NPV, IRR, MIRR, payback138139`CashFlowSeries` is an initial flow at time 0 followed by `CashFlowGroup(amount:count:)` groups, at most 20 000 periods.140141- **NPV / NFV**: Horner's rule on `x = 1/(1+r)` for `r ≥ 0`; for `r < 0` the reversed polynomial is accumulated in `1 + r`142  and discounted once, to stay in the numerically stable direction. `npvExplained` cross-checks Horner against143  term-by-term discounting (relative gap ≤ 1e-9).144- **IRR** (`irr()`): NPV is a polynomial in the discount factor. Rates `r ≥ 0` are roots of `p(x) = Σ CF_k·x^k` on (0, 1];145  rates `r < 0` are roots of the reversed polynomial in `y = 1 + r` on (0, 1). The sign changes of the flow sequence are146  counted first (Descartes' rule).147  - 0 sign changes → `.none(reason:)`.148  - 1 sign change → the root is unique; it is bracketed directly on `[1e-6, 1]` and refined with Brent (tolerance 1e-16).149  - More → both unit intervals are scanned with `RootFinder.allRoots` on 4 000 intervals (sign changes and tangential150    roots), each refined with Brent; duplicates within 1e-9 relative are merged.151  The result is `IRROutcome.unique`, `.multiple` (sorted ascending) or `.none`. Ambiguity and absence are results, not152  errors; `uniqueRate()` turns them into `.multipleIRR` / `.noRealIRR`.153- **MIRR**: negative flows discounted at the finance rate, positive flows compounded at the reinvestment rate,154  `(FV₊ / −PV₋)^(1/n) − 1`.155- **Payback / discounted payback**: fractional, linear interpolation inside the recovery period; `nil` if never recovered.156- **Profitability index**: `1 + NPV/|CF₀|`, requires `CF₀ < 0`.157158## `Loans.swift` — payments and amortization schedules159160- **Periodic rate**: `(1 + r/m)^(m/p) − 1` for `m` compoundings and `p` payments a year, `e^(r/p) − 1` for continuous161  compounding. `CompoundingConvention` is explicit (`usMonthly`, `canadianFixed` = semi-annual, `canadianVariable` =162  monthly, `periodic(perYear:)`, `continuous`) and never inferred. Loan rates must be ≥ 0.163- **Payment**: level-payment closed form; accelerated biweekly / weekly payments are the monthly payment ÷ 2 or ÷ 4.164  `amortizationYears × paymentsPerYear` must be a whole number.165- **Schedule** (`Loan.schedule`): a period-by-period loop. In each row, interest = balance × periodic rate, principal =166  payment − interest, then prepayments (capped at the balance). With `MoneyRounding.nearestCent` (default) the payment,167  interest, principal and balance of every row are rounded to the cent. The interest product is formed in `Decimal`: when168  compounding matches the payment frequency the rate is exactly `r/m` in decimal, so half-cent ties are rounded half away169  from zero as on paper. The final payment is adjusted to clear the balance exactly.170- **Options**: `paymentOverride`, `prepayments` (lump sum or recurring), `rateChanges` (`.recalculatePayment` keeps the171  original end date, `.keepPayment` changes the duration), `stopAfterPeriods` (term shorter than amortization).172- **Guards**: a payment that does not cover the interest throws `.invalidInput` (no negative amortization); more than173  20 000 payments throws `.nonConvergence`.174- `Loan.balance` is the closed-form balance; `termSummary`, `compareRefinance` (simple and net break-even, undiscounted175  lifetime savings) and `affordability` (ratio limits are inputs; no regulatory rule is embedded) are built on the same176  payment and schedule functions.177178## `Bonds.swift` — price, yield, duration, convexity179180Street convention with compound discounting in every period:181182```183dirty = Σ_{k=0}^{n−1} C/(1 + y/f)^(w+k) + R/(1 + y/f)^(w+n−1)      clean = dirty − accrued      accrued = C·A/E184```185186`w` is the fraction of a period from settlement to the next coupon, `A` the accrued days and `E` the days in the period187under the day-count convention. Coupon dates are generated backwards from maturity (frequencies 1, 2, 4 or 12; optional188month-end rule). `Bond.analyze(_:periods:quote:)` is the dateless mode with whole periods and no accrued interest.189190- **Yield from price** (`solveYield`): the lower bracket end is found by halving `1 + y/f` from 0.5 until the price exceeds191  the target (down to 1e-9), the upper end by doubling the yield from 1.0 (up to 10⁶); Brent then solves192  `dirty(y) − target = 0` with tolerance 1e-15 and `maxIterations` (default 200).193- **Macaulay duration, modified duration, convexity** are analytic sums over the discounted flows.194- **Effective duration and convexity** are bump-and-reprice figures with ±`bump` (default 0.0001).195- `Bond.yieldToCall` anchors the coupon schedule on the call date and redeems at the call price.196197## `Investment.swift` — returns and annuities198199`Returns`: holding-period return, CAGR, annualisation, arithmetic and geometric means, exact Fisher real / nominal200relation, inflation adjustment, time-weighted return (product of sub-period growth factors) and money-weighted return.201The money-weighted return solves `Σ CF_j/(1+r)^((d_j − d_0)/365) = 0` (Actual/365, effective annual) in `u = ln(1+r)` with202an overflow-free form, scanning `u ∈ [ln 10⁻⁶, ln 10⁶]` on 6 000 intervals and refining with Brent; the outcome is an203`IRROutcome`, as for `irr()`.204205`Annuity`: present and future values of single amounts, level annuities (ordinary and due), perpetuities, growing206annuities (the `g = r` case is handled exactly as `n·C/(1+r)`) and growing perpetuities (`r > g` required). Amounts are207unsigned; rates are per period.208209## `Options.swift` — Black–Scholes–Merton, binomial tree, strategies210211- **`BlackScholes`** (European, continuous dividend yield): closed-form price with `Φ(x) = ½·erfc(−x/√2)`, `d1`, `d2`212  and closed-form Greeks (`delta`, `gamma`, `vega`, `thetaPerYear`, `rho` and their per-percent / per-day forms).213  `T > 0` and `σ > 0` are required.214- **Implied volatility**: the price is first checked against the no-arbitrage bounds (discounted intrinsic value and215  `S·e^(−qT)` for a call, `K·e^(−rT)` for a put). The bracket starts at `σ = 1e-6`; the upper end doubles from 1.0 until the216  model price exceeds the target, up to 64 (6 400 %). Brent then solves with tolerance 1e-15. A price within rounding of a217  bound throws `.outsideNoArbitrageBounds`.218- **`BinomialTree`** (Cox–Ross–Rubinstein): `u = e^(σ√Δt)`, `d = 1/u`, `p = (e^((r−q)Δt) − d)/(u − d)`, 1 to 10 000 steps.219  Underlying prices `S·u^k` are computed once; backward induction runs in a single array, taking220  `max(continuation, intrinsic)` at every node for American exercise. Delta is read from the first step. A probability221  outside (0, 1) throws `.invalidInput`. The result carries the European value from the same tree, the early-exercise222  premium and the Black–Scholes–Merton European reference.223- **`OptionStrategy`**: expiry payoff and profit of option and underlying legs. The profit is piecewise linear between224  strikes, so break-evens, maximum profit and maximum loss are solved exactly per segment (`nil` = unlimited).225226## `Sensitivity.swift` — Sensitivity Studio227228`Sensitivity.sweep` evaluates a model at `count` equally spaced parameter values (2 to 100 000, bounds included). A point229where the model throws or returns a non-finite value is kept with `y == nil` and its reason; it is never dropped or230replaced. Ready-made sweeps: NPV vs discount rate, bond price vs yield, mortgage payment vs rate, option value vs231volatility or spot, future value vs time.232233## How `Explanation` and `VerificationReport` are produced234235Both are built inside the solver that produced the value, from the numbers it actually used:236237- **`Explanation`**: the title, the governing formula as text, the inputs after normalisation, ordered `ExplanationStep`s238  (label, substituted expression, value formatted by the internal `Fmt` helper), the result and the list of assumptions239  (sign convention, rate basis, model assumptions, search range).240- **`VerificationReport`**: a list of `VerificationCheck`s that were executed, each with a kind, a status and the measured241  detail. `isVerified` is true only when every check passed; `warnings` lists the others.242243| Solver | Checks recorded |244|---|---|245| `TVM.solve` | residual of the governing equation (relative ≤ 1e-9); independent period-by-period simulation of the balance (≤ 1e-7) for whole N up to 1 000 000; fractional-N warning; `i > −100 %`; unique-rate check when solving I/Y |246| `CashFlowSeries.irr` | Descartes sign changes; NPV residual at each rate (≤ 1e-9 relative to the flows); root count vs Descartes bound; warnings for multiple or no IRR |247| `Loan.payment` | balance after the last payment; payment covers interest |248| `Loan.schedule` | principal conservation; payment = interest + principal in every row; loan repaid (or stopped as requested); closed-form balance within the stated rounding bound when no option is used |249| `Loan.compareRefinance`, `Loan.affordability` | break-even and lifetime-savings identities; payment of the maximum loan; both ratios within their limits |250| `Bond.analyze` | accrued interest within one coupon; reprice at the solved yield (≤ 1e-10); modified duration vs Ridders numerical derivative (≤ 1e-6); convexity vs numerical second derivative (≤ 1e-4); positive price |251| `Returns.moneyWeighted`, `Returns.timeWeighted` | present-value residual at each rate; uniqueness / existence warnings; product of growth factors |252| `BlackScholes.price` | put-call parity; delta and vega vs numerical derivatives; no-arbitrage bounds |253| `BlackScholes.impliedVolatility` | reprice at the implied volatility; no-arbitrage bounds; vega at the solution (warning when tiny) |254| `BinomialTree.price` | risk-neutral probability in (0, 1); European tree vs closed form within `2·S·σ·√T / steps`; American ≥ European; American ≥ intrinsic value |255256The UI shows a "verified" badge only when `verification.isVerified` is true and otherwise displays `verification.warnings`.257
Files main
Menu

Theme