Repository Public MIT
1<!--2ORIX Calc3File: Packages/ORIXFinancial/VALIDATION.md4Description: Validation record of the financial engine — reference cases, sources, tolerances, known limitations.5Author: Simon-Pierre Boucher6Contact: contact@spboucher.ai7-->8# ORIXFinancial — validation910State on 2026-11-20: `swift build` and `swift test` pass with zero warnings on macOS 27 / Swift 6.4.2 (Swift 6 language11mode, strict concurrency). **67 tests in 8 suites, all passing.** The tests were run with `swift test` on macOS only;12they have not been run on an iOS simulator or device.1314## How the references are produced1516`Reference/generate_reference.py` (Python 3, mpmath 50 digits, numpy, scipy 1.17.1, `decimal`) writes17`Reference/reference.json` (108 cases) and copies it to `Tests/ORIXFinancialTests/Resources/reference.json`, which the18tests load from the test bundle. A test (`bundledReferenceMatchesTheGeneratedFile`) fails if the two files differ.19Regenerate with `python3 Reference/generate_reference.py`; the last console output is kept in `Reference/reference_run.txt`.2021`numpy_financial` and QuantLib were not used. Each reference is computed by a different route from the Swift code:2223| Area | Swift implementation | Python reference |24|---|---|---|25| TVM | closed form with `log1p`/`expm1`; Brent for I/Y | balance compounded period by period, 50 digits, no closed form |26| NPV / IRR | Horner; sign-change scan + Brent | term-by-term discounting; `mpmath.polyroots` / `findroot` |27| Loan payments | closed form in Double | closed form in 50 digits |28| Schedules | Double amounts, `Decimal` cent rounding | `decimal` module, exact cents, `ROUND_HALF_UP` |29| Bonds | analytic sums for duration and convexity | `mpmath.diff` (numerical 1st and 2nd derivative of the price), `datetime` for dates, `brentq` for yields |30| XIRR | scan in ln(1+r) + Brent | `brentq` then `mpmath.findroot` |31| BSM | `erfc`, closed-form Greeks | `mpmath.ncdf` 50 digits; Greeks by `mpmath.diff` of the price; cross-checked with `scipy.stats.norm` |32| Implied volatility | Brent | `scipy.optimize.brentq` |33| CRR trees | scalar loops | vectorised numpy |3435## Reference cases3637Tolerance is `|obtained − expected| ≤ tol · max(1, |expected|)` unless stated. "Python" = `reference.json`.3839### External / textbook values4041| Case | Source | Expected | Obtained | Tolerance |42|---|---|---|---|---|43| Canadian mortgage 300 000, 5% semi-annual, 25 y, monthly | project brief; reproduced in Python | 1 744.81 | 1 744.81 (unrounded 1 744.81495511) | exact cent |44| Same loan, monthly compounding (US) | Python | 1 753.77 | 1 753.77 (1 753.77012452) | exact cent |45| TVM: 100 000, 6% monthly, 360 payments → PMT | standard textbook case | −599.55 | −599.550525153 | 1e-9 |46| TVM: 1 000 at 5% for 10 years → FV | standard textbook case | 1 628.89 | 1 628.89462678 | 1e-9 |47| BSM call S=42, K=40, r=10%, σ=20%, T=0.5 | Hull, *Options, Futures and Other Derivatives* | 4.76 | 4.75942239287 | 2 decimals |48| BSM put, same inputs | Hull | 0.81 | 0.8085993729 | 2 decimals |49| d1, d2 of that example | Hull | 0.7693, 0.6278 | within 5e-5 | 5e-5 |50| American put, CRR 5 steps, S=K=50, r=10%, σ=40%, T=5/12 | Hull (binomial tree example) | 4.49 (u = 1.1224, p = 0.5073) | 4.48845853473 | 2 decimals; u, p 5e-5 |51| IRR of −1000, 2300, −1320 | project brief; Python polynomial roots | 10% and 20% | 0.1, 0.2 | 1e-12 |52| Excel `PRICE` example (15-Feb-2008 → 15-Nov-2017, 5.75%, 6.5%, semi-annual, 30/360) | Microsoft Excel documentation | 94.63436 | 94.6343616213 | 5e-6 |53| Excel `YIELD` example (15-Feb-2008 → 15-Nov-2016, 5.75%, price 95.04287) | Microsoft Excel documentation | 6.5% | 0.0650000068808 | 5e-8 |54| Excel `DURATION` example (1-Jul-2018 → 1-Jan-2048, 8%, 9%, semi-annual, actual/actual) | Microsoft Excel documentation | 10.9191453 | 10.9191452816 | 5e-8 |55| Excel `MDURATION` example (1-Jan-2008 → 1-Jan-2016, 8%, 9%, semi-annual, actual/actual) | Microsoft Excel documentation | 5.736 | 5.73566981392 | 5e-4 |56| Excel `XIRR` example (5 dated flows, 2008–2009) | Microsoft Excel documentation | 0.373362535 | 0.373362533519 | 5e-9 (Excel iterates to 1e-8) |57| 10-year 8% semi-annual bond at 10% | standard textbook case | 87.5378 | 87.5377896575 | 1e-7 |58| American put S=36, K=40, r=6%, σ=20%, T=1, 2 000 steps | Python CRR | 4.48669 | 4.48668713311 | 1e-10 |5960The Excel figures were quoted from memory of the Microsoft function documentation, not re-downloaded during this work.61They are reproduced to every published digit, which makes a mis-recollection unlikely, but the pages were not re-read.6263### Python reference sets (all in `reference.json`)6465| Set | Cases | What is compared | Tolerance |66|---|---|---|---|67| `tvm` | 11 worksheets × 5 unknowns = 55 solves (END/BEGIN, P/Y ≠ C/Y, daily compounding, zero, negative and 1e-7 % rates) | each solved variable vs the worksheet | 1e-9 (I/Y in %: 1e-8); periodic rate 1e-14 |68| `rates` | 5 | nominal ↔ effective, continuous | 1e-15 |69| `cashflows` | 8 series | NPV, NFV, all IRRs (count and values), MIRR, payback, discounted payback, PI | 1e-12 (IRR 1e-10, absolute) |70| `cashflow_long` | 361 flows | IRR, NPV | 1e-12 |71| `loan_payments` | 10 (all 6 frequencies; US, Canadian fixed, Canadian variable, quarterly, continuous, 0%) | unrounded payment; rounded payment | 1e-12; exact cent |72| `loan_schedules` | 11 (plain, accelerated biweekly, weekly, semi-monthly, 0%, prepayments, rate changes with both policies, payment override, 5-year term) | number of payments, payment, final payment, totals, ending balance, probe rows (interest, principal, balance) | < 0.005 (to the cent) |73| `refinance` | 2 (costs in cash / financed) | payments, simple and net break-even, interest, lifetime savings | exact / to the cent |74| `affordability` | 1 | max payment by each ratio, max loan | 1e-12 |75| `daycounts` | 10 date pairs × 5 conventions | day counts | exact |76| `bonds` | 10 dated bonds (every convention; f = 1, 2, 4, 12; EOM maturity, zero coupon, negative yield, coupon date, premium redemption) | accrued days, w, accrued, dirty, clean, Macaulay, modified, convexity, yield from clean and dirty price | 1e-12 prices, 1e-11 durations/convexity, 1e-12 yields (absolute) |77| `bonds_simple` | 4 | price, durations, convexity, yield | same |78| `yield_to_call` | 1 | accrued, yield to call | 1e-12 |79| `xirr` | 3 | money-weighted return | 1e-11 |80| `growing_annuities` | 6 (incl. g = r and g − r = 1e-10, annuity due, negative growth) | PV, FV vs brute-force sums | 1e-12 |81| `returns` | 10 values | means, CAGR, annualization, Fisher, inflation, TWR, annuity PV/FV, PV at a 1e-10 rate | 1e-13 … 1e-14 |82| `bsm` | 8 markets × call/put | price; delta, gamma, vega, theta, rho; implied volatility | price 1e-12·S + 1e-10·price; Greeks 1e-10·S; IV 1e-10 or price-noise/vega |83| `crr` | 6 markets × call/put, 5 … 2 000 steps | European and American tree values, premium | 1e-10 |8485### Property tests (no external number needed)8687BEGIN = END × (1+i); zero rate exact for all five TVM variables; negative-rate round trip; multiple-rate TVM refused with both88candidates; no-solution and invalid-input paths; fractional N flagged; double IRR root (−1000, 2200, −1210) found;89no-real-IRR and same-sign series reported distinctly; final-payment adjustment and principal conservation; unrounded90schedule = closed-form balance (1e-10); accelerated payment = monthly ÷ 2 or ÷ 4 and shorter schedule; payment below91interest refused; cent rounding of 1.005, 2.675, −1.005 and exact half-cent interest ties; accrued interest = 0 on a92coupon date for every convention; par bond at coupon-rate yield; coupon schedule with and without the month-end rule;93duration and convexity vs numerical derivatives; effective vs analytic duration; Greeks vs finite differences and the94documented per-percent / per-day units; put-call parity (1e-11·S); implied-volatility round trip from 1% to 300%;95arbitrage-bound errors; non-convergence surfaced (bond yield and implied volatility with `maxIterations: 1`);96European tree → BSM with error < 4/steps and decreasing; American put ≥ European put, American call without dividends =97European call; break-evens and max profit/loss of single legs, straddle, vertical spread, iron condor, covered call,98butterfly; sweeps keep failed points; date serial round trip against Foundation's UTC Gregorian calendar.99100## Example figures from the brief101102All three example numbers in the brief were checked independently and are **correct**: Canadian mortgage payment1031 744.81; Hull call 4.76 and put 0.81; IRRs of (−1000, 2300, −1320) = 10% and 20%.104105## Known limitations (stated plainly)106107**Validation**108- The Python references are independent *implementations*, but written in the same work session from the same reading of109 the conventions. They catch arithmetic, precision and algorithm errors; they cannot catch a convention that was110 misunderstood in both places (the 30/360 US February rule, the month-end coupon rule, Actual/360 and Actual/365 Fixed111 period handling, the accelerated-payment definition). No QuantLib, numpy-financial, Bloomberg or calculator112 cross-check was run. The five Excel documentation examples are the only third-party bond/XIRR figures.113- No value was checked against a physical BA II Plus or its manual. The "textbook" TVM cases are standard figures.114 The defaults `P/Y = 1`, `C/Y = P/Y` are a choice of this engine.115- Not run on iOS/iPadOS hardware or simulator.116117**TVM and cash flows**118- I/Y is searched between −99.99% and 99 900% per period on 6 000 log-spaced intervals; IRRs on 4 000 intervals of the119 discount factor (plus a tangency test). Two distinct roots closer than one interval (about 0.2% of 1+i for TVM,120 0.025% of the discount factor for IRR) can be missed or merged. With exactly one sign change the root is provably121 unique and bracketed directly.122- A fractional N is the compound-interest solution, not the "last smaller payment" a lender would use.123- Cash-flow series are limited to 20 000 periods; an IRR scan at that size takes about 0.2 s in a release build (several124 seconds in a debug build).125126**Loans**127- Payments at the end of each period only; biweekly and weekly loans use 26 and 52 equal periods a year (no calendar128 dates, no 27-payment years). Loan rates must be ≥ 0.129- Cent rounding follows one stated policy (half away from zero on payment, interest, principal). Lenders differ (some130 round the payment up, some compute interest daily); schedules can differ from a lender's statement by cents.131- "Accelerated" means monthly payment ÷ 2 or ÷ 4; other lender definitions are not modelled.132- Refinancing savings are undiscounted and assume both loans are held to maturity. Affordability embeds no regulatory133 rule (no stress test, no insurance premium, no minimum down payment).134135**Bonds**136- Regular coupons only: no odd first or last coupon, no business-day adjustment, no ex-dividend period, no settlement lag.137- Compound (street) discounting is used in every period. Excel `PRICE`/`YIELD` switch to a simple-interest formula when138 one coupon or less remains; results differ from Excel in that case (not validated against Excel there).139- Actual/360 and Actual/365 Fixed use a nominal period of 360/f or 365/f days, so accrued interest can slightly exceed140 one coupon late in a long period and accrued + remaining days need not equal the period.141- Yield to call anchors the coupon schedule on the call date (assumed to be a coupon date). No yield to worst.142- Effective duration and convexity are parallel-shift bump-and-reprice figures on an option-free bond, not option-adjusted measures.143- Actual/Actual ISDA and Actual/365L are not implemented.144145**Investment**146- Money-weighted return uses Actual/365 from the first flow, like XIRR; a different day count gives a different rate.147- Time-weighted return needs a valuation at every external flow; no Modified Dietz approximation.148149**Options**150- Black-Scholes-Merton requires T > 0 and σ > 0 (no expiry-day limit case) and a continuous dividend yield; discrete151 dividends are not modelled, in BSM or in the tree.152- Implied volatility cannot be recovered when the time value is below double precision (deep in/out of the money or153 very short expiry); the engine then throws `.outsideNoArbitrageBounds` rather than return a meaningless number.154 Search range: 0.0001% to 6 400%.155- CRR values carry a discretization error of order 1/steps with the usual odd/even oscillation; no smoothing or156 Richardson extrapolation. American exercise is only possible at tree dates. The tree reports delta only.157 10 000 steps take about 0.03 s in a release build and about 9 s in a debug build.158- Strategy payoffs are at expiry, premiums undiscounted, all legs with the same expiry.159