SPB Git

Repository Public MIT

financial-engine.md 16.6 KB

# Financial engine (ORIXFinancial)

A pure Swift package with no UI: Foundation plus ORIXNumerics (root finding, Ridders differentiation, the Explanation and VerificationReport types). Every public type is a Sendable value type and every function is pure. The public surface is listed in Packages/ORIXFinancial/API.md; reference cases, tolerances and limitations are in Packages/ORIXFinancial/VALIDATION.md; the conventions seen by the user are in docs/mathematics/financial-conventions.md.

flowchart LR
    subgraph Inputs
        TVMI["TVMInputs<br/>N · I/Y % · PV · PMT · FV · P/Y · C/Y · END/BEGIN"]
        CF["CashFlowSeries · DatedCashFlow"]
        LT["LoanTerms · ScheduleOptions"]
        BS["BondSpec · BondQuote · FinancialDate"]
        OI["OptionInputs · OptionStrategy"]
    end
    Val["Validation<br/>requireFinite · domain guards"]
    subgraph Solvers
        Closed["Closed forms<br/>log1p / expm1 · Horner · erfc"]
        Scan["Sign-change scan + Brent<br/>RootFinder.allRoots"]
        Brent["Bracket expansion + Brent<br/>RootFinder.brent"]
        Sched["Period-by-period schedule<br/>Decimal cent rounding"]
        Tree["CRR binomial tree"]
    end
    subgraph Output
        Value["Value(s) or typed outcome<br/>IRROutcome · BondResult · BSMResult …"]
        Expl["Explanation<br/>formula · inputs · steps · assumptions"]
        Ver["VerificationReport<br/>residual · crossCheck · domain · convergence"]
    end
    Err["FinancialError (typed throws)"]

    TVMI --> Val
    CF --> Val
    LT --> Val
    BS --> Val
    OI --> Val
    Val -->|invalid| Err
    Val --> Closed
    Val --> Scan
    Val --> Brent
    Val --> Sched
    Val --> Tree
    Scan -->|"no root / several roots"| Err
    Brent -->|"not bracketed / no convergence"| Err
    Closed --> Value
    Scan --> Value
    Brent --> Value
    Sched --> Value
    Tree --> Value
    Value --> Expl
    Value --> Ver
    Sens["Sensitivity.sweep"] -. "calls any model point by point" .-> Solvers

# Source files

File Lines Public entry points
FinancialError.swift 110 FinancialError, ExplainedValue, MoneyRounding
FinancialDate.swift 149 FinancialDate, CouponPeriod, DayCountConvention
TVM.swift 324 TVM, TVMInputs, TVMResult, RateConversion, Compounding
CashFlows.swift 281 CashFlowSeries, CashFlowGroup, IRRResult, IRROutcome
Loans.swift 715 Loan, LoanTerms, ScheduleOptions, AmortizationSchedule, refinancing and affordability types
Bonds.swift 312 Bond, BondSpec, BondQuote, BondResult
Investment.swift 319 Returns, Annuity, DatedCashFlow, SubPeriod
Options.swift 482 BlackScholes, BinomialTree, OptionStrategy, OptionLeg
Sensitivity.swift 108 Sensitivity, SensitivitySeries

All paths are under Packages/ORIXFinancial/Sources/ORIXFinancial/.

# FinancialError.swift — error model and money rounding

Every throwing function uses typed throws, throws(FinancialError). Nothing returns NaN or infinity.

Case Meaning
invalidInput(String) Non-finite or out-of-domain input
noSolution(String) The equation has no solution in the search range
multipleSolutions(candidates:message:) Several I/Y satisfy a TVM worksheet (candidates in percent)
noRealIRR(String) / multipleIRR([Double]) Raised by uniqueRate() when a single IRR is demanded
nonConvergence(String) Iteration limit reached, or a result overflows
outsideNoArbitrageBounds(String) No volatility can reproduce an option price

Internal helpers: requireFinite (input guard), requireFiniteResult (overflow guard on outputs) and bridge, which runs an ORIXNumerics root finder and maps RootFindingError.notBracketed to .noSolution and .nonFiniteFunctionValue / .didNotConverge to .nonConvergence.

MoneyRounding.nearestCent works in base 10: the Double is converted to its shortest round-trip decimal text, parsed as a Foundation Decimal, rounded to two decimals half away from zero (NSDecimalRound, .plain) and converted back through decimal text. This avoids binary artefacts such as 1.005 rounding to 1.00. .none disables rounding.

# FinancialDate.swift — dates and day counts

FinancialDate is a proleptic Gregorian year/month/day with no time zone. Arithmetic uses a serial day number (days since 1970-01-01); the conversion from a serial is Howard Hinnant's civil_from_days. addingMonths(_:endOfMonth:) clamps the day to the month length and, with endOfMonth, keeps a month-end date on month ends.

Convention dayCount(from:to:) Year fraction
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
thirtyE360 D1 = 31 → 30; D2 = 31 → 30 days / 360
actual360 actual days days / 360
actual365Fixed actual days days / 365
actualActualICMA actual days days / (frequency × actual days in the CouponPeriod)

# TVM.swift — time value of money

Governing equation, with i the effective rate per payment period, v = (1+i)^(−N) and b = 1 in BEGIN mode:

text
PV + PMT·(1 + i·b)·(1 − v)/i + FV·v = 0      (i ≠ 0)
PV + PMT·N + FV = 0                           (i = 0)
i = (1 + (I/Y)/(100·C/Y))^(C/Y ÷ P/Y) − 1
  • Rates. periodicRate evaluates expm1(cy/py · log1p(j)), so very small rates keep full precision; the zero rate is handled exactly.
  • PV, FV, PMT are closed forms on the discount factor and the annuity factor (-expm1(-n·l)/i).
  • N is log1p(z)/log1p(i) with z = −(PV + FV)·i / (PMT·(1 + i·b) + PV·i); z ≤ −1, a zero denominator or a negative result throws .noSolution. A fractional N is accepted and flagged by a warning check.
  • I/Y. Same-sign amounts throw .noSolution at once. Otherwise the equation is rewritten in x = ln(1+i) in an overflow-free form (present-value form for x ≥ 0, future-value form for x < 0), and RootFinder.allRoots scans x ∈ [ln 10⁻⁴, ln 10³] (i from −99.99 % to 99 900 % per period) on 6 000 intervals, refining each sign change with Brent's method (tolerance 1e-15). An exact zero-rate solution is reported as exactly 0. Zero roots throw .noSolution; more than one throws .multipleSolutions with every candidate. The solver never picks one root.

RateConversion converts nominal ↔ effective rates for Compounding.periodic(m) or .continuous with the same log1p/expm1 forms.

# CashFlows.swift — NPV, IRR, MIRR, payback

CashFlowSeries is an initial flow at time 0 followed by CashFlowGroup(amount:count:) groups, at most 20 000 periods.

  • NPV / NFV: Horner's rule on x = 1/(1+r) for r ≥ 0; for r < 0 the reversed polynomial is accumulated in 1 + r and discounted once, to stay in the numerically stable direction. npvExplained cross-checks Horner against term-by-term discounting (relative gap ≤ 1e-9).
  • 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]; rates r < 0 are roots of the reversed polynomial in y = 1 + r on (0, 1). The sign changes of the flow sequence are counted first (Descartes' rule).
    • 0 sign changes → .none(reason:).
    • 1 sign change → the root is unique; it is bracketed directly on [1e-6, 1] and refined with Brent (tolerance 1e-16).
    • More → both unit intervals are scanned with RootFinder.allRoots on 4 000 intervals (sign changes and tangential roots), each refined with Brent; duplicates within 1e-9 relative are merged. The result is IRROutcome.unique, .multiple (sorted ascending) or .none. Ambiguity and absence are results, not errors; uniqueRate() turns them into .multipleIRR / .noRealIRR.
  • MIRR: negative flows discounted at the finance rate, positive flows compounded at the reinvestment rate, (FV₊ / −PV₋)^(1/n) − 1.
  • Payback / discounted payback: fractional, linear interpolation inside the recovery period; nil if never recovered.
  • Profitability index: 1 + NPV/|CF₀|, requires CF₀ < 0.

# Loans.swift — payments and amortization schedules

  • Periodic rate: (1 + r/m)^(m/p) − 1 for m compoundings and p payments a year, e^(r/p) − 1 for continuous compounding. CompoundingConvention is explicit (usMonthly, canadianFixed = semi-annual, canadianVariable = monthly, periodic(perYear:), continuous) and never inferred. Loan rates must be ≥ 0.
  • Payment: level-payment closed form; accelerated biweekly / weekly payments are the monthly payment ÷ 2 or ÷ 4. amortizationYears × paymentsPerYear must be a whole number.
  • Schedule (Loan.schedule): a period-by-period loop. In each row, interest = balance × periodic rate, principal = payment − interest, then prepayments (capped at the balance). With MoneyRounding.nearestCent (default) the payment, interest, principal and balance of every row are rounded to the cent. The interest product is formed in Decimal: when compounding matches the payment frequency the rate is exactly r/m in decimal, so half-cent ties are rounded half away from zero as on paper. The final payment is adjusted to clear the balance exactly.
  • Options: paymentOverride, prepayments (lump sum or recurring), rateChanges (.recalculatePayment keeps the original end date, .keepPayment changes the duration), stopAfterPeriods (term shorter than amortization).
  • Guards: a payment that does not cover the interest throws .invalidInput (no negative amortization); more than 20 000 payments throws .nonConvergence.
  • Loan.balance is the closed-form balance; termSummary, compareRefinance (simple and net break-even, undiscounted lifetime savings) and affordability (ratio limits are inputs; no regulatory rule is embedded) are built on the same payment and schedule functions.

# Bonds.swift — price, yield, duration, convexity

Street convention with compound discounting in every period:

text
dirty = Σ_{k=0}^{n−1} C/(1 + y/f)^(w+k) + R/(1 + y/f)^(w+n−1)      clean = dirty − accrued      accrued = C·A/E

w is the fraction of a period from settlement to the next coupon, A the accrued days and E the days in the period under the day-count convention. Coupon dates are generated backwards from maturity (frequencies 1, 2, 4 or 12; optional month-end rule). Bond.analyze(_:periods:quote:) is the dateless mode with whole periods and no accrued interest.

  • Yield from price (solveYield): the lower bracket end is found by halving 1 + y/f from 0.5 until the price exceeds the target (down to 1e-9), the upper end by doubling the yield from 1.0 (up to 10⁶); Brent then solves dirty(y) − target = 0 with tolerance 1e-15 and maxIterations (default 200).
  • Macaulay duration, modified duration, convexity are analytic sums over the discounted flows.
  • Effective duration and convexity are bump-and-reprice figures with ±bump (default 0.0001).
  • Bond.yieldToCall anchors the coupon schedule on the call date and redeems at the call price.

# Investment.swift — returns and annuities

Returns: holding-period return, CAGR, annualisation, arithmetic and geometric means, exact Fisher real / nominal relation, inflation adjustment, time-weighted return (product of sub-period growth factors) and money-weighted return. The money-weighted return solves Σ CF_j/(1+r)^((d_j − d_0)/365) = 0 (Actual/365, effective annual) in u = ln(1+r) with an overflow-free form, scanning u ∈ [ln 10⁻⁶, ln 10⁶] on 6 000 intervals and refining with Brent; the outcome is an IRROutcome, as for irr().

Annuity: present and future values of single amounts, level annuities (ordinary and due), perpetuities, growing annuities (the g = r case is handled exactly as n·C/(1+r)) and growing perpetuities (r > g required). Amounts are unsigned; rates are per period.

# Options.swift — Black–Scholes–Merton, binomial tree, strategies

  • BlackScholes (European, continuous dividend yield): closed-form price with Φ(x) = ½·erfc(−x/√2), d1, d2 and closed-form Greeks (delta, gamma, vega, thetaPerYear, rho and their per-percent / per-day forms). T > 0 and σ > 0 are required.
  • Implied volatility: the price is first checked against the no-arbitrage bounds (discounted intrinsic value and 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 the model price exceeds the target, up to 64 (6 400 %). Brent then solves with tolerance 1e-15. A price within rounding of a bound throws .outsideNoArbitrageBounds.
  • BinomialTree (Cox–Ross–Rubinstein): u = e^(σ√Δt), d = 1/u, p = (e^((r−q)Δt) − d)/(u − d), 1 to 10 000 steps. Underlying prices S·u^k are computed once; backward induction runs in a single array, taking max(continuation, intrinsic) at every node for American exercise. Delta is read from the first step. A probability outside (0, 1) throws .invalidInput. The result carries the European value from the same tree, the early-exercise premium and the Black–Scholes–Merton European reference.
  • OptionStrategy: expiry payoff and profit of option and underlying legs. The profit is piecewise linear between strikes, so break-evens, maximum profit and maximum loss are solved exactly per segment (nil = unlimited).

# Sensitivity.swift — Sensitivity Studio

Sensitivity.sweep evaluates a model at count equally spaced parameter values (2 to 100 000, bounds included). A point where the model throws or returns a non-finite value is kept with y == nil and its reason; it is never dropped or replaced. Ready-made sweeps: NPV vs discount rate, bond price vs yield, mortgage payment vs rate, option value vs volatility or spot, future value vs time.

# How Explanation and VerificationReport are produced

Both are built inside the solver that produced the value, from the numbers it actually used:

  • Explanation: the title, the governing formula as text, the inputs after normalisation, ordered ExplanationSteps (label, substituted expression, value formatted by the internal Fmt helper), the result and the list of assumptions (sign convention, rate basis, model assumptions, search range).
  • VerificationReport: a list of VerificationChecks that were executed, each with a kind, a status and the measured detail. isVerified is true only when every check passed; warnings lists the others.
Solver Checks recorded
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
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
Loan.payment balance after the last payment; payment covers interest
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
Loan.compareRefinance, Loan.affordability break-even and lifetime-savings identities; payment of the maximum loan; both ratios within their limits
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
Returns.moneyWeighted, Returns.timeWeighted present-value residual at each rate; uniqueness / existence warnings; product of growth factors
BlackScholes.price put-call parity; delta and vega vs numerical derivatives; no-arbitrage bounds
BlackScholes.impliedVolatility reprice at the implied volatility; no-arbitrage bounds; vega at the solution (warning when tiny)
BinomialTree.price risk-neutral probability in (0, 1); European tree vs closed form within 2·S·σ·√T / steps; American ≥ European; American ≥ intrinsic value

The UI shows a "verified" badge only when verification.isVerified is true and otherwise displays verification.warnings.

Files main
Menu

Theme