Repository navigation
Open
Description
Goal
Value cash flows under a combination of interest, default, lapse and in-force mortality with the existing pv/discount machinery, for example:
pv(compose(curve, Continuous(λ_default), InForce(life, 10)), cashflows)This happens without a shared supertype. The design replaces the AbstractDeflator attempt in #39, JuliaActuary/FinanceModels.jl#255, JuliaActuary/MortalityTables.jl#134 and JuliaActuary/ActuaryUtilities.jl#133. Those PRs are being closed in favor of this issue.
Why not a supertype
- Single inheritance. Yield models would have to leave
AbstractModel, losingRefbroadcasting andQuotesupport. Mortality tables areOffsetArrays, so MortalityTables#134 had to wrap them in a newMortalityVectortype, which made it a breaking 3.0 release. - Recursion. The mutual defaults between
discountandfactorrecurse, so a subtype that defines neither overflows the stack instead of raising aMethodError. - The single-argument form was optional, even though
pvdepends on it. - Silent axis mix-ups. Mortality indexed by attained age composed silently with curves indexed by time from valuation.
factor(mv, t)anchored at the table's first index, socompose(curve, mv)valued a 65-year-old as a newborn unless the caller rememberedat_age.
Design
FinanceCore (additive, 2.8)
A trait selects which discount arity a type defines. FinanceCore derives the other arity, in exactly one direction per style, so the two can't recurse:
abstract type FactorStyle end
struct NotAFactor <: FactorStyle end # default
struct SpotPrimitive <: FactorStyle end # type defines discount(p, t)
struct IntervalPrimitive <: FactorStyle end # type defines discount(p, from, to)
FactorStyle(::Type) = NotAFactor()
FactorStyle(::Type{<:Rate}) = SpotPrimitive()
# derived, trait-dispatched (sketch)
discount(p, from, to) # SpotPrimitive: discount(p, to) / discount(p, from)
discount(p, t) # IntervalPrimitive: discount(p, zero(t), t)
accumulation(p, args...) = inv(discount(p, args...)) # members only- One verb:
discount. Every consumer (pv, FinanceModelsProjection, ActuaryUtilitiespresent_values, LifeContingencies) already calls it. It also matches actuarial usage: ₙEₓ = vⁿ · ₙpₓ is a discount factor. No newfactorfunction. Mortality adapters may addsurvivalas an alias for readability. - Typed fallbacks. The untyped fallbacks at
src/Rates.jl:392-394and:418-420become typedNumber/Ratemethods.- Today,
discount(rate, from, to) = discount(rate, to - from)applies to any type that lacks a 3-argument method. For a non-flat type that defines onlydiscount(p, t), that silently returns D(to − from) instead of D(to)/D(from). - After the change, translation invariance applies only to flat
Number/Rateinputs. Other types either declare a style or get aMethodError, with an error hint suggestingFinanceCore.FactorStyle(::Type{<:YourType}) = SpotPrimitive().
- Today,
- Composites:
compose(ps...)returns aComposed{<:Tuple}: flattened (associativity forms give the same type), zero-allocation and inferable. It is anIntervalPrimitivethat defines both arities as the product of its members.dynamic_compose(v::AbstractVector)is the runtime-sized version for Monte Carlo. It has noinit, so Dual and BigFloat element types survive.components(c)returns the members;showround-trips; composites broadcast as scalars (Ref).intensity(p, t)is optional and has no numeric fallback. A composite's intensity is the sum of its members' intensities.- Composition assumes the members are independent (documented). Correlated effects need a bespoke member type.
composerejects bare numbers (0.012could be interest or a decrement probability), non-members and empty argument lists, each with anArgumentError. The message points to explicit constructors:Rate(x),Continuous(λ),Continuous(-log1p(-q)).- Deliberately absent:
- a
*operator: it clashes with curve+/*and withRate * Realused for ELGD scaling; - a generic
forward: it already has several meanings, including the FX forward price; - generic
Base.zero(p, t)orbroadcastablemethods on non-owned types, which would be type piracy.
- a
Contract for members
- Time is measured in years from the valuation instant, so t = 0 is valuation.
discount(p, from, to)is the value atfromof 1 paid atto, conditional on the process's status atfrom(alive, in force, not defaulted).- D(t, t) = 1 and D(a, c) = D(a, b) · D(b, c).
- Only valuation-time objects are members. An object whose natural axis is something else (attained age, duration since issue, calendar date) needs an adapter that carries an explicit anchor.
- We rejected an axis-parameterized trait. It still needs a wrapper, because a trait method on
OffsetArraywould be piracy. The axis tag also doesn't carry the anchor value, so issue ages 40 and 55 would compose "validly". And it creates objects that compose but can't be passed topv.
- We rejected an axis-parameterized trait. It still needs a wrapper, because a trait method on
FinanceModels (7.1, after 7.0)
One line:
FinanceCore.FactorStyle(::Type{<:Yield.AbstractYieldModel}) = FinanceCore.SpotPrimitive()- This covers every curve, the shift and spread wrappers,
ForwardStarting, the closed forms of the short-rate models, andRatePath. - The type hierarchy is unchanged; FX and equity models stay non-members.
- FinanceModels already defines
discount(yc::AbstractYieldModel, from, to) = discount(yc, to) / discount(yc, from)(src/model/Yield.jl), so the derived method matches today's numbers. - Docs contrast
curve + spread, which stays a yield model that sensitivities can bump, withcompose, which mixes in non-yield members.
LifeContingencies (the next minor after FinanceCore 2.8)
InForce(life, duration)is anIntervalPrimitive.durationis required: the time since issue at the valuation date. The constructor validates that the life is alive and the duration is non-negative.discount(p::InForce, from, to) = survival(p.life, p.duration + from, p.duration + to), using the life's fractional-age assumption.- Reversed times throw.
SingleLifeandLifeContingencystay non-members, because their t = 0 is issue rather than valuation. Socompose(life, curve)fails loudly.- Default and lapse use
Continuous(λ)(ELGD scaling viaλ * ELGD) or any yield curve. A duration-indexed lapse table type can come later. - The same release should revisit the silent
issue_age = firstindex(mortality)default, since explicit anchors are the point of this design.
ActuaryUtilities
- Nothing changes in 6.0. Sensitivities of composites start with documented closure recipes: bump the yield member inside the valuation function.
- Later minors:
- parallel measures for any member via
compose(p, Continuous(s)); - the named-roles
sensitivitiesengine accepts non-curve members as fixed layers.
- parallel measures for any member via
What carries over from the closed PRs
- From Introduce AbstractDeflator abstraction #39:
- the scope, independence and ELGD documentation;
- the tuple-flattening
composecode; - the inference and allocation tests.
- From MortalityTables#134: the survival-over-interval semantics and tests. These move to
InForcein LifeContingencies rather than wrapping tables. - Not carried over: the supertype, the
factorverb,MortalityVector/ShiftedMortality/at_age, and the yield-model re-parenting in FinanceModels#255.
Sequencing
- FinanceCore 2.8 (this issue).
- FinanceModels 7.1 (the trait line). It ships after 7.0, which is in progress.
- LifeContingencies minor (
InForce). - ActuaryUtilities minors (composite sensitivities).
Verification checklist
FinanceCore
- Existing
Rate/pvtests pass unchanged. - Non-flat
SpotPrimitivemock:discount(p, 1, 3) == D(3) / D(1), which differs fromD(2). - A non-member that defines only
discount(x, t)throws on the 3-argument call. - A declared primitive that is missing raises
MethodError, notStackOverflowError. Check both styles and both arities, plus the error-hint text. -
compose: every associativity form flattens to the same type. Empty,Numberand non-member arguments throw. -
@inferredand zero allocations for aRate, a 3-part composite, an 8-part composite, andpvoverCashflows. - ForwardDiff through a composite; intensity sum; intensity
MethodError; dynamic ≡ static;show/reprround-trip; broadcasting; Aqua.
FinanceModels
- The trait holds for every curve type, including the stochastic models and a simulated
RatePath. - A yield-model subtype without
discountraisesMethodError. -
pv(compose(curve, Continuous(λ)), bond)throughProjectionwithcur_time > 0. -
compose(fx_model, …)throws.
LifeContingencies
-
InForceequalssurvival(life, d, d + t)under eachDeathDistribution. -
pv(compose(i, InForce(...)), cfs)reproduces the existing APV and annuity values. - Negative duration, a dead life and reversed times each throw.
Metadata
Metadata
Assignees
Labels
No labels
Activity
alecloudenback commentedon Sep 25, 2026
Updates from the 2026-09-24 review of the suite plan
composeofRates returns aContinuousrate:compose(a::Rate, b::Rate...) = Continuous(Σ forces). The composite of constant rates is a constant rate, and it stays aRateeverywhere one is accepted. This is the named form of the force sum proposed in Make Rate addition convention independent #53, which is closed;+stays nominal in the left operand's convention.Versioning. Removing the untyped
discount(rate, from, to) = discount(rate, to - from)fallback is breaking for any third-party type that relies on it, even though the result is wrong for a non-flat type. In the next minor:depwarnthat names theFinanceCore.FactorStyledeclaration;The
accumulationfallback gets the same treatment.Documentation:
composemultiplies discount factors, which assumes the components are independent. In stochastic valuation a dependent mortality/financial or lapse/rate structure needs a bespoke member type.Continuous(λ * LGD)assumes recovery of market value. Recovery of par or of treasury needs a different member.Date-aware curves. The DayCounts extension (Add DayCounts extension: discount/accumulation over Date intervals (v2.6.0) #50) now accepts only
Union{Real, Rate}: a curve anchored at its valuation date cannot be discounted over two dates by the interval's length. A date-aware curve API needs an explicit valuation-date anchor and is out of scope here.alecloudenback commentedon Sep 27, 2026
Contract revisions from the 2026-09-24 ecosystem review
The trait, the single
discountverb, explicit anchors such asInForce, tuple composition and the deprecation bridge all stay. The review found two places where the member contract says more than the design delivers, and one weak test. Each is revised below.1. The three-argument factor is a forward factor, not a conditional stochastic price.
The contract says
discount(p, from, to)is "the value atfromof 1 paid atto, conditional on the process's status atfrom". For aSpotPrimitive, however, FinanceCore derives it as the ratioD(to)/D(from)of spot factors seen from valuation, and FinanceModels' short-rate models are to be members. Those are different quantities. ForVasicek(0.1, 0.04, 0.02, 0.03), years 1 to 3 give:Revised contract:
discount(p, from, to)is the forward factor seen from valuation,D(to)/D(from). For a deterministic discount curve, the ratio is its forward discount factor. ForInForceunder a fixed mortality law, the survival ratio is the conditional survival probability, provided survival to the anchor has positive probability. The lifetime itself does not need to be deterministic.fromgiven the state atfrom. State-conditional prices stay a separate API: FinanceModels' existing four-argumentdiscount(m, from, to, r). A future adapter that reanchors a model at a state would make that price a member.RatePath) gives realized path factors. For them, D(a,c) = D(a,b)·D(b,c) holds pathwise. That identity is not a claim about conditional expectations formed under different information.2. The interval domain when a spot factor vanishes.
The ratio needs D(from) ≠ 0. A survival process past extinction has no conditioning event, and spot factors can underflow while the interval factor is still representable. In FinanceModels 6,
Yield.Constant(Continuous(1.0))gives NaN fordiscount(c, 1000, 1000)and fordiscount(c, 1000, 1001), through the generic ratio. (FinanceModels 7's log-discount intervals, point 7, make both finite.)Revised design:
SpotPrimitiveinterval throws aDomainErrorwhendiscount(p, from)is zero, rather than returning 0/0.Rateand constant curves (theto - fromtranslation), and anyIntervalPrimitive. A member may definediscount(p, from, to)itself to avoid underflow; log-space formulas are preferred where available.InForcepast the table'somega) are invalid and throw.3. LifeContingencies verification.
The checklist item "
InForceequalssurvival(life, d, d + t)" would reproduce any defect insurvivalrather than detect it. The review found one: MortalityTables' fractional-year survival ignored the starting fraction, so under Uniform two half-year factors gave 0.81 instead of 0.8. MortalityTables 3 fixes it. The checklist becomes:survival: D(a,c) = D(a,b)·D(b,c) over fractional anchors, including birthday and select-to-ultimate crossings, against closed-form Uniform, Balducci and constant-force references.omega = Infneeds an explicit projection-horizon policy, not a blanket age cap. Finite-domain, proper and defective laws are tested separately.4. One composition principle, with a unit.
composeis the product of factors:discount(compose(a, b), s, t) == discount(a, s, t) * discount(b, s, t). The product of two members is again a member, since the composition law carries through.compose()with no arguments returns the unit factor, an exact 1, instead of throwing.dynamic_composeof an empty vector does the same. An empty composition is a valid state, for example a filtered list of decrements that happens to be empty. Folds need the unit.pv: exact zero, typed by the inputs.a + b,a - bandk * aare the product, its inverse and its powers, and a test pinsdiscount(a + b, s, t) ≈ discount(compose(a, b), s, t). FinanceModels 7 restrictsCompositeYieldto+and-for this reason. Other zero-rate operations build valid curves, but they are curve constructions, not compositions.+onRates stays nominal arithmetic in the left operand's convention (Document the conventions of Rate addition and subtraction #66). The docs should say so explicitly:Periodic(0.05, 1) + Periodic(0.05, 1)discounts one year at 0.909091, while the product of the two factors is 0.907029.5. Reversed intervals invert.
Members are invertible wherever the factor is positive:
discount(p, b, a) == 1 / discount(p, a, b). FinanceCore rates, FinanceModels curves and MortalityTables' parametric laws already behave this way, and MortalityTables 3 aligns its tables.InForceshould therefore invert rather than throw on reversed times.6. Dates are measured from an anchor.
A factor over dates composes only if the year fraction adds up across consecutive periods. 30/360 (US) does not: from Jan 31 to Mar 31, 2025 is 60/360 directly but 61/360 via Feb 28. Actual/365, Actual/Actual ISDA and 30E/360 do add up.
discount(r, from::Date, to::Date, dc)uses the direct year fraction. That is right for coupon accrual, but it does not compose.f(date) − f(anchor), which composes under every convention.7. Implementation note. Composites may add cumulative log-factors internally. That avoids 0/0 when spot factors underflow, which is the interval-domain issue in point 2. FinanceModels 7 adopts this for curve intervals.