From c35e5ebbcf275f0ef545511cff2d94c94fca4aef Mon Sep 17 00:00:00 2001 From: Auto Differentiation Dev Team <107129969+auto-differentiation-dev@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:17:27 +0000 Subject: [PATCH 1/2] Check the Bermudan swaption sample's vegas against bump and recalibrate --- .../AdjointBermudanSwaption/CMakeLists.txt | 3 +- .../CheckExample.cmake | 127 ++++++++++++++++++ 2 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 Examples/AdjointBermudanSwaption/CheckExample.cmake diff --git a/Examples/AdjointBermudanSwaption/CMakeLists.txt b/Examples/AdjointBermudanSwaption/CMakeLists.txt index 10d439b..72735b3 100644 --- a/Examples/AdjointBermudanSwaption/CMakeLists.txt +++ b/Examples/AdjointBermudanSwaption/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(AdjointBermudanSwaption AdjointBermudanSwaptionXAD.cpp) target_link_libraries(AdjointBermudanSwaption ql_library) if(QL_INSTALL_EXAMPLES) install(TARGETS AdjointBermudanSwaption RUNTIME DESTINATION ${QL_INSTALL_EXAMPLESDIR}) -endif() \ No newline at end of file +endif() +add_sample_test(AdjointBermudanSwaption) diff --git a/Examples/AdjointBermudanSwaption/CheckExample.cmake b/Examples/AdjointBermudanSwaption/CheckExample.cmake new file mode 100644 index 0000000..95f0161 --- /dev/null +++ b/Examples/AdjointBermudanSwaption/CheckExample.cmake @@ -0,0 +1,127 @@ +# Runs the Bermudan swaption sample and checks its exit code, its price and, with +# XAD, its vegas. +# cmake -DEXAMPLE= -DDISABLE_AAD= -P CheckExample.cmake +# +# The reference is bump & recalibrate in the doubles build, independent of XAD: the +# sample's pricing, with its data, engines and grids unchanged, but the Hull-White +# calibration converged to the least-squares optimum: LevenbergMarquardt(1e-8, +# 1e-15, 1e-15, true), i.e. with the cost function's central-difference Jacobian, +# and EndCriteria(2000, 200, 1e-16, 1e-16, 1e-16), restarted from its result until +# the parameters move by less than 1e-15 (relative). The price below is that +# pricing without bumps, at a = 0.046415256, sigma = 0.0058693096. The default +# Levenberg-Marquardt uses a forward-difference Jacobian and stops with the mean +# reversion 2e-5 (relative) away from the optimum. Each of the 5 calibrated vols +# (vega #4, #8, #12, #16, #20) was bumped on a grid of 81 steps of 5e-5 within +# +-2e-3 and recalibrated each time; the vega is the slope at 0 of a degree-5 +# least-squares polynomial through those prices. A fit rather than a single central +# difference, as the price is not smooth in the vols at small steps: it jitters by +# about 1e-6 between neighbouring bumps and jumps by up to 1e-3 at a few of them +# (such points, more than 10 times the median residual off the fit, are dropped), +# while above 1e-3 the vegas change quickly with the step (vega #20 is 17.85 with +# a 4e-3 central difference). Over the windows +# +-1e-3 and +-2e-3 and degrees 3 to 7, the fitted vegas differ from the reference +# by at most 6e-4 (relative), and the implicit function theorem with XAD agrees +# with it within 3e-4. The other 20 vols are not calibrated to, so their vegas are +# exactly 0, as bumping them confirms. +# +# Each vega must match the reference within 2e-3 relative to it, over 3 times the +# reference's own spread; differentiating through the optimizer's iterations +# instead misses vegas #8, #12 and #20 by 0.7% to 1.7% even at a calibration +# tolerance of 1e-12, and by up to 7% at 1e-8. The price must match within 1e-6 +# relative: stopping the calibration at 1e-8 moves it by 6e-8. Values printed with +# fewer digits than stored are compared to the reference rounded to them, and may +# differ by one unit of their last digit. + +set(price 42.21532351) +set(reference # vega #0 to #24 + 0 0 0 0 10.28901 0 0 0 4.71138 0 0 0 3.35763 0 0 0 7.33365 0 0 0 17.14283 0 0 0 0) + +include(${CMAKE_CURRENT_LIST_DIR}/../CheckSample.cmake) + +# the reference rounded, or padded with zeros, to the decimals of a printed number, +# so that check_relative_close can compare them; shifts by whole digits only, as +# cmake has no floating point +function(to_printed_decimals stored printed result) + foreach(number IN ITEMS stored printed) + set(d 0) + if(${number} MATCHES "\\.([0-9]+)$") + string(LENGTH "${CMAKE_MATCH_1}" d) + endif() + set(${number}_decimals ${d}) + endforeach() + to_units(${stored} r) + if(stored_decimals GREATER printed_decimals) + math(EXPR shift "${stored_decimals} - ${printed_decimals}") + string(REPEAT 0 ${shift} zeros) + math(EXPR half "1${zeros} / 2") + if(r LESS 0) + math(EXPR r "(${r} - ${half}) / 1${zeros}") + else() + math(EXPR r "(${r} + ${half}) / 1${zeros}") + endif() + elseif(printed_decimals GREATER stored_decimals) + math(EXPR shift "${printed_decimals} - ${stored_decimals}") + string(REPEAT 0 ${shift} zeros) + math(EXPR r "${r} * 1${zeros}") + endif() + set(sign "") + if(r LESS 0) + set(sign "-") + endif() + absolute(${r} digits) + if(printed_decimals GREATER 0) + math(EXPR width "${printed_decimals} + 1") + string(LENGTH "${digits}" length) + if(length LESS width) + math(EXPR missing "${width} - ${length}") + string(REPEAT 0 ${missing} zeros) + set(digits "${zeros}${digits}") + endif() + string(LENGTH "${digits}" length) + math(EXPR integer "${length} - ${printed_decimals}") + string(SUBSTRING "${digits}" 0 ${integer} whole) + string(SUBSTRING "${digits}" ${integer} -1 fraction) + set(digits "${whole}.${fraction}") + endif() + set(${result} "${sign}${digits}" PARENT_SCOPE) +endfunction() + +# fails unless a printed number is within tolerance (like 2e-3) of the reference, +# relative to it, after rounding the reference to the printed decimals, or within +# one unit of the printed last digit where that allows more +function(check_printed label printed stored tolerance) + to_printed_decimals(${stored} ${printed} rounded) + check_relative_close("${label}" ${printed} ${rounded} ${tolerance} 1) +endfunction() + +run_example(output) +set(output "\n${output}") + +if(NOT output MATCHES "\nPrice = (-?[0-9,]+(\\.[0-9]+)?)") + message(FATAL_ERROR "no price in the output") +endif() +check_printed("Price" ${CMAKE_MATCH_1} ${price} 1e-6) + +if(DISABLE_AAD) + message("checked the price") + return() +endif() + +string(REGEX MATCHALL "\nVega #[0-9]+ = -?[0-9,]+(\\.[0-9]+)?" printed "${output}") +list(LENGTH printed count) +list(LENGTH reference expected) +if(NOT count EQUAL expected) + message(FATAL_ERROR "printed ${count} vegas, expected ${expected}") +endif() + +set(index 0) +foreach(line IN LISTS printed) + list(GET reference ${index} stored) + string(REGEX MATCH "Vega #([0-9]+) = (.+)$" line "${line}") + if(NOT CMAKE_MATCH_1 EQUAL index) + message(FATAL_ERROR "printed vega #${CMAKE_MATCH_1} where #${index} was expected") + endif() + check_printed("Vega #${index}" ${CMAKE_MATCH_2} ${stored} 2e-3) + math(EXPR index "${index} + 1") +endforeach() +message("checked the price and ${count} vegas") From c18a1c424dac5e61d4c0ca2eed67a538ab290ed2 Mon Sep 17 00:00:00 2001 From: Auto Differentiation Dev Team <107129969+auto-differentiation-dev@users.noreply.github.com> Date: Tue, 17 Nov 2026 20:17:27 +0000 Subject: [PATCH 2/2] Use the implicit function theorem for the vegas in AdjointBermudanSwaption --- .../AdjointBermudanSwaptionXAD.cpp | 346 ++++++++++-------- 1 file changed, 185 insertions(+), 161 deletions(-) diff --git a/Examples/AdjointBermudanSwaption/AdjointBermudanSwaptionXAD.cpp b/Examples/AdjointBermudanSwaption/AdjointBermudanSwaptionXAD.cpp index 95f6cb6..f114bba 100644 --- a/Examples/AdjointBermudanSwaption/AdjointBermudanSwaptionXAD.cpp +++ b/Examples/AdjointBermudanSwaption/AdjointBermudanSwaptionXAD.cpp @@ -22,10 +22,17 @@ */ /* -This example demonstrates how to use XAD to price a Bermudan Swaption with -sensitivities. - -TODO: Use the implicit function theorem for calibration with AAD. +This example demonstrates how to use XAD to price a Bermudan swaption with +sensitivities to the swaption volatilities, through a Hull-White model +calibrated to 5 of them. + +The sensitivities go through the calibration with the implicit function +theorem, without recording the optimizer: at the calibrated parameters p the +gradient of the calibration objective in p is zero, so +dV/dvol = dV/dvol|p - (Hpp^-1 dV/dp)' Hpvol, with the Hessian blocks Hpp and +Hpvol from central differences of the XAD gradient in p (as in the +AdjointHestonModel example). Recording the optimizer's iterations instead gives +the derivative of where it stopped, not of the optimum. */ #include @@ -36,177 +43,195 @@ TODO: Use the implicit function theorem for calibration with AAD. #include #include #include +#include #include #include -#include +#include #include -#include #include -#include #include -#include #include #include #include #include -#include +#include +#include +#include #include #include -#include using namespace QuantLib; -// Number of swaptions to be calibrated to... -void calibrateModel(const ext::shared_ptr& model, - const std::vector>& swaptions, - const std::vector& swapLengths, - const std::vector& swaptionVols, - Size numRows, - Size numCols) { - - std::vector> helpers(swaptions.begin(), swaptions.end()); - LevenbergMarquardt om; - model->calibrate(helpers, om, EndCriteria(400, 100, 1.0e-8, 1.0e-8, 1.0e-8)); -} - -Handle setupYields(Date settlementDate, Real flatRate) { - // flat yield term structure impling 1x5 swap at 5% - auto rate = ext::make_shared(flatRate); - return Handle( - ext::make_shared(settlementDate, Handle(rate), Actual365Fixed())); -} +namespace { + + // the curve, the calibration swaptions and the Bermudan swaption + struct Market { + Handle curve; + std::vector> swaptions; + ext::shared_ptr bermudan; + }; + + // builds the market from the 5x5 swaption vols (by expiry, then swap length); + // the model is calibrated to the diagonal 1x5, 2x4, 3x3, 4x2, 5x1 + Market build(const std::vector& swaptionVols, Real flatRate) { + Market m; + Calendar calendar = TARGET(); + Date settlementDate(19, February, 2002); + m.curve = Handle( + ext::make_shared(settlementDate, flatRate, Actual365Fixed())); + auto indexSixMonths = ext::make_shared(m.curve); + + const Size numRows = 5, numCols = 5; + const Integer swapLengths[] = {1, 2, 3, 4, 5}; + for (Size i = 0; i < numRows; i++) { + Size j = numCols - i - 1; + auto vol = ext::make_shared(swaptionVols[i * numCols + j]); + m.swaptions.push_back(ext::make_shared( + Period(i + 1, Years), Period(swapLengths[j], Years), Handle(vol), + indexSixMonths, indexSixMonths->tenor(), indexSixMonths->dayCounter(), + indexSixMonths->dayCounter(), m.curve)); + } -Real priceSwaption(const std::vector& swapLengths, - const std::vector& swaptionVols, - Size numRows, - Size numCols, - Real flatRate) { - - Date todaysDate(15, February, 2002); - Calendar calendar = TARGET(); - Date settlementDate(19, February, 2002); - Settings::instance().evaluationDate() = todaysDate; - - auto rhTermStructure = setupYields(settlementDate, flatRate); - - // Define the ITM swap - Frequency fixedLegFrequency = Annual; - BusinessDayConvention fixedLegConvention = Unadjusted; - BusinessDayConvention floatingLegConvention = ModifiedFollowing; - DayCounter fixedLegDayCounter = Thirty360(Thirty360::European); - Frequency floatingLegFrequency = Semiannual; - Swap::Type type = Swap::Payer; - Rate dummyFixedRate = 0.03; - auto indexSixMonths = ext::make_shared(rhTermStructure); - - Date startDate = calendar.advance(settlementDate, 1, Years, floatingLegConvention); - Date maturity = calendar.advance(startDate, 5, Years, floatingLegConvention); - Schedule fixedSchedule(startDate, maturity, Period(fixedLegFrequency), calendar, - fixedLegConvention, fixedLegConvention, DateGeneration::Forward, false); - Schedule floatSchedule(startDate, maturity, Period(floatingLegFrequency), calendar, - floatingLegConvention, floatingLegConvention, DateGeneration::Forward, - false); - - auto swap = ext::make_shared(type, 1000.0, fixedSchedule, dummyFixedRate, - fixedLegDayCounter, floatSchedule, indexSixMonths, - 0.0, indexSixMonths->dayCounter()); - swap->setPricingEngine(ext::make_shared(rhTermStructure)); - Rate fixedITMRate = swap->fairRate() * 0.8; - - auto itmSwap = ext::make_shared(type, 1000.0, fixedSchedule, fixedITMRate, - fixedLegDayCounter, floatSchedule, indexSixMonths, - 0.0, indexSixMonths->dayCounter()); - - // defining the swaptions to be used in model calibration - std::vector swaptionMaturities = {1 * Years, 2 * Years, 3 * Years, 4 * Years, - 5 * Years}; - - std::vector> swaptions; - - // List of times that have to be included in the timegrid - std::list