diff --git a/Examples/AdjointAmericanEquityOption/AdjointAmericanEquityOptionXAD.cpp b/Examples/AdjointAmericanEquityOption/AdjointAmericanEquityOptionXAD.cpp index 7dd10b9..954b1b6 100644 --- a/Examples/AdjointAmericanEquityOption/AdjointAmericanEquityOptionXAD.cpp +++ b/Examples/AdjointAmericanEquityOption/AdjointAmericanEquityOptionXAD.cpp @@ -117,6 +117,33 @@ Real priceWithSensi(Rate riskFreeRate, const Calendar& calendar, return value; } +#else + +// Sensitivities by bumping each input (central difference), in the order of the XAD version +Real priceWithSensi(Rate riskFreeRate, const Calendar& calendar, + const Date maturity, Real strike, const Date settlementDate, + DayCounter dayCounter, Volatility volatility, Date todaysDate, + Spread dividendYield, Option::Type type, Real underlying, + const std::vector& exerciseDates, std::vector& gradient) +{ + // the FD price is smooth in its inputs: error about h^2, round-off about 1e-16 * v / h + const Real h = 1e-4; + auto price = [&](Rate r, Real k, Volatility vol, Real s, Spread q) { + return priceAmerican(r, calendar, maturity, k, settlementDate, dayCounter, vol, + todaysDate, q, type, s, exerciseDates); + }; + Real value = price(riskFreeRate, strike, volatility, underlying, dividendYield); + + Real r = riskFreeRate, k = strike, vol = volatility, s = underlying, q = dividendYield; + gradient.push_back((price(r + h, k, vol, s, q) - price(r - h, k, vol, s, q)) / (2 * h)); + gradient.push_back((price(r, k + h, vol, s, q) - price(r, k - h, vol, s, q)) / (2 * h)); + gradient.push_back((price(r, k, vol + h, s, q) - price(r, k, vol - h, s, q)) / (2 * h)); + gradient.push_back((price(r, k, vol, s + h, q) - price(r, k, vol, s - h, q)) / (2 * h)); + gradient.push_back((price(r, k, vol, s, q + h) - price(r, k, vol, s, q - h)) / (2 * h)); + + return value; +} + #endif void printResults(Real v, const std::vector &gradient) @@ -158,21 +185,17 @@ int main() std::cout.precision(10); + std::vector gradient; #ifdef QLAAD_DISABLE_AAD - std::cout << "Pricing American equity option (without sensitivities)...\n"; - Real v = priceAmerican(riskFreeRate, calendar, maturity, strike, - settlementDate, dayCounter, volatility, todaysDate, - dividendYield, type, underlying, exerciseDates); - std::cout << "American equity option value: " << v << "\n"; + std::cout << "Pricing American equity option with bumped sensitivities...\n"; #else - std::vector gradient; std::cout << "Pricing American equity option with sensitivities...\n"; +#endif Real v = priceWithSensi(riskFreeRate, calendar, maturity, strike, settlementDate, dayCounter, volatility, todaysDate, dividendYield, type, underlying, exerciseDates, gradient); std::cout << "American equity option value: " << v << "\n"; printResults(v, gradient); -#endif return 0; } diff --git a/Examples/AdjointAmericanEquityOption/CMakeLists.txt b/Examples/AdjointAmericanEquityOption/CMakeLists.txt index ec2fb89..ff78ee2 100644 --- a/Examples/AdjointAmericanEquityOption/CMakeLists.txt +++ b/Examples/AdjointAmericanEquityOption/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(AdjointAmericanEquityOption AdjointAmericanEquityOptionXAD.cpp) target_link_libraries(AdjointAmericanEquityOption ql_library) if(QL_INSTALL_EXAMPLES) install(TARGETS AdjointAmericanEquityOption RUNTIME DESTINATION ${QL_INSTALL_EXAMPLESDIR}) -endif() \ No newline at end of file +endif() +add_sample_test(AdjointAmericanEquityOption) diff --git a/Examples/AdjointAmericanEquityOption/CheckExample.cmake b/Examples/AdjointAmericanEquityOption/CheckExample.cmake new file mode 100644 index 0000000..2f35f58 --- /dev/null +++ b/Examples/AdjointAmericanEquityOption/CheckExample.cmake @@ -0,0 +1,54 @@ +# Runs the American option sample and checks its exit code, its value and its greeks. +# cmake -DEXAMPLE= -DDISABLE_AAD= -P CheckExample.cmake +# +# The value must match the one below within 1e-8 relative in both builds: it is the +# same double computation in both, so only rounding that differs between compilers +# and platforms moves it, while a change to its inputs, engine or grid that shows in +# the 8th digit fails. Each greek must match the XAD value below, relative to that +# value: within 1e-7 with XAD (the print has 10 significant digits), and within 1e-4 +# with doubles. The finite-difference price is smooth in every input: central bumps +# with h from 1e-2 to 1e-6 agree with each other, and those with h near 1e-4 are +# within 4e-6 of XAD; 1e-4 also leaves room for a forward difference of that size. +# +# Dividend Rho at the sample's dividend yield of 0 needs QuantLib 1.45 or later +# (lballabio/QuantLib#3057, which keeps the derivative of an implied rate when the +# compound factor is 1); before it, XAD gave 3.08e-5, while bumping gives 9.0464. + +set(value 4.486113273) # from the XAD build +set(names "Rho" "Strike Sensitivity" "Vega" "Delta" "Dividend Rho") +set(reference -10.34248692 0.7392268427 10.93683447 -0.6967489009 9.046354776) # from XAD +if(DISABLE_AAD) + set(tolerance 1e-4) +else() + set(tolerance 1e-7) +endif() + +include(${CMAKE_CURRENT_LIST_DIR}/../CheckSample.cmake) +run_example(output) +set(output "\n${output}") + +set(printed) +foreach(name IN LISTS names) + if(output MATCHES "\n${name} *= ([^\n]*)") + list(APPEND printed ${CMAKE_MATCH_1}) + endif() +endforeach() +list(LENGTH printed count) +list(LENGTH names expected) +if(NOT count EQUAL expected) + message(FATAL_ERROR "printed ${count} greeks, expected ${expected}") +endif() + +math(EXPR last "${count} - 1") +foreach(index RANGE ${last}) + list(GET names ${index} name) + list(GET printed ${index} greek) + list(GET reference ${index} stored) + check_printed_close("${name}" ${greek} ${stored} ${tolerance} 0) +endforeach() + +if(NOT output MATCHES "\nAmerican equity option value: ([^\n]*)") + message(FATAL_ERROR "printed no value") +endif() +check_printed_close("value" ${CMAKE_MATCH_1} ${value} 1e-8 0) +message("checked the value and ${count} greeks") diff --git a/Examples/AdjointCDS/AdjointCdsXAD.cpp b/Examples/AdjointCDS/AdjointCdsXAD.cpp index 65d8541..6ce984f 100644 --- a/Examples/AdjointCDS/AdjointCdsXAD.cpp +++ b/Examples/AdjointCDS/AdjointCdsXAD.cpp @@ -130,6 +130,50 @@ Real priceWithSensi(const std::vector& hazardRates, return value; } +#else + +// Sensitivities by bumping each input (forward difference), in the order of the XAD version +Real priceWithSensi(const std::vector& hazardRates, + std::vector& dates, + const std::vector& riskFreeRate, + Date issueDate, + Date& maturity, + Real recoveryRate, + Real fixedRate, + Calendar& calendar, + DayCounter& dayCount, + Real notional, + std::vector& gradient) { + // error about h * T / 2 relative for rates over T <= 2 years, round-off about 1e-16 * v / h + const Real h = 1e-5; + Real value = priceCDS(hazardRates, dates, riskFreeRate, issueDate, maturity, recoveryRate, + fixedRate, calendar, dayCount, notional); + // (value with the bumped inputs - value) / h + auto slope = [&](const std::vector& hazard, const std::vector& riskFree, + Real recovery, Real fixed, Real nominal) { + return (priceCDS(hazard, dates, riskFree, issueDate, maturity, recovery, fixed, calendar, + dayCount, nominal) - + value) / + h; + }; + + for (Size i = 0; i < riskFreeRate.size(); ++i) { + auto bumped = riskFreeRate; + bumped[i] += h; + gradient.push_back(slope(hazardRates, bumped, recoveryRate, fixedRate, notional)); + } + for (Size i = 0; i < hazardRates.size(); ++i) { + auto bumped = hazardRates; + bumped[i] += h; + gradient.push_back(slope(bumped, riskFreeRate, recoveryRate, fixedRate, notional)); + } + gradient.push_back(slope(hazardRates, riskFreeRate, recoveryRate + h, fixedRate, notional)); + gradient.push_back(slope(hazardRates, riskFreeRate, recoveryRate, fixedRate + h, notional)); + gradient.push_back(slope(hazardRates, riskFreeRate, recoveryRate, fixedRate, notional + h)); + + return value; +} + #endif void printResults(Real v, const std::vector& gradient) { @@ -140,12 +184,12 @@ void printResults(Real v, const std::vector& gradient) { std::cout << gradient[i] << ", "; std::cout << "]\n"; std::cout << "Hazard rate sensitivities = ["; - for (int i = 9; i < 17; ++i) + for (int i = 9; i < 18; ++i) std::cout << gradient[i] << ", "; std::cout << "]\n"; - std::cout << "Recovery rate sensitivity = " << gradient[17] << "\n"; - std::cout << "Fixed rate sensitivity = " << gradient[18] << "\n"; - std::cout << "Notional sensitivity = " << gradient[19] << "\n"; + std::cout << "Recovery rate sensitivity = " << gradient[18] << "\n"; + std::cout << "Fixed rate sensitivity = " << gradient[19] << "\n"; + std::cout << "Notional sensitivity = " << gradient[20] << "\n"; } int main() { @@ -177,18 +221,15 @@ int main() { dates.push_back(today + tn[i]); } + std::vector gradient; #ifdef QLAAD_DISABLE_AAD - std::cout << "Pricing a CDS without sensitivities...\n"; - Real v = priceCDS(hazardRates, dates, riskFreeRate, issueDate, maturity, recoveryRate, - fixedRate, calendar, dayCount, notional); - std::cout << "CDS value: " << v << "\n"; + std::cout << "Pricing a CDS with bumped sensitivities...\n"; #else - std::vector gradient; std::cout << "Pricing a CDS with sensitivities...\n"; +#endif Real v = priceWithSensi(hazardRates, dates, riskFreeRate, issueDate, maturity, recoveryRate, fixedRate, calendar, dayCount, notional, gradient); printResults(v, gradient); -#endif return 0; } catch (std::exception& e) { diff --git a/Examples/AdjointCDS/CMakeLists.txt b/Examples/AdjointCDS/CMakeLists.txt index 21174ce..2d4e3c3 100644 --- a/Examples/AdjointCDS/CMakeLists.txt +++ b/Examples/AdjointCDS/CMakeLists.txt @@ -2,4 +2,5 @@ add_executable(AdjointCDS AdjointCdsXAD.cpp) target_link_libraries(AdjointCDS ql_library) if(QL_INSTALL_EXAMPLES) install(TARGETS AdjointCDS RUNTIME DESTINATION ${QL_INSTALL_EXAMPLESDIR}) -endif() \ No newline at end of file +endif() +add_sample_test(AdjointCDS) diff --git a/Examples/AdjointCDS/CheckExample.cmake b/Examples/AdjointCDS/CheckExample.cmake new file mode 100644 index 0000000..fd03c2d --- /dev/null +++ b/Examples/AdjointCDS/CheckExample.cmake @@ -0,0 +1,83 @@ +# Runs the CDS sample and checks its exit code, its value and its sensitivities. +# cmake -DEXAMPLE= -DDISABLE_AAD= -P CheckExample.cmake +# +# The value must be printed exactly as below in both builds. Each sensitivity must +# match the XAD value below, relative to that value: within 1e-7 with XAD (the print +# has 6 significant digits, so this means the same print, up to the rounding of the +# last digit), and within 5e-4 with doubles. Bumping is a forward difference, off by +# about h * T / 2 relative for a step h and times T of up to 2 years here: 1e-5 with +# h = 1e-5 (measured: within 1e-5, the rounding of the print), and 1e-4 with h = 1e-4. +# 5e-4 leaves a margin of 50 and still catches a wrong sign or a shifted entry, off +# by 3% or more. Where XAD gives exactly 0, the value does not depend on that input, +# and bumping it only adds round-off, about 1e-16 * value / h, near 1e-9 here, so +# doubles may differ from 0 by up to 1e-6; that is far above the round-off and below +# 5e-4 of the smallest non-zero sensitivity, the notional's 0.00486724, so it never +# loosens a check that is not of a zero. + +set(value 48.6724) # from the XAD build +set(reference # from the XAD build: rhos, hazard rates, recovery, fixed rate, notional + 0 0 0 7.71442 -22.3278 12.2303 -46.1047 -7.2333 0 + 0 -215.432 -464.008 -563.438 -1491.45 -1474.51 -1432.88 -354.194 0 + 115.967 9854.37 0.00486724) +if(DISABLE_AAD) + set(tolerance 5e-4) + set(floor 1e-6) +else() + set(tolerance 1e-7) + set(floor 0) +endif() + +include(${CMAKE_CURRENT_LIST_DIR}/../CheckSample.cmake) +run_example(output) +set(output "\n${output}") + +# appends the numbers printed after " = " to the list printed, and their names +# to the list labels; a list like "[0, 1.5, ]" adds one number per entry, as [] +function(collect name) + if(NOT output MATCHES "\n${name} *= ([^\n]*)") + return() + endif() + set(numbers "${CMAKE_MATCH_1}") + if(numbers MATCHES "^\\[(.*)\\]$") + string(REGEX MATCHALL "[^ ,]+" numbers "${CMAKE_MATCH_1}") + set(index 0) + foreach(number IN LISTS numbers) + list(APPEND printed ${number}) + list(APPEND labels "${name}[${index}]") + math(EXPR index "${index} + 1") + endforeach() + else() + list(APPEND printed ${numbers}) + list(APPEND labels "${name}") + endif() + set(printed ${printed} PARENT_SCOPE) + set(labels ${labels} PARENT_SCOPE) +endfunction() + +set(printed) +set(labels) +foreach(name IN ITEMS "Rhos" "Hazard rate sensitivities" "Recovery rate sensitivity" + "Fixed rate sensitivity" "Notional sensitivity") + collect("${name}") +endforeach() +list(LENGTH printed count) +list(LENGTH reference expected) +if(NOT count EQUAL expected) + message(FATAL_ERROR "printed ${count} sensitivities, expected ${expected}") +endif() + +if(NOT output MATCHES "\nCDS value *= ([^\n]*)") + message(FATAL_ERROR "printed no CDS value") +endif() +if(NOT CMAKE_MATCH_1 STREQUAL value) + message(FATAL_ERROR "CDS value: ${CMAKE_MATCH_1} differs from ${value}") +endif() + +math(EXPR last "${count} - 1") +foreach(index RANGE ${last}) + list(GET labels ${index} label) + list(GET printed ${index} number) + list(GET reference ${index} stored) + check_printed_close("${label}" ${number} ${stored} ${tolerance} ${floor}) +endforeach() +message("checked the value and ${count} sensitivities") diff --git a/Examples/CheckSample.cmake b/Examples/CheckSample.cmake index 1f11bf9..bc16d69 100644 --- a/Examples/CheckSample.cmake +++ b/Examples/CheckSample.cmake @@ -69,3 +69,78 @@ function(check_relative label number largest digits) message(FATAL_ERROR "${label}: ${number} is more than 1e-${digits} times ${largest}") endif() endfunction() + +# a number as iostreams print it by default (like 48.6724, -3.5e-07 or 0) as an +# integer in units of 1e-9, digits beyond those dropped; also sets _unit to +# one unit of the number's last printed digit, in the same units +function(to_nano number result) + if(NOT number MATCHES "^(-?)([0-9]+)\\.?([0-9]*)(e([-+]?)0*([0-9]+))?$") + message(FATAL_ERROR "${number} is not a number") + endif() + set(sign "${CMAKE_MATCH_1}") + set(digits "${CMAKE_MATCH_2}${CMAKE_MATCH_3}") + string(LENGTH "${CMAKE_MATCH_3}" decimals) + set(exponent 0) + if(CMAKE_MATCH_4) + set(exponent "${CMAKE_MATCH_6}") + if(CMAKE_MATCH_5 STREQUAL "-") + set(exponent "-${exponent}") + endif() + endif() + math(EXPR shift "9 + ${exponent} - ${decimals}") + if(shift GREATER_EQUAL 0) + string(REPEAT 0 ${shift} zeros) + string(APPEND digits "${zeros}") + set(unit "1${zeros}") + else() + string(LENGTH "${digits}" length) + math(EXPR length "${length} + ${shift}") + if(length GREATER 0) + string(SUBSTRING "${digits}" 0 ${length} digits) + else() + set(digits 0) + endif() + set(unit 1) + endif() + string(REGEX REPLACE "^0+" "" digits "${digits}") + string(LENGTH "${digits}" length) + if(length GREATER 18) + message(FATAL_ERROR "${number} is too large to check") + endif() + if(digits STREQUAL "") + set(digits 0) + elseif(sign) + set(digits "-${digits}") + endif() + set(${result} ${digits} PARENT_SCOPE) + set(${result}_unit ${unit} PARENT_SCOPE) +endfunction() + +# fails unless value is within tolerance (like 5e-4) of reference, relative to the +# reference, or within floor (like 1e-3, or 0) absolutely where that allows more; +# both are printed with iostreams' default format, so a non-zero reference may also +# differ by one unit of its last digit, the rounding of the print +function(check_printed_close label value reference tolerance floor) + if(NOT tolerance MATCHES "^([0-9]+)e-([0-9]+)$") + message(FATAL_ERROR "${label}: tolerance ${tolerance} is not like 5e-4") + endif() + set(mantissa ${CMAKE_MATCH_1}) + string(REPEAT 0 ${CMAKE_MATCH_2} zeros) + to_nano(${value} v) + to_nano(${reference} r) + to_nano(${floor} allowed) + absolute(${r} size) + math(EXPR relative "${size} * ${mantissa} / 1${zeros}") + if(relative GREATER allowed) + set(allowed ${relative}) + endif() + if(NOT r EQUAL 0 AND r_unit GREATER allowed) + set(allowed ${r_unit}) + endif() + math(EXPR difference "${v} - ${r}") + absolute(${difference} difference) + if(difference GREATER allowed) + message(FATAL_ERROR + "${label}: ${value} differs from ${reference} (within ${tolerance}, floor ${floor})") + endif() +endfunction()