ORIXFinancial — API reference
Pure Swift 6 package, no UI, Foundation only, depends on ../ORIXNumerics. Every public type is a Sendable value type;
every function is pure and can be called from any actor. import ORIXFinancial (and import ORIXNumerics to name
Explanation / VerificationReport).
Conventions that apply everywhere
| Topic | Convention |
|---|---|
| Errors | Every throwing function uses typed throws: throws(FinancialError). Nothing returns NaN/∞ silently. |
| Rates | Decimals (0.05 = 5%) everywhere, except TVMInputs.iy, which is in percent (BA II Plus style). |
| Rate basis | Stated per function: per period (cash flows, annuities), nominal annual (loans, bonds), continuous annual (options). |
| Signs | TVM worksheet and cash-flow series: money received +, money paid out −. Loans, bonds, annuity helpers, options: unsigned amounts. |
| Dates | FinancialDate(year:month:day:), proleptic Gregorian, no time zone. |
| Money rounding | Only loan schedules round (MoneyRounding.nearestCent, default; .none to disable). Everything else is full Double. |
| 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. |
FinancialError
enum FinancialError: Error, Equatable, CustomStringConvertible, LocalizedError {
case invalidInput(String) // bad or out-of-domain input
case noSolution(String) // equation has no solution
case multipleSolutions(candidates: [Double], message: String) // e.g. several I/Y (candidates in %)
case noRealIRR(String)
case multipleIRR([Double]) // decimal rates
case nonConvergence(String) // iteration limit or overflow
case outsideNoArbitrageBounds(String) // implied volatility impossible
}error.description (= errorDescription) is a complete user-facing sentence: catch { label.text = "\(error)" }.
Shared small types
ExplainedValue { value: Double; explanation; verification }MoneyRounding { .none, .nearestCent }—.apply(_:)rounds half away from zero in base 10 (Decimal).PaymentTiming { .end, .begin }
1. Time value of money — TVM
struct TVMInputs { var n, iy, pv, pmt, fv, py, cy: Double; var timing: PaymentTiming } // iy in PERCENT
// init(n: 0, iy: 0, pv: 0, pmt: 0, fv: 0, py: 1, cy: nil /* = py */, timing: .end); subscript[TVMVariable]
enum TVMVariable { .n, .iy, .pv, .pmt, .fv } // .label → "N", "I/Y", …
struct TVMResult { variable; value: Double; inputs: TVMInputs /* solved value filled in */; periodicRate; explanation; verification }
TVM.solve(for: TVMVariable, _ inputs: TVMInputs) throws -> TVMResult
TVM.periodicRate(iy:py:cy:) throws -> Double // i = (1 + iy/(100·cy))^(cy/py) − 1
TVM.nominalRatePercent(periodicRate:py:cy:) -> Double
TVM.residual(_ inputs) throws -> Double // left-hand side of the TVM equation (0 = consistent)let pmt = try TVM.solve(for: .pmt, TVMInputs(n: 300, iy: 5, pv: 300_000, py: 12, cy: 2)).value // −1744.81…- The value stored for the solved variable is ignored.
Nmay be fractional (thenverification.status == .warning). - Solving
I/Yscans −99.99% … 99 900% per period; throws.noSolution(same-sign amounts, or nothing in range) or.multipleSolutions(candidates:)— it never picks one root. - Rate conversion (decimals):
RateConversion.effectiveAnnual(nominal:compounding:),.nominal(effectiveAnnual:compounding:),.convert(nominal:from:to:)withCompounding.periodic(m)or.continuous.
let ear = try RateConversion.effectiveAnnual(nominal: 0.05, compounding: .periodic(2)) // 0.050625 2. Cash flows — CashFlowSeries
CashFlowSeries(initial: -50_000, groups: [CashFlowGroup(amount: 12_000, count: 5), CashFlowGroup(amount: 20_000)])
CashFlowSeries(flows: [-1000, 2300, -1320]) // flows[0] at time 0
series.flows -> [Double] // expanded; at most 20 000 periods
series.npv(rate:) / nfv(rate:) throws -> Double // rate per period, > −1
series.npvExplained(rate:) throws -> ExplainedValue
series.irr() throws -> IRRResult
series.mirr(financeRate:reinvestmentRate:) throws -> Double
series.payback() / discountedPayback(rate:) throws -> Double? // periods, fractional; nil = never recovered
series.profitabilityIndex(rate:) throws -> Double // needs initial < 0struct IRRResult { outcome: IRROutcome; descartesSignChanges: Int; explanation; verification; var rates: [Double]; func uniqueRate() throws -> Double }
enum IRROutcome { case unique(Double), multiple([Double]), none(reason: String) }switch try series.irr().outcome {
case .unique(let r): show(r) // decimal per period
case .multiple(let rs): warnAmbiguous(rs) // sorted ascending
case .none(let reason): explain(reason)
}irr() only throws for invalid input; ambiguity and absence are results. uniqueRate() converts them to
.multipleIRR / .noRealIRR errors when a single number is required.
3. Loans and mortgages — Loan
struct LoanTerms { principal; annualRate /* nominal, decimal */; amortizationYears; frequency: PaymentFrequency = .monthly;
compounding: CompoundingConvention = .usMonthly; rounding: MoneyRounding = .nearestCent }
enum PaymentFrequency { .monthly, .semiMonthly, .biweekly, .acceleratedBiweekly, .weekly, .acceleratedWeekly } // .paymentsPerYear, .label
enum CompoundingConvention { .usMonthly, .canadianFixed /* semi-annual, not in advance */, .canadianVariable /* monthly */,
.periodic(perYear: Int), .continuous } // .label
Loan.payment(_ terms) throws -> LoanPaymentResult // payment, unroundedPayment, periodicRate, effectiveAnnualRate, numberOfPayments, …
Loan.schedule(_ terms, options: ScheduleOptions = .init()) throws -> AmortizationSchedule
Loan.balance(_ terms, afterPayments:) throws -> Double // closed form; use the schedule for cent-exact balances
Loan.termSummary(_ terms, termYears:, options:) throws -> TermSummary
Loan.compareRefinance(_ RefinanceInputs) throws -> RefinanceComparison
Loan.affordability(_ AffordabilityInputs) throws -> AffordabilityResult
Loan.periodicRate(annualRate:compounding:paymentsPerYear:) throws -> Doublelet terms = LoanTerms(principal: 300_000, annualRate: 0.05, amortizationYears: 25, compounding: .canadianFixed)
let payment = try Loan.payment(terms).payment // 1744.81
let schedule = try Loan.schedule(terms) // 300 rows, last payment adjusted
let term = try Loan.termSummary(terms, termYears: 5) // balanceAtEndOfTerm, interestPaidInTerm …ScheduleRow { period (1-based), payment, interest, principal, prepayment, balance, annualRate };Identifiable.AmortizationSchedule { rows, openingBalance, payment, finalPayment, totalInterest, totalPrincipal, totalPrepayments, totalPaid, endingBalance, isPaidOff, explanation, verification },balance(after: k).ScheduleOptions(paymentOverride:, prepayments:, rateChanges:, stopAfterPeriods:)Prepayment(amount:, schedule: .lumpSum(period:) | .recurring(start:, end:, every:))— applied to principal right after the period's regular payment, capped at the balance.RateChange(period:, annualRate:, compounding: nil, policy: .recalculatePayment | .keepPayment)— applies from the interest ofperiod..recalculatePaymentkeeps the original end date;.keepPaymentchanges the duration.
- Accelerated frequencies: payment = monthly payment ÷ 2 (biweekly) or ÷ 4 (weekly);
numberOfPaymentsis then fractional and the schedule is shorter thanamortizationYears. amortizationYears × paymentsPerYearmust be a whole number. Loan rates must be ≥ 0. Schedules stop with an error after 20 000 payments, or at once if a payment does not cover the interest (no negative amortization).- Refinancing:
simpleBreakEvenPeriods/Months= costs ÷ payment savings (nil when the payment does not drop);netBreakEvenPeriod/Months= first payment at which payments + remaining balance (+ cash costs) is no higher with the new loan;lifetimeSavingsundiscounted, both loans held to maturity.financeCosts: trueadds the costs to the new loan. - Affordability: all ratios and costs are inputs (
housingRatioLimit,totalDebtRatioLimit,condoFeeShare, qualifyingannualRate); the engine embeds no regulatory rule. Output:maxMonthlyPayment,maxLoan,maxPurchasePrice,bindingConstraint, the ratios reached.
4. Bonds — Bond
struct BondSpec { faceValue = 100; couponRate; frequency = 2 /* 1, 2, 4, 12 */; redemption = faceValue;
dayCount: DayCountConvention = .thirty360US; endOfMonthRule = true }
enum BondQuote { case yield(Double), cleanPrice(Double), dirtyPrice(Double) }
enum DayCountConvention { .thirty360US, .thirtyE360, .actual360, .actual365Fixed, .actualActualICMA } // .label, .dayCount(from:to:), .yearFraction(from:to:in:)
Bond.analyze(_ spec, settlement:, maturity:, quote:, bump: 0.0001, maxIterations: 200) throws -> BondResult
Bond.analyze(_ spec, periods: Int, quote:, bump:, maxIterations:) throws -> BondResult // N whole periods, no dates
Bond.yieldToCall(_ spec, settlement:, callDate:, callPrice:, cleanPrice:, bump:) throws -> BondResult
Bond.accruedInterest(_ spec, settlement:, maturity:) throws -> Double
Bond.couponSchedule(settlement:, maturity:, frequency:, endOfMonthRule:) throws -> (previous: FinancialDate, remaining: [FinancialDate])let b = BondSpec(couponRate: 0.0575, frequency: 2, dayCount: .thirty360US)
let r = try Bond.analyze(b, settlement: try FinancialDate(year: 2008, month: 2, day: 15),
maturity: try FinancialDate(year: 2017, month: 11, day: 15), quote: .yield(0.065)) // r.cleanPrice 94.63436
let ytm = try Bond.analyze(b, periods: 20, quote: .cleanPrice(95)).yieldBondResult: yield (nominal annual, compounded at the coupon frequency), cleanPrice, dirtyPrice, accruedInterest
(all in the unit of faceValue), currentYield, macaulayDuration (years), modifiedDuration (years; % price change per
1.00 of yield), convexity (years²), effectiveDuration, effectiveConvexity (bump-and-reprice with ±bump; label them
as such), remainingCoupons, couponDates, previousCouponDate, nextCouponDate, accruedDays, periodDays,
fractionToNextCoupon, explanation, verification.
Price change estimate: ΔP/P ≈ −modifiedDuration·Δy + ½·convexity·Δy².
5. Investment analysis — Returns, Annuity
Returns.holdingPeriodReturn(beginValue:endValue:income:) Returns.cagr(beginValue:endValue:years:)
Returns.annualized(totalReturn:years:) Returns.arithmeticMean(_:) Returns.geometricMean(_:)
Returns.realReturn(nominal:inflation:) /* exact Fisher */ Returns.nominalReturn(real:inflation:)
Returns.inflationAdjusted(amount:inflation:years:) Returns.inflated(amount:inflation:years:)
Returns.moneyWeighted(_ flows: [DatedCashFlow]) throws -> MoneyWeightedResult // XIRR-style, Actual/365, effective annual
Returns.timeWeighted(_ periods: [SubPeriod], years: Double? = nil) throws -> TimeWeightedResult
Returns.timeWeighted(valuations: [(valueBeforeFlow: Double, flow: Double)], years:) throws -> TimeWeightedResult
Annuity.presentValue(futureValue:rate:periods:) Annuity.futureValue(presentValue:rate:periods:)
Annuity.presentValue(payment:rate:periods:timing:) Annuity.futureValue(payment:rate:periods:timing:)
Annuity.perpetuityPresentValue(payment:rate:timing:) // rate > 0
Annuity.growingAnnuityPresentValue(firstPayment:rate:growth:periods:timing:) // exact when growth == rate
Annuity.growingAnnuityFutureValue(firstPayment:rate:growth:periods:timing:)
Annuity.growingPerpetuityPresentValue(firstPayment:rate:growth:timing:) // throws unless rate > growthlet mwr = try Returns.moneyWeighted([DatedCashFlow(date: d0, amount: -10_000), DatedCashFlow(date: d1, amount: 11_200)]).uniqueRate()
let twr = try Returns.timeWeighted(valuations: [(100_000, 0), (105_000, 10_000), (118_000, 0)]).cumulativeReturnMoneyWeightedResult.outcomeis anIRROutcomelikeirr(); investor's view: contributions−, withdrawals and ending value+.timeWeighted(valuations:): each entry is the value just before the external flow of that date (contribution+).Annuityfunctions take unsigned amounts and a rate per period; they are valuation formulas, not the signed TVM worksheet.
6. Options — BlackScholes, BinomialTree, OptionStrategy
struct OptionInputs { spot; strike; rate /* cont. */; dividendYield = 0 /* cont. */; volatility /* 0.20 = 20% */; time /* years */ }
enum OptionKind { .call, .put } enum ExerciseStyle { .european, .american }
BlackScholes.price(_ kind, _ inputs) throws -> BSMResult // price, d1, d2, greeks, explanation, verification
BlackScholes.value(_ kind, _ inputs) throws -> Double // price only (fast, for charts)
BlackScholes.impliedVolatility(_ kind, price:, _ inputs, maxIterations: 200) throws -> ImpliedVolatilityResult // inputs.volatility ignored
BlackScholes.putCallParity(call:put:spot:strike:rate:dividendYield:time:tolerance:) throws -> PutCallParityResult // left, right, gap, holds
BlackScholes.parityPrice(of:otherPrice:_:) throws -> Double
BinomialTree.price(_ kind, style:, _ inputs, steps: 500) throws -> BinomialResultlet o = OptionInputs(spot: 42, strike: 40, rate: 0.10, volatility: 0.20, time: 0.5)
let call = try BlackScholes.price(.call, o) // 4.7594
let iv = try BlackScholes.impliedVolatility(.call, price: 4.76, o).volatility
let am = try BinomialTree.price(.put, style: .american, o, steps: 1000) // am.price, am.earlyExercisePremiumGreeks (BSMResult.greeks), per one unit of underlying:
| Field | Unit |
|---|---|
delta, gamma |
per 1.00 of spot (and per 1.00² for gamma) |
vega / vegaPerPercent |
per 1.00 of volatility (100 vol points) / per +1 vol point (= vega ÷ 100) |
thetaPerYear / thetaPerDay |
per year of calendar time passing / per calendar day (÷ 365) |
rho / rhoPerPercent |
per 1.00 of rate / per +1 percentage point (÷ 100) |
- Black-Scholes-Merton is European only. For American options use
BinomialTree; itsblackScholesEuropeanReferenceis a European figure and must be labelled as such. BinomialResult:price,europeanPrice(same tree),earlyExercisePremium,delta(tree),up,down,probability,steps(1 … 10 000). Throws.invalidInputif the risk-neutral probability leaves (0, 1) — raisesteps.- Implied volatility throws
.outsideNoArbitrageBoundswhen the price is not strictly betweenmax(S·e^(−qT) − K·e^(−rT), 0)andS·e^(−qT)(call) /max(K·e^(−rT) − S·e^(−qT), 0)andK·e^(−rT)(put). explanation.assumptionslists the model assumptions; display them with the result.
Expiry payoffs:
let condor = OptionStrategy(legs: [OptionLeg(.put, .long, strike: 80, premium: 1), OptionLeg(.put, .short, strike: 90, premium: 3),
OptionLeg(.call, .short, strike: 110, premium: 3), OptionLeg(.call, .long, strike: 120, premium: 1)])
try condor.breakEvens() // [86, 114]
try condor.maxProfit() // 4 (nil = unlimited)
try condor.maxLoss() // −6 (negative profit; nil = unlimited)
try condor.curve(from: 60, to: 140, count: 81) // [StrategyPoint(price, payoff, profit)], strikes insertedOptionLeg(_ instrument: .call | .put | .underlying, _ position: .long | .short, strike:, premium:, quantity: 1); for
.underlying, premium is the entry price. payoff(at:) is the value at expiry, profit(at:) nets the premiums
(undiscounted). netPremium > 0 is a net debit.
7. Sensitivity Studio — Sensitivity
Sensitivity.sweep(parameter: "x", output: "y", from:, to:, count:, model: (Double) throws -> Double) throws -> SensitivitySeries
Sensitivity.npvVsDiscountRate(_ series, from:to:count:)
Sensitivity.bondPriceVsYield(_ spec, settlement:maturity:from:to:count:) Sensitivity.bondPriceVsYield(_ spec, periods:from:to:count:)
Sensitivity.mortgagePaymentVsRate(_ terms, from:to:count:)
Sensitivity.optionValueVsVolatility(_ kind, _ inputs, from:to:count:) Sensitivity.optionValueVsSpot(_ kind, _ inputs, from:to:count:)
Sensitivity.futureValueVsTime(_ tvmInputs, from:to:count:)let s = try Sensitivity.sweep(parameter: "Rate", output: "Payment", from: 0.02, to: 0.08, count: 61) { r in
try Loan.payment(LoanTerms(principal: 400_000, annualRate: r, amortizationYears: 25, compounding: .canadianFixed)).payment
}
chart(s.valid) // [(x, y)]; s.points keeps failed points with y == nil and a `failure` messagecount default 101 (2 … 100 000), bounds included. A failing point is kept with y == nil and its reason; draw a gap, not a value.
Dates and day counts
let d = try FinancialDate(year: 2025, month: 3, day: 31) // throws on impossible dates
d.addingMonths(-6, endOfMonth: true); d.addingDays(30); d.days(to: other); d.serial; d.isEndOfMonth; FinancialDate(serial:)
try FinancialDate(dateComponents) // from a DatePicker: Calendar(identifier: .gregorian).dateComponents([.year, .month, .day], from: date)
DayCountConvention.thirty360US.dayCount(from: a, to: b) // Int
try DayCountConvention.actualActualICMA.yearFraction(from: a, to: b, in: CouponPeriod(start:end:frequency:))