SPB Git

Repository Public MIT

VALIDATION.md 12.5 KB

# ORIXFinancial — validation

State on 2026-11-20: swift build and swift test pass with zero warnings on macOS 27 / Swift 6.4.2 (Swift 6 language mode, strict concurrency). 67 tests in 8 suites, all passing. The tests were run with swift test on macOS only; they have not been run on an iOS simulator or device.

# How the references are produced

Reference/generate_reference.py (Python 3, mpmath 50 digits, numpy, scipy 1.17.1, decimal) writes Reference/reference.json (108 cases) and copies it to Tests/ORIXFinancialTests/Resources/reference.json, which the tests load from the test bundle. A test (bundledReferenceMatchesTheGeneratedFile) fails if the two files differ. Regenerate with python3 Reference/generate_reference.py; the last console output is kept in Reference/reference_run.txt.

numpy_financial and QuantLib were not used. Each reference is computed by a different route from the Swift code:

Area Swift implementation Python reference
TVM closed form with log1p/expm1; Brent for I/Y balance compounded period by period, 50 digits, no closed form
NPV / IRR Horner; sign-change scan + Brent term-by-term discounting; mpmath.polyroots / findroot
Loan payments closed form in Double closed form in 50 digits
Schedules Double amounts, Decimal cent rounding decimal module, exact cents, ROUND_HALF_UP
Bonds analytic sums for duration and convexity mpmath.diff (numerical 1st and 2nd derivative of the price), datetime for dates, brentq for yields
XIRR scan in ln(1+r) + Brent brentq then mpmath.findroot
BSM erfc, closed-form Greeks mpmath.ncdf 50 digits; Greeks by mpmath.diff of the price; cross-checked with scipy.stats.norm
Implied volatility Brent scipy.optimize.brentq
CRR trees scalar loops vectorised numpy

# Reference cases

Tolerance is |obtained − expected| ≤ tol · max(1, |expected|) unless stated. "Python" = reference.json.

# External / textbook values

Case Source Expected Obtained Tolerance
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
Same loan, monthly compounding (US) Python 1 753.77 1 753.77 (1 753.77012452) exact cent
TVM: 100 000, 6% monthly, 360 payments → PMT standard textbook case −599.55 −599.550525153 1e-9
TVM: 1 000 at 5% for 10 years → FV standard textbook case 1 628.89 1 628.89462678 1e-9
BSM call S=42, K=40, r=10%, σ=20%, T=0.5 Hull, Options, Futures and Other Derivatives 4.76 4.75942239287 2 decimals
BSM put, same inputs Hull 0.81 0.8085993729 2 decimals
d1, d2 of that example Hull 0.7693, 0.6278 within 5e-5 5e-5
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
IRR of −1000, 2300, −1320 project brief; Python polynomial roots 10% and 20% 0.1, 0.2 1e-12
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
Excel YIELD example (15-Feb-2008 → 15-Nov-2016, 5.75%, price 95.04287) Microsoft Excel documentation 6.5% 0.0650000068808 5e-8
Excel DURATION example (1-Jul-2018 → 1-Jan-2048, 8%, 9%, semi-annual, actual/actual) Microsoft Excel documentation 10.9191453 10.9191452816 5e-8
Excel MDURATION example (1-Jan-2008 → 1-Jan-2016, 8%, 9%, semi-annual, actual/actual) Microsoft Excel documentation 5.736 5.73566981392 5e-4
Excel XIRR example (5 dated flows, 2008–2009) Microsoft Excel documentation 0.373362535 0.373362533519 5e-9 (Excel iterates to 1e-8)
10-year 8% semi-annual bond at 10% standard textbook case 87.5378 87.5377896575 1e-7
American put S=36, K=40, r=6%, σ=20%, T=1, 2 000 steps Python CRR 4.48669 4.48668713311 1e-10

The Excel figures were quoted from memory of the Microsoft function documentation, not re-downloaded during this work. They are reproduced to every published digit, which makes a mis-recollection unlikely, but the pages were not re-read.

# Python reference sets (all in reference.json)

Set Cases What is compared Tolerance
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
rates 5 nominal ↔ effective, continuous 1e-15
cashflows 8 series NPV, NFV, all IRRs (count and values), MIRR, payback, discounted payback, PI 1e-12 (IRR 1e-10, absolute)
cashflow_long 361 flows IRR, NPV 1e-12
loan_payments 10 (all 6 frequencies; US, Canadian fixed, Canadian variable, quarterly, continuous, 0%) unrounded payment; rounded payment 1e-12; exact cent
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)
refinance 2 (costs in cash / financed) payments, simple and net break-even, interest, lifetime savings exact / to the cent
affordability 1 max payment by each ratio, max loan 1e-12
daycounts 10 date pairs × 5 conventions day counts exact
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)
bonds_simple 4 price, durations, convexity, yield same
yield_to_call 1 accrued, yield to call 1e-12
xirr 3 money-weighted return 1e-11
growing_annuities 6 (incl. g = r and g − r = 1e-10, annuity due, negative growth) PV, FV vs brute-force sums 1e-12
returns 10 values means, CAGR, annualization, Fisher, inflation, TWR, annuity PV/FV, PV at a 1e-10 rate 1e-13 … 1e-14
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
crr 6 markets × call/put, 5 … 2 000 steps European and American tree values, premium 1e-10

# Property tests (no external number needed)

BEGIN = END × (1+i); zero rate exact for all five TVM variables; negative-rate round trip; multiple-rate TVM refused with both candidates; no-solution and invalid-input paths; fractional N flagged; double IRR root (−1000, 2200, −1210) found; no-real-IRR and same-sign series reported distinctly; final-payment adjustment and principal conservation; unrounded schedule = closed-form balance (1e-10); accelerated payment = monthly ÷ 2 or ÷ 4 and shorter schedule; payment below interest refused; cent rounding of 1.005, 2.675, −1.005 and exact half-cent interest ties; accrued interest = 0 on a coupon date for every convention; par bond at coupon-rate yield; coupon schedule with and without the month-end rule; duration and convexity vs numerical derivatives; effective vs analytic duration; Greeks vs finite differences and the documented per-percent / per-day units; put-call parity (1e-11·S); implied-volatility round trip from 1% to 300%; arbitrage-bound errors; non-convergence surfaced (bond yield and implied volatility with maxIterations: 1); European tree → BSM with error < 4/steps and decreasing; American put ≥ European put, American call without dividends = European call; break-evens and max profit/loss of single legs, straddle, vertical spread, iron condor, covered call, butterfly; sweeps keep failed points; date serial round trip against Foundation's UTC Gregorian calendar.

# Example figures from the brief

All three example numbers in the brief were checked independently and are correct: Canadian mortgage payment 1 744.81; Hull call 4.76 and put 0.81; IRRs of (−1000, 2300, −1320) = 10% and 20%.

# Known limitations (stated plainly)

Validation

  • The Python references are independent implementations, but written in the same work session from the same reading of the conventions. They catch arithmetic, precision and algorithm errors; they cannot catch a convention that was misunderstood in both places (the 30/360 US February rule, the month-end coupon rule, Actual/360 and Actual/365 Fixed period handling, the accelerated-payment definition). No QuantLib, numpy-financial, Bloomberg or calculator cross-check was run. The five Excel documentation examples are the only third-party bond/XIRR figures.
  • No value was checked against a physical BA II Plus or its manual. The "textbook" TVM cases are standard figures. The defaults P/Y = 1, C/Y = P/Y are a choice of this engine.
  • Not run on iOS/iPadOS hardware or simulator.

TVM and cash flows

  • I/Y is searched between −99.99% and 99 900% per period on 6 000 log-spaced intervals; IRRs on 4 000 intervals of the discount factor (plus a tangency test). Two distinct roots closer than one interval (about 0.2% of 1+i for TVM, 0.025% of the discount factor for IRR) can be missed or merged. With exactly one sign change the root is provably unique and bracketed directly.
  • A fractional N is the compound-interest solution, not the "last smaller payment" a lender would use.
  • Cash-flow series are limited to 20 000 periods; an IRR scan at that size takes about 0.2 s in a release build (several seconds in a debug build).

Loans

  • Payments at the end of each period only; biweekly and weekly loans use 26 and 52 equal periods a year (no calendar dates, no 27-payment years). Loan rates must be ≥ 0.
  • Cent rounding follows one stated policy (half away from zero on payment, interest, principal). Lenders differ (some round the payment up, some compute interest daily); schedules can differ from a lender's statement by cents.
  • "Accelerated" means monthly payment ÷ 2 or ÷ 4; other lender definitions are not modelled.
  • Refinancing savings are undiscounted and assume both loans are held to maturity. Affordability embeds no regulatory rule (no stress test, no insurance premium, no minimum down payment).

Bonds

  • Regular coupons only: no odd first or last coupon, no business-day adjustment, no ex-dividend period, no settlement lag.
  • Compound (street) discounting is used in every period. Excel PRICE/YIELD switch to a simple-interest formula when one coupon or less remains; results differ from Excel in that case (not validated against Excel there).
  • Actual/360 and Actual/365 Fixed use a nominal period of 360/f or 365/f days, so accrued interest can slightly exceed one coupon late in a long period and accrued + remaining days need not equal the period.
  • Yield to call anchors the coupon schedule on the call date (assumed to be a coupon date). No yield to worst.
  • Effective duration and convexity are parallel-shift bump-and-reprice figures on an option-free bond, not option-adjusted measures.
  • Actual/Actual ISDA and Actual/365L are not implemented.

Investment

  • Money-weighted return uses Actual/365 from the first flow, like XIRR; a different day count gives a different rate.
  • Time-weighted return needs a valuation at every external flow; no Modified Dietz approximation.

Options

  • Black-Scholes-Merton requires T > 0 and σ > 0 (no expiry-day limit case) and a continuous dividend yield; discrete dividends are not modelled, in BSM or in the tree.
  • Implied volatility cannot be recovered when the time value is below double precision (deep in/out of the money or very short expiry); the engine then throws .outsideNoArbitrageBounds rather than return a meaningless number. Search range: 0.0001% to 6 400%.
  • CRR values carry a discretization error of order 1/steps with the usual odd/even oscillation; no smoothing or Richardson extrapolation. American exercise is only possible at tree dates. The tree reports delta only. 10 000 steps take about 0.03 s in a release build and about 9 s in a debug build.
  • Strategy payoffs are at expiry, premiums undiscounted, all legs with the same expiry.
Files main
Menu

Theme