Repository navigation
v6: unify sensitivities: shock coordinates, signed dollar risk, no tenor grids for parallel risk - #161
Merged
Conversation
This was referenced Sep 8, 2026
`sensitivities(target, forward, credit, tenors)` derived `effective_dv01`, `spread_dv01`, and `forward_dv01` as duration × value / 10_000, which is NaN·0 for a zero-present-value position even though the exposure is finite and `dv01(Effective()/Spread(), …)` already returns it. Compute the dollar figures from the value gradient directly; the normalized durations and key-rate vectors keep their documented undefined-at-zero behaviour. Regression: a two-cashflow portfolio with zero present value and nonzero DV01, both signs, single- and two-curve forms, plus a nonzero-value bond to lock the unchanged path. Bump to 6.0.0: scalar convexity for yield-model inputs changes its numeric result, so the release is a major, not 5.12.0. Update the upgrade guide header and the convexity guide accordingly. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014DUnw1ft1K357DbYdcuCCx
…sitivity-engine # Conflicts: # Project.toml
Default contract DV01 and convexity to Effective, honor embedded cashflow times across analytic sensitivities and derived grids, and share allocation-free fixed-cashflow convexity for yield models. Add regression coverage and migration documentation.
Scalar IR01 and CS01 now equal the DV01 of the combined rate base + spread, shocked in that rate's own coordinate. Per-component bumping disagreed whenever the inputs mixed types (e.g. a curve base with a scalar spread gave CS01 ≈ IR01 / (1 + spread)). Tenor grids now appear only where results have a tenor dimension. The scalar tenor-aware duration/DV01/IR01/CS01/convexity forms, their callback and do-block variants, and the scalar contract forms never depended on the grid, and their positions let swapped arguments return wrong numbers silently. Remove them and add the missing no-tenor equivalents: the DV01 do-block, two-curve callback IR01/CS01, two-curve convexity blocks for callbacks and fixed cashflows, and contract duration/DV01/convexity on (target, curve) and (target, forward, credit). Every removed v5 call shape now throws. Remove the finite-difference KeyRateZero/KeyRate/KeyRatePar API; KeyRates applies the same bumps with exact derivatives. Yield-model modified duration and DV01 for fixed cashflows use analytic continuous-zero kernels; DV01 does not divide by value, so zero-value exposure stays defined. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Add a canonical Shock coordinates section and restructure the sensitivities guide around scalar measures, key-rate decomposition, and contracts without tenor grids. Expand the v6 upgrade notes with the liability DV01 sign, the IR01/CS01 identity, a migration table for removed tenor forms, and the KeyRate* removal. Restore the historical v5.6→v5.7 and v5.11→v5.12 notes to their original wording. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
sensitivities(valuation, inputs::NamedTuple) differentiates a valuation with respect to named vectors of market inputs (quoted rates, spreads, zero rates) and reports value plus per-input parallel and per-element durations and signed DV01s. Inputs are bumped in the units they are given, so quote conventions come from the caller's own constructors. Up to 64 elements are differentiated in one forward pass, so a valuation that refits a curve refits once. Named curve and named input tuples dispatch separately; both require at least one element. The named-curve form also reports per-tenor DV01s. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The helper evaluates the valuation once for the value and once more for the derivatives (one forward pass per 64 inputs), so a valuation that fits a curve fits it twice, not once. `-∂V/∂s / 10000` is the value lost for an increase, not the value change. The duration and DV01 sums equal a parallel-shift derivative only where the valuation is differentiable, which excludes interpolation kinks such as a flat MonotoneConvex interval; link FinanceModels' calibration sensitivities page for that contract. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
The hat functions, `_bumped`, `_PARALLEL_GRID` and both `_parallel_bumped` methods serve the scalar callbacks, the contract measures and `Scenarios`, not only key rates. They move with `AYM` and `HW` into curve_shifts.jl, included after measures.jl, so scalar_measures.jl can write `AYM` and the two `_parallel_bumped` methods sit together. The definitions only move. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Fixed-cashflow IR01 and CS01 are one rule: the DV01 of `base + credit`.
The scalar form is now one `Union{IR01, CS01}` method, and the key-rate
cashflow form computes `duration(DV01(), kr, base + credit, cfs, times)`
instead of taking one role of the two-role kernel; it matches the old
result to a relative 3e-16. The two near-duplicate docstrings become one,
which also documents the key-rate forms and states which operand's
compounding a `Rate` sum takes. `_role` has no caller left and is deleted.
The callback docstring now describes only the callback forms.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
- `_cashflow_vector(::AbstractArray{Union{}})` existed because an empty
`Union{}[]` also matched a `Cashflow` method. No method dispatches on
`AbstractVector{<:Cashflow}` any more, and the zero-stream type table
already handles `Union{}`; `()`, `Union{}[]` and `Any[]` give the same
zeros and types without it.
- `dv01` forwarded keywords, but no `duration` method takes any since the
Hull-White keywords moved into `Scenarios`. A keyword call still raises a
`MethodError`.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
The contract `discount=` form merges the projection curve into the named curves as `index`, so a discount layer named `index` was silently replaced: the projection curve was summed twice and the value was wrong. A layer with that name now throws an `ArgumentError`, and the docstring says so. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Code comments and docstrings, checked against the code: - Recompute the stale `julia-repl` outputs (convexity, callback duration, `spread`) and replace the `convexity` examples, which were mostly `duration` calls, with two `convexity` calls. - IR01/CS01 marker docstrings: no contract method takes them, and fixed-cashflow key-rate IR01 and CS01 are equal; only the callback forms separate them. Say "credit curve" throughout. - A floater's effective duration is small, not the time to its next reset (that holds once the current coupon is fixed, see `locked_floater`), and its spread duration is close to a fixed-rate bond's, not its maturity. - Modified duration is per unit of rate, and DV01 is the value lost. - Use ≈ where a parallel result is a reordered sum of key-rate results. - State the `spread` repricing test and domain bound as the code checks them, and give `spread` and `zspread` their full signatures. - Shorten the zero-stream caveats to a link; say plainly that callback and contract forms do not use the zero-stream convention. - `breakeven` returns the time from which the balance stays nonnegative. - Scope the `_gap` comment: only two `Signed`/`Unsigned` integers subtract exactly; `Bool` and integer-float pairs convert first. - Clarify the shock-coordinate, parallel-grid and contract-context comments. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Docs pages, README and landing page, each claim checked against the code: - A new floater's effective duration is small, not the time to its next reset, and its spread duration is close to a fixed-rate bond's, not its maturity (0.19 and 4.60 years for the 5-year example). - The multi-curve example labelled relative durations as IR01/CS01; it now shows the dollar risk per role. Discount layers are not basis spreads. - A bare HullWhite keeps its closed forms; it is not valued only on its discount function. `Scenarios` already reuses one seed per call. - State the domains the code has: linear-interpolation input risk equals the key-rate decomposition only inside the knot range; knot bumps match a hat at the knots; a portfolio of self-timed contracts sharing a reporting currency is worth ≈ the sum of its parts. Use ≈ for reordered sums. - Upgrade guide: drop the "new" parallel forms v5 already had and the internal-only bullets; say convexity changed for yield models; state what changed for unmarked contract DV01 and convexity, and list only v5 calls that existed; describe the KeyRateZero migration, integer wasserstein gaps and the spread convergence test as the code does them. - Quickstart values round correctly (105.66, 10.63); the README `discount` example takes a time; the argument-order tip matches callback-first. - Move the floater key-rate example next to the two-curve key-rate forms and drop the separate section; shorten repeated IR01 = CS01 and zero-stream explanations to one statement and links; consistent terms (credit curve, normalized, key-rate, Hull–White, AD, V for value). Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
FinanceCore 3 now throws when amounts and times differ in length, so the unused trailing times of a shared grid, which ActuaryUtilities accepts, are left out before the per-path present value. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
`zspread(...).zspread` is now `Continuous(s)`, as `spread` returns a `Periodic` rate, and `zspread_dv01` stays a number. A number added to a curve is read as an annual rate, so `credit + result.zspread` mispriced a 5-year bond by 2.2e-4 per unit of face; the typed spread reprices. `s0` may be a number, read as continuously compounded, or a `Rate`. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
`z + Periodic(0.01, 1)` adds log(1.01) in z's continuous convention; it is not +100 bp annual effective. The example now shows both. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
duration(issue_date, date) shared a name with interest-rate duration. It is now policy_duration(issue_date, date), with the same results. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
price was abs(present_value(...)), and nothing dispatched on Duration. Statistics was an unused dependency, and OptimalTransport imported StatsBase without using it. FinancialMath now owns duration, since policy_duration took the other method. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Cashflows discounted at base + credit, or at a product of named discount layers, have the same derivatives with respect to every layer. The IR01 and CS01 cashflow forms, the two-curve and named cashflow forms of convexity and sensitivities, and _role_keyed returned that one result several times. The combined curve gives it once. The IR01 and CS01 callback forms remain for valuations in which the curves differ. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Every fixed-cashflow kernel now takes its inputs from _cashflow_inputs. It resolves omitted times to the amounts' indices before any reindexing, reuses 1-based vectors, collects tuples and generators once, views offset vectors from 1, and trims unused trailing times with a view. Amounts and times therefore pair by position, as in FinanceCore. Offset times used to pair by index, and offset key-rate grids read out of bounds inside @inbounds loops; KeyRates now keeps a 1-based copy of its tenors. Key-rate and Scenarios cashflow forms accept tuples and generators like the scalar forms. present_values, breakeven and spread use the same boundary. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
_newton holds the loop: one value-and-derivative evaluation per step, an exact-root exit, and the iteration limit. Each solver passes its own step rule, so spread keeps its damping, its domain protection and its repricing check scaled by gross value, and zspread keeps its continuous coordinate and step-size acceptance. Results and messages are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
…tract sensitivities now returns (; value, duration, dv01), or with SecondOrder() also convexity. FirstOrder() is the default. value is always a number; the derivative fields are numbers for parallel shifts, vectors and matrices with KeyRates, and keyed by role with several curves. One normalizer builds every result from the total value and dollar derivatives. Without KeyRates each role takes one parallel shock, so no tenor gradient is built and summed, and FirstOrder takes no second derivatives. The DV01() forms of sensitivities are removed. Contract measures take the curve first and the index curve as a keyword, as in Models(discount; index). Contract sensitivities report the discount and index roles; effective convexity is the sum of all four blocks, and convexity(Spread(), ...) is new. zspread takes (discount, contract, price; index). A vector of Cashflows after a curve is fixed cashflows, and other contract vectors are portfolios. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
dv01(valuation, args...) forwards to duration(valuation, DV01(), args...) for a rate or curve, a KeyRates grid, two curves and named curves, so callable structs and do-blocks work as they do for duration. With several curves, duration(valuation, DV01(), ...) returns one DV01 per role, the dv01 field of sensitivities. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Scenarios now requires horizon, which must be a whole number of timesteps up to rounding. It validates the grid with FinanceModels.simulation_steps, the function simulate counts steps with, before drawing a seed, and stores the step count and the seed. An unaligned horizon throws ArgumentError instead of silently reaching the next grid point. Every valuation simulates the same paths from the stored seed and never touches the caller's RNG, so results are reproducible and add across positions with different maturities. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
The dispatch test compared the selected method with a signature that no method has, so it always passed. It now checks that every yield type selects the same analytic duration and convexity methods, and that their results are the closed forms summed in payment order, to the bit. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Add a cheat sheet of call shapes to the upgrade guide and reconcile its v6 notes with the curve-first contract forms, the order markers and the Scenarios horizon. Update the sensitivities page, the financial math page, the overview and the README. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
Scenarios stored the validated step count, but nothing read it: simulate counts the steps from the same horizon and timestep with the same function. The tests now check the grid by its effect, a payment at the horizon valued and one a step later throwing. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
present_values discounted each entry over its paired time and added Cashflow objects to the accumulator, so a Cashflow at time 2 paired with time 10 was worth 74.08 instead of 94.18, and Cashflows at different times threw. Each payment is now read through its amount and resolved time, and the entries are numbers of the type the zero-stream rule gives. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
A single offset input reached ForwardDiff with its offset axis, since `reduce(vcat, ...)` returns a lone vector as it is, and ForwardDiff rejected it. Every input is now viewed from 1 before it is concatenated: the valuation receives 1-based vectors of the same lengths, and the derivatives are 1-based. Ordinary vectors are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
convexity(valuation, [KeyRates(t),] base, credit) returned (; base, credit, cross), while the convexity field of sensitivities(valuation, SecondOrder(), ...) nests by role. Both now return (; base = (; base, credit), credit = (; base, credit)) from one normalizer, without building the durations and DV01s. With KeyRates, credit.base is the transpose of base.credit. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
dv01 repeated duration(DV01(), ...) and duration(valuation, DV01(), ...), and held the contract calculations itself. Those now live in duration(DV01(), Effective() | Spread(), [KeyRates(t),] discount, contract; index), and the fixed-cashflow and key-rate routers send contracts there. Markers come in the order DV01(), then Effective() or Spread(), then KeyRates. Every sensitivities result keeps its dv01 field. The upgrade guide maps each removed call. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
DollarConvexity() selects H = ∂²V/∂sᵢ∂sⱼ in the usual shock coordinates, with no factor of one-half and no basis-point scaling, for fixed cashflows (also scalars and Rates), callbacks on one or two curves, and contracts (Effective() by default, or Spread()), with or without KeyRates, in the layouts of convexity. Second-order sensitivities return the same Hessian as dollar_convexity, also for named curves, market inputs and Scenarios; first-order results are unchanged. It is defined at zero value and adds across positions: cashflows [-1, 1] at [0, 1] under a 0% continuous rate are worth zero, with DV01 0.0001 and dollar convexity 1. The analytic kernels and the AD engine already computed the Hessian, so it is returned without another derivative evaluation or division by value. Normalized parallel convexity now divides the raw second derivative by the value instead of differentiating abs(value); the values are the same. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Nw2FiivhYrC16532c1mJQN
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Merge map (next version, 2026-10-04)
The next majors: FinanceCore 3.0, FinanceModels 7.0, ActuaryUtilities 6.0 and MortalityTables 3.0. Merge every PR with Create a merge commit. In the FinanceModels stack, automatic branch deletion retargets the next PR onto
masterafter each merge: check its base and let its CI finish before merging it.masterThis PR: ActuaryUtilities #161, the only open PR for ActuaryUtilities. It merges after FinanceCore 3.0.0 and FinanceModels 7.0.0 are registered, on your go-ahead.
Revised 2026-10-02 (next-version review): eight commits, 498195a through a7422e3, developed against the FinanceModels 7 stack top (valuation contexts) and FinanceCore 3.
_valueis one line,present_value(FinanceModels.Models(discount; index), target): the bumped discount curve discounts and prices, and every model a contract reads by key is the bumped index curve. FinanceModels 7 removedmodel_requirementsandProjection(c; index), and FinanceCore 3 values a collection of contracts as the sum of its contracts, so the closed-form branch and the vector method are deleted. ACompositeof closed forms, or of a closed form and a fixed bond, now has risk (it threw). A custom contract is valued by FinanceModels: a cashflow projection, or a closed formpresent_value(ctx, c::MyContract)readingdiscount(ctx, t),ctx[key]andvaluation_model(ctx). A closed form defined only for a yield model is not reached through the context, and a contract with neither throws aMethodError._coordinate(y)states the docs' shock-coordinate table: the convexity weight t(t + 1/m), with 1/m = 0 for continuous coordinates and yield models, and the divisor 1 + y/m. Macaulay, modified duration, DV01 and convexity are each one method for scalars,Rates and yield models alike. The per-type methods, the automatic-differentiation route for scalar andRateDV01,_macaulay_ratioand_zero_shiftedare deleted. Macaulay, modified duration and convexity were identical in value and type to the previous code in a comparison of 2,850 cases (rates, curves and streams, zero streams and errors included). DV01 for scalar andRateinputs moves by at most 4 ulp in Float64 and is computed at the rate's precision: a Float32 rate with Float32 amounts gives a Float32 DV01, where it gave Float64. Vector methods defaulttimes = eachindex(cfs).duration(f, curve),duration(f, DV01(), curve),duration(f, IR01(), base, credit),convexity(f, kr, curve),sensitivities(f, kr, curves), assensitivities(f, inputs)already was. Do-blocks therefore work for every input type, scalar andRateincluded. The 18 reverse-order forwarders and the three ambiguity patches (twoinvokes and a Hull–White contract disambiguator) are deleted, andTest.detect_ambiguitiesreports none. Contract forms keep(marker, target, curve). Because the untyped callback slot no longer catches contracts,duration(DV01(), kr, bond, curve),dv01(kr, bond, curve)andconvexity(kr, bond, curve)return effective key-rate risk instead of calling the bond. The callback-second orders throw aMethodError;upgrade.mdhas the table.Scenarios(379c02d).Scenarios(hw; n_scenarios, timestep, horizon, rng)is not a yield model:sensitivities(f, kr, s)passes simulated paths tof, andsensitivities(kr, s, cfs, times)values fixed cashflows as their mean present value. A bareHullWhiteis a curve to every measure, sosensitivities(kr, hw, cfs, times)agrees withduration(kr, hw, cfs, times)instead of returning a Monte Carlo estimate under the same name. The simulation is unchanged, and its results matched the previous head exactly in a comparison: one seed drawn per call and reused in every AD evaluation and bump, zero streams valued onhw.curvewithout simulating or touching the RNG, and horizon defaults of 30 years for callbacks and one year past the last payment for cashflows. The bumped model is rebuilt withConstructionBase.setproperties(hw; curve)instead of positionally (new dependency: ConstructionBase 1.5).wassersteinno longer wraps around on integer samples (e51ef19). The three exact transport kernels tookabs(x - y)in the samples' own type:wasserstein(UInt8[0], UInt8[1])was 255 andwasserstein(Int8[-100], Int8[100])was 56. One helper,_gap, converts both values to the accumulator's float type before subtracting, so these are 1 and 200. Float32 samples' gaps are no longer rounded to Float32 first, which can change results in the last bits._hat_bumpreads the interval and weights from_active_hats, and a yield model's parallel shift is the one-knot grid's bump, so the scalar callback, contract and two-curve forms shift curves through one constructor; discount factors and hat values matched the former code exactly in a comparison, including infinite and nested-dual bumps. A one-knot grid's hat is flat and is returned without weighting, which removes the slowdown the first version of this change had added toduration(Effective(), floater, curve). IR01 and CS01 select their curve role with a marker (_role), so each two-curve form is one method.FinanceCore = "3"andFinanceModels = "7", so CI fails until both are registered.sensitivities.mdandupgrade.md(callback order,Scenarios, valuation contexts, the DV01 kernel andwasserstein), plus the call forms inconvexity.md,financial_math.md,index.mdand the README.Scenarios(and that it is not a yield model, so a bareHullWhiteequals its curve); Aqua with 0 ambiguities and no patches. 5,161 pass on Julia 1.12 and 1.10 against FinanceModels' valuation-contexts head and FinanceCore 3.RateDV01 −61% and −83% (6 → 0 allocations); two-curve IR01 and convexity for fixed cashflows −47% and −28%; contract measures −8% to −21% (effective and spread duration, key rates for a bond, swap, floater and portfolio); integerwasserstein−10%; curve duration, DV01 and convexity within ±2%.convexity(f, curve)is 9–15% slower (about 150 ns), a side effect of the FinanceModels inlining that tookduration(f, curve)from 20% slower back to −1%.The notes below are kept as written, with corrections where this round made them false.
Updated 2026-10-01 (#160 folded in): aff5836 brings in #160, which is closed.
InterestRateSwap's transformed floating leg, which threw aMethodError. One helper,_value, replaces_cvalueand_cvalue2. (Corrected 2026-10-02: this note's mechanism, FinanceModels'model_requirementswith a closed-form branch, is gone;_valuenow values in a FinanceModels valuation context, see above.)reprojectis removed; usepresent_value(Models(discount; index = index_curve), contract), orModels(discount, Dict(key => curve, ...))for distinct index curves or FX. (Corrected 2026-10-02: this note saidProjection(contract; index)and required custom contracts to declaremodel_requirements; both are removed in FinanceModels 7.)model_requirementson 2026-10-02.)Updated 2026-09-30 (docs): 476e08d rewrites the two-curve section of the sensitivities page. The equal IR01/CS01 rule for fixed cashflows is now a note; a 5-year floater (coupons reset on the base curve, discounted at
base + credit) sits beside the fixed cashflows with IR01/CS01 side by side, why the floater's IR01 is small, a bar chart and a link to the contract-based effective vs spread durations; the key-rate example reuses that floater and labels its vectors as key rate durations (it had called their sums IR01 and CS01). No code changes; the docs build clean.Updated 2026-09-28 (thermo-nuclear review): ten commits from the 2026-09-28 code-quality review of the whole upgrade.
Breaking: every key-rate grid is a
KeyRates(tenors)marker (f593733).v5.7 made
KeyRates(tenors)"the single uniform way to specify the knot grid". v5.8 (Unify duration/sensitivities across contracts & portfolios; multi-curve; dv01 verb (supersedes #140) #141) then added contract forms that take a positional tenor vector, and a named-curve form that takes atenorskeyword. Neither came with a stated reason.These forms are removed. The upgrade guide lists their replacements:
sensitivities(target, curve, tenors)sensitivities(KeyRates(tenors), target, curve)sensitivities(target, forward, credit, tenors)sensitivities(KeyRates(tenors), target, forward, credit)sensitivities(target, tenors; discount, index)sensitivities(KeyRates(tenors), target; discount, index)sensitivities(valuation, curves; tenors)sensitivities(valuation, KeyRates(tenors), curves)(callback first since 2026-10-02)sensitivities(curves; tenors) do c … endsensitivities(KeyRates(tenors), curves) do c … endCustom valuations, portfolios and separate discount roles (
rf,credit,index) work as before.sensitivities(KeyRates(tenors), contract, hw)is added, matching the existingduration(kr, contract, hw). (Corrected 2026-10-02: the two forms no longer need keeping apart. A bareHullWhiteis a curve everywhere, simulation goes throughScenarios(hw; …), and the Hull–White contract disambiguator is deleted.)One named-role AD engine (e130df2, 68779a3).
_named_adnow does this for both.value,duration,dv01,key_rateandkey_rate_dv01for both.Key-rate cashflow times default to
eachindex(cfs)(a657dac).Cashflow's own time, so the 13Vector{Cashflow}forwarders and_extract_cfs_timesare gone. With 60 cashflows, allocations fall from 1,312 to 176 bytes.sensitivities(KeyRates(t), hw, cashflows)without times valuedhwas a fixed curve, while the call with times simulated. (Corrected 2026-10-02: this note made the call without times simulate too; now neither simulates. A bareHullWhitediscounts on its curve in both, andScenarios(hw; …)requests simulation.)Contract measures price once (762b6dd, eb62bd7).
_contract_parallelgets the value and the slope from one derivative evaluation, anddv01takes only the derivative.zspreadreuses_contract_parallel_value(Spread(), …).Smaller cleanups.
_spread_floordispatches on periodic compounding (3737934).scalar_measures.jlis split (20e3038; the code moves unchanged). The new files are:measures.jl, with the marker types, included first;derivatives.jl;valuation.jl;spread.jl.cashflow_risk.jlmoves intofinancial_math/.Results are unchanged.
Timings (before → after):
Everything else is within ±1%, except the order-2 two-role callback at +2.7%.
Full suite: 4,720 tests pass on Julia 1.12.5 and 1.10.10 against registered FinanceModels 6.5 and FinanceCore 2.7. Against FinanceModels #326 and FinanceCore #56 at their new heads, 4,732 pass, including the 12 Downstream checks. The docs build clean.
Updated 2026-09-27 (structural review): one commit, from the 2026-09-27 structural review.
role (
gradient.role,hessian.role.role), but two private adapters turned that into furtherschemas (
gradient/hessianfor one curve;base_gradient,credit_hessian,cross_hessian, ...for two), the analytic path rebuilt the second, and each public method normalized its own shape.
(; value, gradient, hessian, zero_stream)keyed by role. The analytickernel still computes one gradient and Hessian and exposes them under every role without copying.
The AD engine's
zero_streamis always false: a zero callback value doesn't identify a zerostream.
array is still new.
_keyrate_ad, the two-curve_keyrate_analyticand_conv_blocksare gone(−53 lines net).
Float32, BigFloat, outer duals, parallel forms, do-blocks) is identical to before, type included.
Every public method still infers, now tested.
sensitivities15 → 8, parallel two-curveconvexity11 → 4, two-curve AD callback 41 → 37), and times are unchanged: every key-rate workload in the benchmark suite is within ±2% of before. The two-curve AD callback read 9% slower inside the full suite's process, but alone it measured 130–132 µs both before and after.Full suite: 4,686 tests pass on Julia 1.12.5 and 1.10.10 against registered FinanceModels 6.5 and
FinanceCore 2.7. With FinanceModels 6485528 (#325 plus the structural PR) and FinanceCore #56 at
53d3d90 it's 4,698, including the 12 Downstream checks.
Updated 2026-09-27 (benchmark review): two commits, from the 2026-09-27 benchmark review.
moicwidens before negating (62a169e). 30f4cf2 negated each contribution beforesumwidens small integers, so
-typemin(Int8)wrapped:moic(Int8[-128, -1, 64])was −0.504, not64/129 = 0.496.
widening, still gives +0 (a ratio of +Inf) with no contributions, and keeps Float32 amounts
Float32.
typemincontribution, already wrong in 5.12, is fixed too.Cashflows.spreadprices each iterate once (17f5be7). With the repricing check (3ae7c48),spreadof360 cashflows took 1.76× 5.12's time. Each Newton step priced in Float64 and again as a dual
number for the derivative, and the accepted candidate was discounted twice.
ForwardDiff.derivativemakes,keeping any outer partials.
another order. Taking the dual value instead doubled the root's rounding error (mean 5e-17
against 2.5e-17 over 300 random cases); with this step it is 2.2e-17.
moic's contributions are no longer negated before summing.Full suite: 4,672 tests pass on Julia 1.12.5 and 1.10.10 against registered FinanceModels 6.5 and
FinanceCore 2.7. With FinanceModels 56e8c1e and FinanceCore #56 at 53d3d90 it's 4,684, including
the 12 Downstream checks.
Updated 2026-09-27 (speed): one commit, from profiling against ActuaryUtilities 5.12.
moic's sums are type-stable (30f4cf2).init = false(9827822) made each accumulator aUnion{Bool, Float64}, somoictook 103 ns against 5.12's 34 ns._zero_amount(cfs), the amounts' zero for a concrete element type.−0.0 and return −Inf when nothing was invested.
0.0, no contributionsInf, empty or all-zeroNaN.moic([1.0]) === Inf,Any[]streams, and@inferredfor concreteelement types.
discount fixes (the new FinanceModels speed PR, stacked on #324). No change here.
Full suite: 4,663 tests pass on Julia 1.12.5 and 1.10.10 against registered FinanceModels 6.5 and
FinanceCore 2.7. With FinanceModels 5f83d30 and FinanceCore #56 at 5572e38 it's 4,675, including the
12 Downstream checks.
Updated 2026-09-27: three commits from the published-stack review (
review-artifacts/2026-09-26-published-review/):Zero streams in abstract collections (790aba2). b45b9f6 typed a zero stream's time by its element type. A
Cashflow[...]collection (abstract element type) therefore took an untyped zero and ignored its embedded times. With Float32 amounts at BigFloat times, a nonzero stream's duration was BigFloat, but the all-zero stream's was Float32.Any[...]streams promoted the supplied times, not the embedded ones. A nonempty collection whose element type isn't concrete now promotes the times its payments use (aCashflow's own time, a number's supplied time), as_zero_amountalready scans the amounts present. Concrete and empty collections keep the type-only path.moicevaluates its formula with empty sums of zero (9827822). After b4eaaaa, one-sign input failed from a sum over no terms. That error is Julia's refusal to type an empty reduction, not an undefined quantity: aMethodErroron Julia 1.10 and anArgumentErroron 1.12, which failed the minimum-version and Downgrade jobs. By definition an empty sum is zero:0.0;Inf(x/0);NaN(0/0).The amounts' type is kept. v5 threw an
ArgumentErrorfor these; the upgrade guide says so. The docstring (031438f) says that a division by zero is still undefined, not a meaningful multiple.Full suite: 4,656 tests pass on Julia 1.10.10 and 1.12.5 against registered FinanceModels 6.5 and FinanceCore 2.7, and 4,668 (with the 12 Downstream checks) against FinanceModels #324 at 5698867 and FinanceCore #56 at 0a2f2a4.
Updated 2026-09-26: six commits from two follow-up reviews:
spreadchecks that its answer reprices (3ae7c48). A tiny Newton step used to be accepted on its own: near an annual rate of −100% the price derivative is huge, so the step was tiny far from the root.rate(spread(-1 + 1e-13, 0.05, [1.0], [1.0]))returned 1e-13 instead of 1.05.toland its pricing residual is withinsqrt(eps)of the gross discounted value, which doesn't depend on notional.-0.999clamp is replaced by steps that go at most halfway to the domain floor:-1, or-1 - rfor a scalar or annual base r under nominal addition. Spreads of −0.49 (base −0.5) and −0.9999 (base 0) are now reachable.zspreaddocuments why its step criterion bounds the residual.Scale-equivariance tests for
spreadandzspreadat notionals 1e-12, 1 and 1e10, against closed forms (9124b1d).Checks the language already makes are removed (b4eaaaa): three unreachable checks in the shared engine, and
moic's pre-check (moic is now defined for these inputs; see the 2026-09-27 note). A stale docs line is fixed.Zero cashflow streams are typed like a nonempty result (930f45e). An empty or all-zero stream returns a positive zero of the type a nonempty stream would give: one discount query at time zero determines it.
duration(big(0.03), Float64[])is now aBigFloat, and Float32 amounts with a Float64 rate give Float64, both as for nonempty streams. Untyped empties (Any[],Cashflow[],()) are typed by the rate or curve instead of an inventedFloat64. This matches FinanceCore CompatHelper: bump compat for "Yields" to "0.6" #56's empty present value. Seeupgrade.md.spreadstays differentiable where it damps (b483508).copysign(max_step, newton)converted a ForwardDiff step to Float64, so differentiatingspread(-0.5, y, [1.0], [1.0])at y = −0.99 threw although the primal solve works. The damping decision now uses the primal step; the root keeps its partials (derivative 1 in the target, −1 in the base there).Zero wrapped streams take their embedded time type (b45b9f6). For
Cashflowelements, valuation uses the embedded times and ignores the supplied ones, but the zero-stream type promoted the supplied times: Float32 amounts, times and curve gave Float32 results for a nonzero stream and Float64 for its zero or empty counterpart when the supplied times were Float64. The zero-stream time type now follows valuation.Full suite: 4,638 tests pass against the registered FinanceModels 6.5, and against FinanceModels 7 source with FinanceCore #56 (plus FinanceModels' 12 downstream integration checks). The 2026-09-26 implementation rereview's spread and zero-stream probes pass.
This v6.0 release unifies the sensitivity APIs around one rule: each input is shocked in its native form. A scalar is shocked as an annual rate, a
Ratein its own compounding, and any yield model (includingYield.Constant) as a continuous-zero parallel shift. The new Shock coordinates section documents it.Behavior changes
[5, 5, 105]at[1, 2, 3]underYield.Constant(Periodic(0.04, 1)), convexity changes from 11.26 to 8.40.base + spread, shocked in that rate's coordinate. Before, mixed input types measured different 1bp moves: a curve base with a scalar spread gave CS01 ≈ IR01 / (1 + spread).duration/DV01/IR01/CS01/convexityforms withtenors, their callback and do-block variants, and the contract forms withtenors.DV01do-block, two-curve callback IR01/CS01, two-curve convexity blocks, and contract forms on(target, curve)and(target, forward, credit).MethodError. The upgrade guide has a migration table.KeyRateZero/KeyRate/KeyRateParAPI is removed.KeyRatesapplies the same bumps with exact derivatives. Exact par and quote key rates (QuoteKeyRatesandCalibrationQuotes) will follow in a separate PR, built on FinanceModels 7.Effective(), matching duration.API and implementation
Cashflowtimes are honored throughout, including Hull–White default horizons.Rates and yield models alike.Validation
KeyRatessums;Downstream: FinanceModels' integration test checks the v6
Yield.Constantconvexity (FinanceModels #314), and its Downstream workflow runs this branch's test suite. ActuaryUtilities 6.0 is registered after FinanceCore 3.0 and FinanceModels 7.0.Updates since 2026-10-02
From the third review (2026-10-02), the final review (2026-10-03), the ergonomics review and review 8 (2026-10-04). The call shapes here supersede the earlier ones in this description;
docs/src/upgrade.mdhas a cheat sheet.Call shapes and results
index, which defaults to the discount curve:duration(Effective(), discount, contract; index = discount), and the same forSpread(),dv01,convexity,sensitivitiesandzspread(discount, contract, price; index). The contract-first calls and positional(forward, credit)curves throw aMethodError.sensitivitiesshape, with order markers. It returns(; value, duration, dv01), and withSecondOrder()alsoconvexity;FirstOrder()is the default.valueis a number. The derivative fields are numbers, per-tenor vectors withKeyRates, or keyed by role:s.dv01.discountands.dv01.indexfor a contract,s.convexity.base.creditfor two curves. WithoutKeyRates, each role takes one parallel shift. Effective convexity includes the cross terms.convexityis keyed by role, as theconvexityfield ofsensitivitiesis:(; base = (; base, credit), credit = (; base, credit)). WithKeyRates,credit.baseis the transpose ofbase.credit.dv01is removed (55341d9).duration(DV01(), …)is the one standalone DV01 and takes every formdv01did:duration(DV01(), [KeyRates(t),] curve, cfs, times),duration(valuation, DV01(), [KeyRates(t),] curve | base, credit | named_curves)with do-blocks, andduration(DV01(), [Effective() | Spread(),] [KeyRates(t),] discount, contract; index). Everysensitivitiesresult keeps itsdv01field. The upgrade guide maps each removed call.DollarConvexity()selects the signed second derivativeH = ∂²V/∂sᵢ∂sⱼin the usual shock coordinates, with no factor of one-half and no basis-point scaling, for fixed cashflows (also scalars andRates), callbacks on one or two curves, and contracts, with or withoutKeyRates, in the layouts ofconvexity. Second-ordersensitivitiesreturn the same Hessian asdollar_convexity, also for named curves, market inputs andScenarios; first-order results are unchanged. It is defined at zero value and adds across positions: cashflows[-1, 1]at[0, 1]under a 0% continuous rate are worth zero, with DV01 0.0001 and dollar convexity 1. The Hessian the analytic kernels and the AD engine already computed is returned, with no extra derivative evaluation; normalized parallel convexity now divides the raw second derivative by the value instead of differentiatingabs(value)(same values).Scenarios(hw; horizon, n_scenarios, timestep, rng)fixes the horizon, the grid and one seed at construction. The horizon must be a whole number of timesteps (FinanceModels'simulation_stepsdecides). Valuations reuse the same paths, so results add across calls, and a payment past the horizon throws.price(usepresent_value), the fixed-cashflow IR01, CS01 and two-curve convexity forms (they equalduration(DV01(), base + credit, cfs, times)andconvexity(base + credit, cfs, times)), and theDurationsupertype. The dateduration(issue_date, date)ispolicy_duration.Fixes
KeyRatesgrid read out of bounds. Ordinary vectors are used without copying; tuples and generators are collected once.KeyRateskeeps its own copy of its grid.present_valuespays aCashflowat its own time and returns numbers: aCashflowat time 2 paired with time 10 was aCashflowworth 74.08 instead of 94.18, andCashflows at different times threw.duration(Effective(), cap, hw)and itsCompositeand key-rate forms threw aMethodError: the bump wrapped the model, so the cap and swaption kernels no longer received aHullWhite. A bump now moveshw.curveand keeps the model, inScenariostoo.wassersteinon large integers. Adjacent samplestypemax(Int64) - 1andtypemax(Int64)were 0.0 apart. Integer gaps are now subtracted exactly, then rounded once.zspreadreturns aContinuousrate, socredit + zspread(…).zspreadreprices; a bare number was read as annual effective (2.2e-4 off on a 5-year bond).:index, which the projection curve silently replaced, throws.spreadandzspreadshare one Newton loop, and each keeps its own safeguards.Tests at 2661464: 7,159 on Julia 1.12 and 1.10 with
--check-bounds=yes(Aqua included), against FinanceModels 7 (b22f39b) and FinanceCore 3 (ad90877). Against 387ef5c, every unchanged call gives identical values with the same allocations, and second-order bundles adddollar_convexitywith no extra allocations or valuation calls. Ordinary-vector hot paths gain no allocations, and their timings are within noise. The docs build.🤖 Generated with Claude Code