Skip to content

Factor-process protocol: trait-based discount composition (replaces AbstractDeflator) #65

Open

Description

@alecloudenback

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, losing Ref broadcasting and Quote support. Mortality tables are OffsetArrays, so MortalityTables#134 had to wrap them in a new MortalityVector type, which made it a breaking 3.0 release.
  • Recursion. The mutual defaults between discount and factor recurse, so a subtype that defines neither overflows the stack instead of raising a MethodError.
  • The single-argument form was optional, even though pv depends 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, so compose(curve, mv) valued a 65-year-old as a newborn unless the caller remembered at_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, FinanceModels Projection, ActuaryUtilities present_values, LifeContingencies) already calls it. It also matches actuarial usage: ₙEₓ = vⁿ · ₙpₓ is a discount factor. No new factor function. Mortality adapters may add survival as an alias for readability.
  • Typed fallbacks. The untyped fallbacks at src/Rates.jl:392-394 and :418-420 become typed Number/Rate methods.
    • 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 only discount(p, t), that silently returns D(to − from) instead of D(to)/D(from).
    • After the change, translation invariance applies only to flat Number/Rate inputs. Other types either declare a style or get a MethodError, with an error hint suggesting FinanceCore.FactorStyle(::Type{<:YourType}) = SpotPrimitive().
  • Composites:
    • compose(ps...) returns a Composed{<:Tuple}: flattened (associativity forms give the same type), zero-allocation and inferable. It is an IntervalPrimitive that defines both arities as the product of its members.
    • dynamic_compose(v::AbstractVector) is the runtime-sized version for Monte Carlo. It has no init, so Dual and BigFloat element types survive.
    • components(c) returns the members; show round-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.
  • compose rejects bare numbers (0.012 could be interest or a decrement probability), non-members and empty argument lists, each with an ArgumentError. The message points to explicit constructors: Rate(x), Continuous(λ), Continuous(-log1p(-q)).
  • Deliberately absent:
    • a * operator: it clashes with curve +/* and with Rate * Real used for ELGD scaling;
    • a generic forward: it already has several meanings, including the FX forward price;
    • generic Base.zero(p, t) or broadcastable methods on non-owned types, which would be type piracy.

Contract for members

  • Time is measured in years from the valuation instant, so t = 0 is valuation.
  • discount(p, from, to) is the value at from of 1 paid at to, conditional on the process's status at from (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 OffsetArray would 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 to pv.

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, and RatePath.
  • 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, with compose, which mixes in non-yield members.

LifeContingencies (the next minor after FinanceCore 2.8)

  • InForce(life, duration) is an IntervalPrimitive.
    • duration is 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.
  • SingleLife and LifeContingency stay non-members, because their t = 0 is issue rather than valuation. So compose(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 sensitivities engine accepts non-curve members as fixed layers.

What carries over from the closed PRs

  • From Introduce AbstractDeflator abstraction #39:
    • the scope, independence and ELGD documentation;
    • the tuple-flattening compose code;
    • the inference and allocation tests.
  • From MortalityTables#134: the survival-over-interval semantics and tests. These move to InForce in LifeContingencies rather than wrapping tables.
  • Not carried over: the supertype, the factor verb, MortalityVector/ShiftedMortality/at_age, and the yield-model re-parenting in FinanceModels#255.

Sequencing

  1. FinanceCore 2.8 (this issue).
  2. FinanceModels 7.1 (the trait line). It ships after 7.0, which is in progress.
  3. LifeContingencies minor (InForce).
  4. ActuaryUtilities minors (composite sensitivities).

Verification checklist

FinanceCore

  • Existing Rate/pv tests pass unchanged.
  • Non-flat SpotPrimitive mock: discount(p, 1, 3) == D(3) / D(1), which differs from D(2).
  • A non-member that defines only discount(x, t) throws on the 3-argument call.
  • A declared primitive that is missing raises MethodError, not StackOverflowError. Check both styles and both arities, plus the error-hint text.
  • compose: every associativity form flattens to the same type. Empty, Number and non-member arguments throw.
  • @inferred and zero allocations for a Rate, a 3-part composite, an 8-part composite, and pv over Cashflows.
  • ForwardDiff through a composite; intensity sum; intensity MethodError; dynamic ≡ static; show/repr round-trip; broadcasting; Aqua.

FinanceModels

  • The trait holds for every curve type, including the stochastic models and a simulated RatePath.
  • A yield-model subtype without discount raises MethodError.
  • pv(compose(curve, Continuous(λ)), bond) through Projection with cur_time > 0.
  • compose(fx_model, …) throws.

LifeContingencies

  • InForce equals survival(life, d, d + t) under each DeathDistribution.
  • pv(compose(i, InForce(...)), cfs) reproduces the existing APV and annuity values.
  • Negative duration, a dead life and reversed times each throw.

Activity

  1. alecloudenback commented on Sep 25, 2026

    @alecloudenback
    MemberAuthor

    Updates from the 2026-09-24 review of the suite plan

    • compose of Rates returns a Continuous rate: compose(a::Rate, b::Rate...) = Continuous(Σ forces). The composite of constant rates is a constant rate, and it stays a Rate everywhere 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:

      • members get the trait-derived methods;
      • non-members keep the old fallback, behind a depwarn that names the FinanceCore.FactorStyle declaration;
      • removal waits for a FinanceCore major.

      The accumulation fallback gets the same treatment.

    • Documentation:

      • compose multiplies discount factors, which assumes the components are independent. In stochastic valuation a dependent mortality/financial or lapse/rate structure needs a bespoke member type.
      • A default intensity entered as 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.

  2. alecloudenback commented on Sep 27, 2026

    @alecloudenback
    MemberAuthor

    Contract revisions from the 2026-09-24 ecosystem review

    The trait, the single discount verb, explicit anchors such as InForce, 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 at from of 1 paid at to, conditional on the process's status at from". For a SpotPrimitive, however, FinanceCore derives it as the ratio D(to)/D(from) of spot factors seen from valuation, and FinanceModels' short-rate models are to be members. Those are different quantities. For Vasicek(0.1, 0.04, 0.02, 0.03), years 1 to 3 give:

    • 0.9396819167 from the three-argument ratio;
    • 0.9751549190 from the state-conditional four-argument price at a 1% short rate, and 0.8589475638 at 8%.

    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. For InForce under 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.
    • For a stochastic model it is the forward factor at the valuation date, not a price at from given the state at from. State-conditional prices stay a separate API: FinanceModels' existing four-argument discount(m, from, to, r). A future adapter that reanchors a model at a state would make that price a member.
    • A simulated path (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.
    • In simulation, compose scenario factors before taking the expectation. Driven jointly, this can represent dependent components. Composing already-averaged marginal factors generally cannot; that is the independence assumption, which the docs already state.

    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 for discount(c, 1000, 1000) and for discount(c, 1000, 1001), through the generic ratio. (FinanceModels 7's log-discount intervals, point 7, make both finite.)

    Revised design:

    • The derived SpotPrimitive interval throws a DomainError when discount(p, from) is zero, rather than returning 0/0.
    • Members with a direct interval formula use it: Rate and constant curves (the to - from translation), and any IntervalPrimitive. A member may define discount(p, from, to) itself to avoid underflow; log-space formulas are preferred where available.
    • Anchors beyond a law's domain (for example, an InForce past the table's omega) are invalid and throw.

    3. LifeContingencies verification.

    The checklist item "InForce equals survival(life, d, d + t)" would reproduce any defect in survival rather 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:

    • Interval identities checked independently of 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.
    • A law with omega = Inf needs 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.

    • compose is 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_compose of 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.
      • This matches the empty-collection convention adopted for pv: exact zero, typed by the inputs.
      • The rejection of bare numbers stays, because a probability could be misread as a rate.
    • On yield curves, a + b, a - b and k * a are the product, its inverse and its powers, and a test pins discount(a + b, s, t) ≈ discount(compose(a, b), s, t). FinanceModels 7 restricts CompositeYield to + and - for this reason. Other zero-rate operations build valid curves, but they are curve constructions, not compositions.
    • + on Rates 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.

    • The use cases are backward projection (in-force now × S(now → earlier) gives the implied in-force earlier), round-trip validation, and retrospective accumulation (1/ₙEₓ).
    • A reversed survival factor is a reverse factor, not a probability: it can exceed 1. Where the forward factor is 0, there is no inverse.
    • InForce should therefore invert rather than throw on reversed times.
    • Past, realized cashflows are accumulated as known amounts, not through contingent factors.

    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.

    • The DayCounts extension's discount(r, from::Date, to::Date, dc) uses the direct year fraction. That is right for coupon accrual, but it does not compose.
    • Date-aware members should measure every date from one fixed anchor (the valuation date), 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions