From a99320cdc1c7ce48e482ca3b32a9b010c17b8e6b Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 1 Mar 2022 10:05:23 +0100 Subject: [PATCH 001/322] Remove exported constructor body --- SWIG/stochasticprocess.i | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/SWIG/stochasticprocess.i b/SWIG/stochasticprocess.i index c9c3f11915..66e6906e3f 100644 --- a/SWIG/stochasticprocess.i +++ b/SWIG/stochasticprocess.i @@ -394,28 +394,19 @@ class ExtendedOrnsteinUhlenbeckProcess : public StochasticProcess1D { %shared_ptr(ExtOUWithJumpsProcess) class ExtOUWithJumpsProcess : public StochasticProcess { - public: - ExtOUWithJumpsProcess( + public: + ExtOUWithJumpsProcess( const ext::shared_ptr& process, - Real Y0, Real beta, Real jumpIntensity, Real eta) { - - return new ExtOUWithJumpsProcess( - new ExtOUWithJumpsProcess( - process, Y0, beta, jumpIntensity, eta)); - } + Real Y0, Real beta, Real jumpIntensity, Real eta); }; %shared_ptr(KlugeExtOUProcess) class KlugeExtOUProcess : public StochasticProcess { - public: - KlugeExtOUProcess( + public: + KlugeExtOUProcess( Real rho, const ext::shared_ptr& kluge, - const ext::shared_ptr& extOU) { - - return new KlugeExtOUProcess(new KlugeExtOUProcess( - rho, kluge, extOU)); - } + const ext::shared_ptr& extOU); }; %{ From 30cf3481fc953ff668deaf06ce7b7ba4ff77b91e Mon Sep 17 00:00:00 2001 From: Marcin Rybacki Date: Wed, 2 Mar 2022 16:28:46 +0100 Subject: [PATCH 002/322] Exposed Akima cubic interpolation scheme. --- SWIG/discountcurve.i | 2 ++ SWIG/interpolation.i | 16 ++++++++++++++++ SWIG/zerocurve.i | 2 ++ 3 files changed, 20 insertions(+) diff --git a/SWIG/discountcurve.i b/SWIG/discountcurve.i index 6b6c219576..7e6f3503ea 100644 --- a/SWIG/discountcurve.i +++ b/SWIG/discountcurve.i @@ -32,6 +32,7 @@ using QuantLib::InterpolatedDiscountCurve; %shared_ptr(InterpolatedDiscountCurve); %shared_ptr(InterpolatedDiscountCurve); %shared_ptr(InterpolatedDiscountCurve); +%shared_ptr(InterpolatedDiscountCurve); template class InterpolatedDiscountCurve : public YieldTermStructure { @@ -54,5 +55,6 @@ class InterpolatedDiscountCurve : public YieldTermStructure { %template(MonotonicLogCubicDiscountCurve) InterpolatedDiscountCurve; %template(NaturalCubicDiscountCurve) InterpolatedDiscountCurve; %template(KrugerLogDiscountCurve) InterpolatedDiscountCurve; +%template(AkimaLogDiscountCurve) InterpolatedDiscountCurve; #endif diff --git a/SWIG/interpolation.i b/SWIG/interpolation.i index 25064180ed..529cd88cc1 100644 --- a/SWIG/interpolation.i +++ b/SWIG/interpolation.i @@ -177,6 +177,12 @@ class Kruger : public Cubic { : Cubic(QuantLib::CubicInterpolation::Kruger) {} }; +class Akima : public Cubic { + public: + Akima() + : Cubic(QuantLib::CubicInterpolation::Akima) {} +}; + class DefaultLogCubic : public QuantLib::LogCubic { public: DefaultLogCubic() @@ -198,6 +204,14 @@ class KrugerLog : public QuantLib::LogCubic { QuantLib::CubicInterpolation::SecondDerivative, 0.0, QuantLib::CubicInterpolation::SecondDerivative, 0.0) {} }; + +class AkimaLog : public QuantLib::LogCubic { + public: + AkimaLog() + : QuantLib::LogCubic(QuantLib::CubicInterpolation::Akima, false, + QuantLib::CubicInterpolation::SecondDerivative, 0.0, + QuantLib::CubicInterpolation::SecondDerivative, 0.0) {} +}; %} struct BackwardFlat {}; @@ -212,6 +226,8 @@ struct MonotonicLogCubic {}; struct SplineCubic {}; struct Kruger {}; struct KrugerLog {}; +struct Akima {}; +struct AkimaLog {}; struct ConvexMonotone { ConvexMonotone(Real quadraticity = 0.3, Real monotonicity = 0.7, diff --git a/SWIG/zerocurve.i b/SWIG/zerocurve.i index 5ea246d077..4e8342e21f 100644 --- a/SWIG/zerocurve.i +++ b/SWIG/zerocurve.i @@ -34,6 +34,7 @@ using QuantLib::InterpolatedZeroCurve; %shared_ptr(InterpolatedZeroCurve); %shared_ptr(InterpolatedZeroCurve); %shared_ptr(InterpolatedZeroCurve); +%shared_ptr(InterpolatedZeroCurve); template class InterpolatedZeroCurve : public YieldTermStructure { @@ -61,6 +62,7 @@ class InterpolatedZeroCurve : public YieldTermStructure { %template(LogCubicZeroCurve) InterpolatedZeroCurve; %template(MonotonicCubicZeroCurve) InterpolatedZeroCurve; %template(KrugerZeroCurve) InterpolatedZeroCurve; +%template(AkimaZeroCurve) InterpolatedZeroCurve; #endif From 8bbed7c2d85cef7387ccf6a72b5d23cb83efc0dc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Mar 2022 18:00:54 +0000 Subject: [PATCH 003/322] Bump actions/checkout from 2 to 3 Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2...v3) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/copyrights.yml | 2 +- .github/workflows/link-check.yml | 2 +- .github/workflows/linux.yml | 2 +- .github/workflows/misspell.yml | 2 +- .github/workflows/namespaces.yml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/copyrights.yml b/.github/workflows/copyrights.yml index 472f495cb7..865c342d2b 100644 --- a/.github/workflows/copyrights.yml +++ b/.github/workflows/copyrights.yml @@ -7,7 +7,7 @@ jobs: copyrights: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Check run: | ./tools/check_copyrights.sh diff --git a/.github/workflows/link-check.yml b/.github/workflows/link-check.yml index cbd153f227..29a658a98a 100644 --- a/.github/workflows/link-check.yml +++ b/.github/workflows/link-check.yml @@ -8,5 +8,5 @@ jobs: markdown-link-check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: gaurav-nelson/github-action-markdown-link-check@v1 diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 8dd7d4b8dd..8c445d2ac7 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -9,7 +9,7 @@ jobs: language: [python3, java, csharp, r, scala] container: ghcr.io/lballabio/quantlib-swig-devenv:${{ matrix.language }} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Build and check run: | ./.build/${{ matrix.language }}.build diff --git a/.github/workflows/misspell.yml b/.github/workflows/misspell.yml index 5cbf54c709..d0237ba080 100644 --- a/.github/workflows/misspell.yml +++ b/.github/workflows/misspell.yml @@ -7,7 +7,7 @@ jobs: check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - uses: sobolevn/misspell-fixer-action@master - uses: peter-evans/create-pull-request@v3 with: diff --git a/.github/workflows/namespaces.yml b/.github/workflows/namespaces.yml index e2ee22abbd..fb56537344 100644 --- a/.github/workflows/namespaces.yml +++ b/.github/workflows/namespaces.yml @@ -7,7 +7,7 @@ jobs: namespaces: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v3 - name: Check run: | sed -i -e 's/boost::shared_ptr/ext::shared_ptr/g' SWIG/* From 303db59fd095c284d4c1574dc9e87daae84df663 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Wed, 9 Mar 2022 17:50:20 +0100 Subject: [PATCH 004/322] Remove useless files --- CSharp/Makefile.am | 2 -- CSharp/cpp/QuantLibWrapper.vcxproj | 3 -- CSharp/cpp/QuantLibWrapper.vcxproj.filters | 9 ------ CSharp/cpp/QuantlibWrapper.cpp | 36 ---------------------- CSharp/cpp/QuantlibWrapper.h | 22 ------------- CSharp/cpp/stdafx.h | 13 -------- 6 files changed, 85 deletions(-) delete mode 100644 CSharp/cpp/QuantlibWrapper.cpp delete mode 100644 CSharp/cpp/QuantlibWrapper.h delete mode 100644 CSharp/cpp/stdafx.h diff --git a/CSharp/Makefile.am b/CSharp/Makefile.am index e04ca17279..83ac7b7561 100644 --- a/CSharp/Makefile.am +++ b/CSharp/Makefile.am @@ -47,8 +47,6 @@ dist-hook: $(BUILT_SOURCES) cp ./cpp/*.vcxproj $(distdir)/cpp cp ./cpp/quantlib_wrap.cpp $(distdir)/cpp cp ./cpp/quantlib_wrap.h $(distdir)/cpp - cp ./cpp/QuantlibWrapper.h ./cpp/QuantlibWrapper.cpp $(distdir)/cpp - cp ./cpp/stdafx.h $(distdir)/cpp mkdir -p $(distdir)/csharp cp ./csharp/*.csproj $(distdir)/csharp cp ./csharp/*.cs $(distdir)/csharp diff --git a/CSharp/cpp/QuantLibWrapper.vcxproj b/CSharp/cpp/QuantLibWrapper.vcxproj index 841207f2f1..33992277bb 100644 --- a/CSharp/cpp/QuantLibWrapper.vcxproj +++ b/CSharp/cpp/QuantLibWrapper.vcxproj @@ -184,12 +184,9 @@ - - - diff --git a/CSharp/cpp/QuantLibWrapper.vcxproj.filters b/CSharp/cpp/QuantLibWrapper.vcxproj.filters index 0d50081646..5891cf4c2c 100644 --- a/CSharp/cpp/QuantLibWrapper.vcxproj.filters +++ b/CSharp/cpp/QuantLibWrapper.vcxproj.filters @@ -18,19 +18,10 @@ Source Files - - Source Files - Header Files - - Header Files - - - Header Files - diff --git a/CSharp/cpp/QuantlibWrapper.cpp b/CSharp/cpp/QuantlibWrapper.cpp deleted file mode 100644 index 9f3a3c831e..0000000000 --- a/CSharp/cpp/QuantlibWrapper.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// QuantlibWrapper.cpp : Defines the entry point for the DLL application. -// - -#include "stdafx.h" -#include "QuantlibWrapper.h" -BOOL APIENTRY DllMain( HANDLE hModule, - DWORD ul_reason_for_call, - LPVOID lpReserved - ) -{ - switch (ul_reason_for_call) - { - case DLL_PROCESS_ATTACH: - case DLL_THREAD_ATTACH: - case DLL_THREAD_DETACH: - case DLL_PROCESS_DETACH: - break; - } - return TRUE; -} - -// This is an example of an exported variable -QUANTLIBWRAPPER_API int nQuantlibWrapper=0; - -// This is an example of an exported function. -QUANTLIBWRAPPER_API int fnQuantlibWrapper(void) -{ - return 42; -} - -// This is the constructor of a class that has been exported. -// see QuantlibWrapper.h for the class definition -CQuantlibWrapper::CQuantlibWrapper() -{ - return; -} diff --git a/CSharp/cpp/QuantlibWrapper.h b/CSharp/cpp/QuantlibWrapper.h deleted file mode 100644 index 8e217e1d63..0000000000 --- a/CSharp/cpp/QuantlibWrapper.h +++ /dev/null @@ -1,22 +0,0 @@ -// The following ifdef block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the QUANTLIBWRAPPER_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// QUANTLIBWRAPPER_API functions as being imported from a DLL, whereas this DLL sees symbols -// defined with this macro as being exported. -#ifdef QUANTLIBWRAPPER_EXPORTS -#define QUANTLIBWRAPPER_API __declspec(dllexport) -#else -#define QUANTLIBWRAPPER_API __declspec(dllimport) -#endif - -// This class is exported from the QuantlibWrapper.dll -class QUANTLIBWRAPPER_API CQuantlibWrapper { -public: - CQuantlibWrapper(void); - // TODO: add your methods here. -}; - -extern QUANTLIBWRAPPER_API int nQuantlibWrapper; - -QUANTLIBWRAPPER_API int fnQuantlibWrapper(void); diff --git a/CSharp/cpp/stdafx.h b/CSharp/cpp/stdafx.h deleted file mode 100644 index f45cbcda25..0000000000 --- a/CSharp/cpp/stdafx.h +++ /dev/null @@ -1,13 +0,0 @@ -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// - -#pragma once - - -#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers -// Windows Header Files: -#include - -// TODO: reference additional headers your program requires here From 29bf451f17bfa6b193e577570fd89fc000c12390 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Thu, 10 Mar 2022 15:40:16 +0100 Subject: [PATCH 005/322] Use .Net for C# compilation on Linux/macOS --- .gitignore | 1 + CSharp/Makefile.am | 42 +++-- CSharp/csharp/NQuantLib.csproj | 136 ++-------------- CSharp/examples/BermudanSwaption.csproj | 151 +++--------------- CSharp/examples/EquityOption.csproj | 151 +++--------------- .../examples/FiniteDifferenceMethods.csproj | 151 +++--------------- CSharp/examples/Times.csproj | 151 +++--------------- configure.ac | 13 +- 8 files changed, 134 insertions(+), 662 deletions(-) diff --git a/.gitignore b/.gitignore index 873b34c740..145e5e0a64 100644 --- a/.gitignore +++ b/.gitignore @@ -58,6 +58,7 @@ testCaseCollection.xml *.lo *.o *.so +*.dylib .build-stamp *.pyc *.exe diff --git a/CSharp/Makefile.am b/CSharp/Makefile.am index 83ac7b7561..853a505d6f 100644 --- a/CSharp/Makefile.am +++ b/CSharp/Makefile.am @@ -1,39 +1,35 @@ -CLEANFILES = cpp/quantlib_wrap.* csharp/*.cs *.so *.dll \ - examples/*.so examples/*.dll examples/*.exe +CLEANFILES = cpp/quantlib_wrap.* cpp/*.so cpp/*.dylib csharp/*.cs *.dll BUILT_SOURCES = cpp/quantlib_wrap.cpp cpp/quantlib_wrap.h -if HAVE_MCS -if BUILD_MCS +if HAVE_DOTNET +if BUILD_DOTNET -all-local: libNQuantLibc.so NQuantLib.dll +all-local: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuantLib.dll -libNQuantLibc.so: cpp/quantlib_wrap.o - $(CXX) -shared cpp/quantlib_wrap.o -o libNQuantLibc.so `quantlib-config --libs` +cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@: cpp/quantlib_wrap.o + $(CXX) -shared cpp/quantlib_wrap.o -o cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ `quantlib-config --libs` cpp/quantlib_wrap.o: $(BUILT_SOURCES) $(CXX) -c -fpic $(CXXFLAGS) cpp/quantlib_wrap.cpp -o cpp/quantlib_wrap.o `quantlib-config --cflags` -NQuantLib.dll: $(BUILT_SOURCES) - $(MCS) -nologo -target:library -out:NQuantLib.dll csharp/*.cs +csharp/bin/Release/net5.0/NQuantLib.dll: $(BUILT_SOURCES) + $(DOTNET) build --nologo -c Release -p:Version=$(PACKAGE_VERSION) csharp/NQuantLib.csproj -check-local: examples/BermudanSwaption.exe \ - examples/EquityOption.exe \ - examples/Times.exe \ - examples/libNQuantLibc.so examples/NQuantLib.dll - $(MONO) ./examples/BermudanSwaption.exe - $(MONO) ./examples/EquityOption.exe - $(MONO) ./examples/Times.exe +nupkg: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuantLib.dll + $(DOTNET) pack --no-build -c Release -p:PackageVersion=$(PACKAGE_VERSION) --include-symbols --include-source csharp/NQuantLib.csproj -examples/%.exe: examples/%.cs - $(MCS) -nologo -target:exe -out:$@ -reference:NQuantLib.dll $< +check-local: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuantLib.dll + ln -f cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ examples/ + cd examples && $(DOTNET) run -c Release --project BermudanSwaption.csproj + cd examples && $(DOTNET) run -c Release --project EquityOption.csproj + cd examples && $(DOTNET) run -c Release --project FiniteDifferenceMethods.csproj + cd examples && $(DOTNET) run -c Release --project Times.csproj + rm -f examples/libNQuantLibc.@SHARED_LIB_EXTENSION@ -examples/libNQuantLibc.so: libNQuantLibc.so - cd examples && ln -sf ../libNQuantLibc.so - -examples/NQuantLib.dll: NQuantLib.dll - cd examples && ln -sf ../NQuantLib.dll +clean-local: + rm -rf csharp/bin csharp/obj examples/*/bin examples/*/obj endif endif diff --git a/CSharp/csharp/NQuantLib.csproj b/CSharp/csharp/NQuantLib.csproj index dbfcbf1fba..a29d9f6a4c 100644 --- a/CSharp/csharp/NQuantLib.csproj +++ b/CSharp/csharp/NQuantLib.csproj @@ -1,130 +1,16 @@ - - - + - Local - 9.0.30729 - 2.0 - {928F98EE-7D50-457F-9304-A6818DCF1079} - Debug - AnyCPU - - - - - NQuantLib - - - JScript - Grid - IE50 - false - Library - QuantLib - OnBuildSuccess - - - - - - - 3.5 - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - + net5.0 + QuantLib - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x86 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x86 - prompt - AllRules.ruleset - - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x64 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x64 - prompt - AllRules.ruleset - - - - System - - - System.Data - - - System.XML - - - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - + + runtimes/osx-x64/native + + + runtimes/osx-x64/native + - - - - - - - diff --git a/CSharp/examples/BermudanSwaption.csproj b/CSharp/examples/BermudanSwaption.csproj index e5be3d3392..9dee91c920 100644 --- a/CSharp/examples/BermudanSwaption.csproj +++ b/CSharp/examples/BermudanSwaption.csproj @@ -1,137 +1,34 @@ - - - + + + + - Local - 9.0.21022 - 2.0 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9} - Debug - AnyCPU - - - - - BermudanSwaption - - - JScript - Grid - IE50 - false - Exe - BermudanSwaption - OnBuildSuccess - - - - - - - 3.5 - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x86 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x86 - prompt - AllRules.ruleset + obj\$(MSBuildProjectName) - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x64 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x64 - prompt - AllRules.ruleset + + + + + net5.0 + bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) + false + Exe + false + + + - - System - - - System.Data - - - System.XML - - - + Code + + + - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - {928f98ee-7d50-457f-9304-a6818dcf1079} - NQuantLib - + - - - copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(TargetDir)" - - - - \ No newline at end of file + + diff --git a/CSharp/examples/EquityOption.csproj b/CSharp/examples/EquityOption.csproj index 0071984049..b24b61c77a 100644 --- a/CSharp/examples/EquityOption.csproj +++ b/CSharp/examples/EquityOption.csproj @@ -1,137 +1,34 @@ - - - + + + + - Local - 9.0.21022 - 2.0 - {1FD947F1-D99E-46FB-8890-04E11E8340C2} - Debug - AnyCPU - - - - - EquityOption - - - JScript - Grid - IE50 - false - Exe - EquityOption - OnBuildSuccess - - - - - - - 3.5 - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x86 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x86 - prompt - AllRules.ruleset + obj\$(MSBuildProjectName) - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x64 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x64 - prompt - AllRules.ruleset + + + + + net5.0 + bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) + false + Exe + false + + + - - System - - - System.Data - - - System.XML - - - + Code + + + - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - {928f98ee-7d50-457f-9304-a6818dcf1079} - NQuantLib - + - - - copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(TargetDir)" - - - - \ No newline at end of file + + diff --git a/CSharp/examples/FiniteDifferenceMethods.csproj b/CSharp/examples/FiniteDifferenceMethods.csproj index b0c52451cd..a3989e427f 100755 --- a/CSharp/examples/FiniteDifferenceMethods.csproj +++ b/CSharp/examples/FiniteDifferenceMethods.csproj @@ -1,137 +1,34 @@ - - - + + + + - Local - 9.0.21022 - 2.0 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD} - Debug - AnyCPU - - - - - FiniteDifferenceMethods - - - JScript - Grid - IE50 - false - Exe - FiniteDifferenceMethods - OnBuildSuccess - - - - - - - 3.5 - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x86 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x86 - prompt - AllRules.ruleset + obj\$(MSBuildProjectName) - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x64 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x64 - prompt - AllRules.ruleset + + + + + net5.0 + bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) + false + Exe + false + + + - - System - - - System.Data - - - System.XML - - - + Code + + + - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - {928f98ee-7d50-457f-9304-a6818dcf1079} - NQuantLib - + - - - copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(TargetDir)" - - - - \ No newline at end of file + + diff --git a/CSharp/examples/Times.csproj b/CSharp/examples/Times.csproj index 6b83ca300a..c157098053 100644 --- a/CSharp/examples/Times.csproj +++ b/CSharp/examples/Times.csproj @@ -1,137 +1,34 @@ - - - + + + + - Local - 9.0.21022 - 2.0 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD} - Debug - AnyCPU - - - - - Times - - - JScript - Grid - IE50 - false - Exe - TimesTest - OnBuildSuccess - - - - - - - 3.5 - v4.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x86 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x86 - prompt - AllRules.ruleset + obj\$(MSBuildProjectName) - - true - bin\$(Platform)\$(Configuration)\ - DEBUG;TRACE - 285212672 - 4096 - full - x64 - prompt - AllRules.ruleset - - - bin\$(Platform)\$(Configuration)\ - TRACE - 285212672 - true - 4096 - x64 - prompt - AllRules.ruleset + + + + + net5.0 + bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) + false + Exe + false + + + - - System - - - System.Data - - - System.XML - - - + Code + + + - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - - {928f98ee-7d50-457f-9304-a6818dcf1079} - NQuantLib - + - - - copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(TargetDir)" - - - - \ No newline at end of file + + diff --git a/configure.ac b/configure.ac index 99e3306a0a..b90f223bf4 100644 --- a/configure.ac +++ b/configure.ac @@ -57,16 +57,15 @@ AC_ARG_ENABLE([python], [build_python=yes]) AM_CONDITIONAL(BUILD_PYTHON, test "$build_python" != "no") -AC_PATH_PROGS([MCS], [gmcs mcs gmcs2]) -AC_PATH_PROGS([MONO], [mono]) -AM_CONDITIONAL(HAVE_MCS, test "x${MCS}" != "x" && test "x${MONO}" != "x") +AC_PATH_PROGS([DOTNET], [dotnet]) +AM_CONDITIONAL(HAVE_DOTNET, test "x${DOTNET}" != "x") AC_ARG_ENABLE([csharp], AS_HELP_STRING([--disable-csharp], [If disabled, the C# module will not be built]), - [build_mcs=$enableval], - [build_mcs=yes]) -AM_CONDITIONAL(BUILD_MCS, test "$build_mcs" != "no") + [build_dotnet=$enableval], + [build_dotnet=yes]) +AM_CONDITIONAL(BUILD_DOTNET, test "$build_dotnet" != "no") AC_PATH_PROG([R], [R]) AM_CONDITIONAL(HAVE_R, test "x${R}" != "x") @@ -149,9 +148,11 @@ AM_CONDITIONAL(BUILD_SCALA, test "$build_scala" != "no") case "$target" in Darwin) AC_SUBST([SHARED_LIB],[${SHARED_LIB='-dynamiclib'}]) + AC_SUBST([SHARED_LIB_EXTENSION],[${SHARED_LIB_EXTENSION='dylib'}]) AC_SUBST([JNILIB_EXTENSION],[${JNILIB_EXTENSION='jnilib'}]) ;; *) AC_SUBST([SHARED_LIB],[${SHARED_LIB='-shared'}]) + AC_SUBST([SHARED_LIB_EXTENSION],[${SHARED_LIB_EXTENSION='so'}]) AC_SUBST([JNILIB_EXTENSION],[${JNILIB_EXTENSION='so'}]) ;; esac From f2a1c99beffaedf833d4cd8b85d8eabaeab5f2d4 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Thu, 10 Mar 2022 17:01:25 +0100 Subject: [PATCH 006/322] Try out dotnet build on Linux --- .build/dotnet.build | 6 ++++++ .github/workflows/linux.yml | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100755 .build/dotnet.build diff --git a/.build/dotnet.build b/.build/dotnet.build new file mode 100755 index 0000000000..9d6208d082 --- /dev/null +++ b/.build/dotnet.build @@ -0,0 +1,6 @@ +#!/bin/bash + +./autogen.sh \ +&& ./configure CC=clang CXX=clang++ CXXFLAGS='-O2' \ +&& make -C CSharp \ +&& make -C CSharp check diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 8c445d2ac7..74d5453054 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -6,7 +6,7 @@ jobs: strategy: fail-fast: false matrix: - language: [python3, java, csharp, r, scala] + language: [python3, java, dotnet, r, scala] container: ghcr.io/lballabio/quantlib-swig-devenv:${{ matrix.language }} steps: - uses: actions/checkout@v3 From 42a2e4cf2490df4bced20fc7339c668b52417f38 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Fri, 11 Mar 2022 12:39:04 +0100 Subject: [PATCH 007/322] Make sure examples find locally-compiled dynamic library --- CSharp/Makefile.am | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CSharp/Makefile.am b/CSharp/Makefile.am index 853a505d6f..334c1ba0b8 100644 --- a/CSharp/Makefile.am +++ b/CSharp/Makefile.am @@ -22,10 +22,10 @@ nupkg: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuant check-local: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuantLib.dll ln -f cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ examples/ - cd examples && $(DOTNET) run -c Release --project BermudanSwaption.csproj - cd examples && $(DOTNET) run -c Release --project EquityOption.csproj - cd examples && $(DOTNET) run -c Release --project FiniteDifferenceMethods.csproj - cd examples && $(DOTNET) run -c Release --project Times.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project BermudanSwaption.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project EquityOption.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project FiniteDifferenceMethods.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project Times.csproj rm -f examples/libNQuantLibc.@SHARED_LIB_EXTENSION@ clean-local: From 4d8a06fd70d32c8282d648dd1c83c2987f5afcb5 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Fri, 11 Mar 2022 16:18:36 +0100 Subject: [PATCH 008/322] Unset executable bit --- CSharp/examples/FiniteDifferenceMethods.csproj | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 CSharp/examples/FiniteDifferenceMethods.csproj diff --git a/CSharp/examples/FiniteDifferenceMethods.csproj b/CSharp/examples/FiniteDifferenceMethods.csproj old mode 100755 new mode 100644 From 72dc7a95ad0c1389e336b36f2db7b6bf3a80baf0 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Fri, 11 Mar 2022 18:26:40 +0100 Subject: [PATCH 009/322] Move C# examples to own folder to avoid workarounds --- .gitignore | 4 +- CSharp/Makefile.am | 22 +++-- CSharp/QuantLib.sln | 90 +++++++++---------- CSharp/cpp/QuantLibWrapper.vcxproj | 12 +++ CSharp/csharp/NQuantLib.csproj | 8 +- CSharp/examples/BermudanSwaption.csproj | 34 ------- .../BermudanSwaption.cs | 0 .../BermudanSwaption/BermudanSwaption.csproj | 17 ++++ CSharp/examples/EquityOption.csproj | 34 ------- .../{ => EquityOption}/EquityOption.cs | 0 .../examples/EquityOption/EquityOption.csproj | 17 ++++ .../examples/FiniteDifferenceMethods.csproj | 34 ------- .../FiniteDifferenceMethods.cs | 0 .../FiniteDifferenceMethods.csproj | 17 ++++ CSharp/examples/Times.csproj | 34 ------- CSharp/examples/{ => Times}/Times.cs | 0 CSharp/examples/Times/Times.csproj | 17 ++++ 17 files changed, 149 insertions(+), 191 deletions(-) delete mode 100644 CSharp/examples/BermudanSwaption.csproj rename CSharp/examples/{ => BermudanSwaption}/BermudanSwaption.cs (100%) create mode 100644 CSharp/examples/BermudanSwaption/BermudanSwaption.csproj delete mode 100644 CSharp/examples/EquityOption.csproj rename CSharp/examples/{ => EquityOption}/EquityOption.cs (100%) create mode 100644 CSharp/examples/EquityOption/EquityOption.csproj delete mode 100644 CSharp/examples/FiniteDifferenceMethods.csproj rename CSharp/examples/{ => FiniteDifferenceMethods}/FiniteDifferenceMethods.cs (100%) create mode 100644 CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj delete mode 100644 CSharp/examples/Times.csproj rename CSharp/examples/{ => Times}/Times.cs (100%) create mode 100644 CSharp/examples/Times/Times.csproj diff --git a/.gitignore b/.gitignore index 145e5e0a64..9d2ed14b94 100644 --- a/.gitignore +++ b/.gitignore @@ -9,8 +9,8 @@ CSharp/cpp/quantlib_wrap.cpp CSharp/cpp/quantlib_wrap.h CSharp/cpp/build CSharp/csharp/obj -CSharp/examples/bin -CSharp/examples/obj +CSharp/examples/*/bin +CSharp/examples/*/obj CSharp/.vs/ Java/bin/ Java/quantlib_wrap.cpp diff --git a/CSharp/Makefile.am b/CSharp/Makefile.am index 334c1ba0b8..e6e17ec594 100644 --- a/CSharp/Makefile.am +++ b/CSharp/Makefile.am @@ -22,10 +22,10 @@ nupkg: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuant check-local: cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ csharp/bin/Release/net5.0/NQuantLib.dll ln -f cpp/libNQuantLibc.@SHARED_LIB_EXTENSION@ examples/ - cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project BermudanSwaption.csproj - cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project EquityOption.csproj - cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project FiniteDifferenceMethods.csproj - cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project Times.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project BermudanSwaption/BermudanSwaption.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project EquityOption/EquityOption.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project FiniteDifferenceMethods/FiniteDifferenceMethods.csproj + cd examples && LD_LIBRARY_PATH=. $(DOTNET) run -c Release --project Times/Times.csproj rm -f examples/libNQuantLibc.@SHARED_LIB_EXTENSION@ clean-local: @@ -47,8 +47,18 @@ dist-hook: $(BUILT_SOURCES) cp ./csharp/*.csproj $(distdir)/csharp cp ./csharp/*.cs $(distdir)/csharp mkdir -p $(distdir)/examples - cp ./examples/*.csproj $(distdir)/examples - cp ./examples/*.cs $(distdir)/examples + mkdir -p $(distdir)/examples/BermudanSwaption + cp ./examples/BermudanSwaption/BermudanSwaption.csproj $(distdir)/examples/BermudanSwaption + cp ./examples/BermudanSwaption/BermudanSwaption.cs $(distdir)/examples/BermudanSwaption + mkdir -p $(distdir)/examples/EquityOption + cp ./examples/EquityOption/EquityOption.csproj $(distdir)/examples/EquityOption + cp ./examples/EquityOption/EquityOption.cs $(distdir)/examples/EquityOption + mkdir -p $(distdir)/examples/FiniteDifferenceMethods + cp ./examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj $(distdir)/examples/FiniteDifferenceMethods + cp ./examples/FiniteDifferenceMethods/FiniteDifferenceMethods.cs $(distdir)/examples/FiniteDifferenceMethods + mkdir -p $(distdir)/examples/Times + cp ./examples/Times/Times.csproj $(distdir)/examples/Times + cp ./examples/Times/Times.cs $(distdir)/examples/Times EXTRA_DIST = \ QuantLib.sln \ diff --git a/CSharp/QuantLib.sln b/CSharp/QuantLib.sln index 734f45bbd2..e97a489e6e 100644 --- a/CSharp/QuantLib.sln +++ b/CSharp/QuantLib.sln @@ -2,29 +2,29 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.31515.178 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BermudanSwaption", "examples\BermudanSwaption.csproj", "{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BermudanSwaption", "examples\BermudanSwaption\BermudanSwaption.csproj", "{1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}" ProjectSection(ProjectDependencies) = postProject {21183104-9963-4D4F-B7E8-C8A6169FD053} = {21183104-9963-4D4F-B7E8-C8A6169FD053} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EquityOption", "examples\EquityOption.csproj", "{1FD947F1-D99E-46FB-8890-04E11E8340C2}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EquityOption", "examples\EquityOption\EquityOption.csproj", "{1FD947F1-D99E-46FB-8890-04E11E8340C2}" ProjectSection(ProjectDependencies) = postProject {21183104-9963-4D4F-B7E8-C8A6169FD053} = {21183104-9963-4D4F-B7E8-C8A6169FD053} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FiniteDifferenceMethods", "examples\FiniteDifferenceMethods.csproj", "{EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FiniteDifferenceMethods", "examples\FiniteDifferenceMethods\FiniteDifferenceMethods.csproj", "{EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}" ProjectSection(ProjectDependencies) = postProject {21183104-9963-4D4F-B7E8-C8A6169FD053} = {21183104-9963-4D4F-B7E8-C8A6169FD053} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NQuantLib", "csharp\NQuantLib.csproj", "{928F98EE-7D50-457F-9304-A6818DCF1079}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NQuantLib", "csharp\NQuantLib.csproj", "{928F98EE-7D50-457F-9304-A6818DCF1079}" ProjectSection(ProjectDependencies) = postProject {21183104-9963-4D4F-B7E8-C8A6169FD053} = {21183104-9963-4D4F-B7E8-C8A6169FD053} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "NQuantLibc", "cpp\QuantLibWrapper.vcxproj", "{21183104-9963-4D4F-B7E8-C8A6169FD053}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Times", "examples\Times.csproj", "{C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Times", "examples\Times\Times.csproj", "{C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -34,38 +34,38 @@ Global Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Win32.ActiveCfg = Debug|Win32 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Win32.Build.0 = Debug|Win32 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|x64.ActiveCfg = Debug|x64 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|x64.Build.0 = Debug|x64 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Win32.ActiveCfg = Release|Win32 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Win32.Build.0 = Release|Win32 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|x64.ActiveCfg = Release|x64 - {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|x64.Build.0 = Release|x64 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Win32.ActiveCfg = Debug|Win32 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Win32.Build.0 = Debug|Win32 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|x64.ActiveCfg = Debug|x64 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|x64.Build.0 = Debug|x64 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Win32.ActiveCfg = Release|Win32 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Win32.Build.0 = Release|Win32 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|x64.ActiveCfg = Release|x64 - {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|x64.Build.0 = Release|x64 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|Win32.ActiveCfg = Debug|Win32 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|Win32.Build.0 = Debug|Win32 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|x64.ActiveCfg = Debug|x64 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|x64.Build.0 = Debug|x64 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|Win32.ActiveCfg = Release|Win32 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|Win32.Build.0 = Release|Win32 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|x64.ActiveCfg = Release|x64 - {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|x64.Build.0 = Release|x64 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Win32.ActiveCfg = Debug|Win32 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Win32.Build.0 = Debug|Win32 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|x64.ActiveCfg = Debug|x64 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|x64.Build.0 = Debug|x64 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Win32.ActiveCfg = Release|Win32 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Win32.Build.0 = Release|Win32 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|x64.ActiveCfg = Release|x64 - {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|x64.Build.0 = Release|x64 + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Win32.ActiveCfg = Debug|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|Win32.Build.0 = Debug|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|x64.ActiveCfg = Debug|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Debug|x64.Build.0 = Debug|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Win32.ActiveCfg = Release|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|Win32.Build.0 = Release|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|x64.ActiveCfg = Release|Any CPU + {1BEC49E8-122D-4CC9-9DAC-DD59F551E5E9}.Release|x64.Build.0 = Release|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Win32.ActiveCfg = Debug|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|Win32.Build.0 = Debug|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|x64.ActiveCfg = Debug|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Debug|x64.Build.0 = Debug|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Win32.ActiveCfg = Release|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|Win32.Build.0 = Release|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|x64.ActiveCfg = Release|Any CPU + {1FD947F1-D99E-46FB-8890-04E11E8340C2}.Release|x64.Build.0 = Release|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|Win32.ActiveCfg = Debug|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|Win32.Build.0 = Debug|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|x64.ActiveCfg = Debug|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Debug|x64.Build.0 = Debug|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|Win32.ActiveCfg = Release|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|Win32.Build.0 = Release|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|x64.ActiveCfg = Release|Any CPU + {EF2AFADF-B632-4E95-BEB5-7B7109A9E4FD}.Release|x64.Build.0 = Release|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Win32.ActiveCfg = Debug|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|Win32.Build.0 = Debug|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|x64.ActiveCfg = Debug|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Debug|x64.Build.0 = Debug|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Win32.ActiveCfg = Release|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|Win32.Build.0 = Release|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|x64.ActiveCfg = Release|Any CPU + {928F98EE-7D50-457F-9304-A6818DCF1079}.Release|x64.Build.0 = Release|Any CPU {21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|Win32.ActiveCfg = Debug|Win32 {21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|Win32.Build.0 = Debug|Win32 {21183104-9963-4D4F-B7E8-C8A6169FD053}.Debug|x64.ActiveCfg = Debug|x64 @@ -74,14 +74,14 @@ Global {21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|Win32.Build.0 = Release|Win32 {21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|x64.ActiveCfg = Release|x64 {21183104-9963-4D4F-B7E8-C8A6169FD053}.Release|x64.Build.0 = Release|x64 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|Win32.ActiveCfg = Debug|Win32 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|Win32.Build.0 = Debug|Win32 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|x64.ActiveCfg = Debug|x64 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|x64.Build.0 = Debug|x64 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|Win32.ActiveCfg = Release|Win32 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|Win32.Build.0 = Release|Win32 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|x64.ActiveCfg = Release|x64 - {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|x64.Build.0 = Release|x64 + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|Win32.ActiveCfg = Debug|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|Win32.Build.0 = Debug|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|x64.ActiveCfg = Debug|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Debug|x64.Build.0 = Debug|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|Win32.ActiveCfg = Release|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|Win32.Build.0 = Release|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|x64.ActiveCfg = Release|Any CPU + {C93F5204-5BC9-4AB3-AC06-C2CCE166CEBD}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CSharp/cpp/QuantLibWrapper.vcxproj b/CSharp/cpp/QuantLibWrapper.vcxproj index 33992277bb..3bb58f16a5 100644 --- a/CSharp/cpp/QuantLibWrapper.vcxproj +++ b/CSharp/cpp/QuantLibWrapper.vcxproj @@ -100,6 +100,9 @@ $(OutDir)NQuantLibc.lib MachineX86 + + copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(SolutionDir)cpp" + @@ -126,6 +129,9 @@ $(OutDir)NQuantLibc.lib + + copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(SolutionDir)cpp" + @@ -154,6 +160,9 @@ $(OutDir)NQuantLibc.lib MachineX86 + + copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(SolutionDir)cpp" + @@ -181,6 +190,9 @@ $(OutDir)NQuantLibc.lib + + copy "$(SolutionDir)cpp\bin\$(Platform)\$(Configuration)\NQuantLibc.dll" "$(SolutionDir)cpp" + diff --git a/CSharp/csharp/NQuantLib.csproj b/CSharp/csharp/NQuantLib.csproj index a29d9f6a4c..c1fb5859d3 100644 --- a/CSharp/csharp/NQuantLib.csproj +++ b/CSharp/csharp/NQuantLib.csproj @@ -4,9 +4,13 @@ QuantLib - - runtimes/osx-x64/native + runtimes/win-x64/native + + + runtimes/linux-x64/native diff --git a/CSharp/examples/BermudanSwaption.csproj b/CSharp/examples/BermudanSwaption.csproj deleted file mode 100644 index 9dee91c920..0000000000 --- a/CSharp/examples/BermudanSwaption.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - obj\$(MSBuildProjectName) - - - - - - net5.0 - bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) - false - Exe - false - - - - - - - - Code - - - - - - - - - - diff --git a/CSharp/examples/BermudanSwaption.cs b/CSharp/examples/BermudanSwaption/BermudanSwaption.cs similarity index 100% rename from CSharp/examples/BermudanSwaption.cs rename to CSharp/examples/BermudanSwaption/BermudanSwaption.cs diff --git a/CSharp/examples/BermudanSwaption/BermudanSwaption.csproj b/CSharp/examples/BermudanSwaption/BermudanSwaption.csproj new file mode 100644 index 0000000000..0456a98419 --- /dev/null +++ b/CSharp/examples/BermudanSwaption/BermudanSwaption.csproj @@ -0,0 +1,17 @@ + + + + net5.0 + false + Exe + + + + + + + + + + + diff --git a/CSharp/examples/EquityOption.csproj b/CSharp/examples/EquityOption.csproj deleted file mode 100644 index b24b61c77a..0000000000 --- a/CSharp/examples/EquityOption.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - obj\$(MSBuildProjectName) - - - - - - net5.0 - bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) - false - Exe - false - - - - - - - - Code - - - - - - - - - - diff --git a/CSharp/examples/EquityOption.cs b/CSharp/examples/EquityOption/EquityOption.cs similarity index 100% rename from CSharp/examples/EquityOption.cs rename to CSharp/examples/EquityOption/EquityOption.cs diff --git a/CSharp/examples/EquityOption/EquityOption.csproj b/CSharp/examples/EquityOption/EquityOption.csproj new file mode 100644 index 0000000000..0456a98419 --- /dev/null +++ b/CSharp/examples/EquityOption/EquityOption.csproj @@ -0,0 +1,17 @@ + + + + net5.0 + false + Exe + + + + + + + + + + + diff --git a/CSharp/examples/FiniteDifferenceMethods.csproj b/CSharp/examples/FiniteDifferenceMethods.csproj deleted file mode 100644 index a3989e427f..0000000000 --- a/CSharp/examples/FiniteDifferenceMethods.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - obj\$(MSBuildProjectName) - - - - - - net5.0 - bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) - false - Exe - false - - - - - - - - Code - - - - - - - - - - diff --git a/CSharp/examples/FiniteDifferenceMethods.cs b/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.cs similarity index 100% rename from CSharp/examples/FiniteDifferenceMethods.cs rename to CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.cs diff --git a/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj b/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj new file mode 100644 index 0000000000..0456a98419 --- /dev/null +++ b/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj @@ -0,0 +1,17 @@ + + + + net5.0 + false + Exe + + + + + + + + + + + diff --git a/CSharp/examples/Times.csproj b/CSharp/examples/Times.csproj deleted file mode 100644 index c157098053..0000000000 --- a/CSharp/examples/Times.csproj +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - obj\$(MSBuildProjectName) - - - - - - net5.0 - bin\$(Configuration)\$(TargetFramework)\$(MSBuildProjectName) - false - Exe - false - - - - - - - - Code - - - - - - - - - - diff --git a/CSharp/examples/Times.cs b/CSharp/examples/Times/Times.cs similarity index 100% rename from CSharp/examples/Times.cs rename to CSharp/examples/Times/Times.cs diff --git a/CSharp/examples/Times/Times.csproj b/CSharp/examples/Times/Times.csproj new file mode 100644 index 0000000000..0456a98419 --- /dev/null +++ b/CSharp/examples/Times/Times.csproj @@ -0,0 +1,17 @@ + + + + net5.0 + false + Exe + + + + + + + + + + + From c61bbe1cf42e657babcca9951c3fbad5ccfaf50c Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Fri, 11 Mar 2022 18:33:43 +0100 Subject: [PATCH 010/322] Fix condition --- CSharp/csharp/NQuantLib.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CSharp/csharp/NQuantLib.csproj b/CSharp/csharp/NQuantLib.csproj index c1fb5859d3..fe8d753fab 100644 --- a/CSharp/csharp/NQuantLib.csproj +++ b/CSharp/csharp/NQuantLib.csproj @@ -5,7 +5,7 @@ + Condition=" '$(OS)' == 'Windows_NT' "> runtimes/win-x64/native Date: Fri, 11 Mar 2022 22:31:59 +0100 Subject: [PATCH 011/322] Rename docker image for .Net CI build --- .build/dotnet.build | 6 ------ .github/workflows/linux.yml | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) delete mode 100755 .build/dotnet.build diff --git a/.build/dotnet.build b/.build/dotnet.build deleted file mode 100755 index 9d6208d082..0000000000 --- a/.build/dotnet.build +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -./autogen.sh \ -&& ./configure CC=clang CXX=clang++ CXXFLAGS='-O2' \ -&& make -C CSharp \ -&& make -C CSharp check diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 74d5453054..8c445d2ac7 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -6,7 +6,7 @@ jobs: strategy: fail-fast: false matrix: - language: [python3, java, dotnet, r, scala] + language: [python3, java, csharp, r, scala] container: ghcr.io/lballabio/quantlib-swig-devenv:${{ matrix.language }} steps: - uses: actions/checkout@v3 From 1329a07f5b7d4a11068648d3529b06938e66285d Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Fri, 11 Mar 2022 22:40:59 +0100 Subject: [PATCH 012/322] Use https links to QuantLib site --- Python/QuantLib-Python.spec.in | 2 +- Python/setup.py | 4 ++-- Python/setup.py.in | 4 ++-- R/DESCRIPTION | 2 +- R/DESCRIPTION.in | 2 +- README.md | 6 +++--- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Python/QuantLib-Python.spec.in b/Python/QuantLib-Python.spec.in index c5d3280dfe..192f7732a6 100644 --- a/Python/QuantLib-Python.spec.in +++ b/Python/QuantLib-Python.spec.in @@ -8,7 +8,7 @@ Group: System Environment/Libraries Packager: Liguo Song (Leo) Vendor: QuantLib.org Source0: http://prdownloads.sourceforge.net/quantlib/QuantLib-Python-%{version}.tar.gz -URL: http://quantlib.org/ +URL: https://www.quantlib.org/ Buildroot: %{_tmppath}/%{name}-%{version}-root BuildRequires: QuantLib-devel == %{version}, python >= 2.1 diff --git a/Python/setup.py b/Python/setup.py index 7a04f66f78..8f1015bd5f 100644 --- a/Python/setup.py +++ b/Python/setup.py @@ -215,13 +215,13 @@ def finalize_options(self): version = "1.26-dev", description = "Python bindings for the QuantLib library", long_description = """ -QuantLib (http://quantlib.org/) is a C++ library for financial quantitative +QuantLib (https://www.quantlib.org/) is a C++ library for financial quantitative analysts and developers, aimed at providing a comprehensive software framework for quantitative finance. """, author = "QuantLib Team", author_email = "quantlib-users@lists.sourceforge.net", - url = "http://quantlib.org", + url = "https://www.quantlib.org", license = "BSD 3-Clause", classifiers = classifiers, py_modules = ['QuantLib.__init__','QuantLib.QuantLib'], diff --git a/Python/setup.py.in b/Python/setup.py.in index 340fd0e2d7..d85352599b 100644 --- a/Python/setup.py.in +++ b/Python/setup.py.in @@ -215,13 +215,13 @@ setup(name = "QuantLib", version = "@PACKAGE_VERSION@", description = "Python bindings for the QuantLib library", long_description = """ -QuantLib (http://quantlib.org/) is a C++ library for financial quantitative +QuantLib (https://www.quantlib.org/) is a C++ library for financial quantitative analysts and developers, aimed at providing a comprehensive software framework for quantitative finance. """, author = "QuantLib Team", author_email = "quantlib-users@lists.sourceforge.net", - url = "http://quantlib.org", + url = "https://www.quantlib.org", license = "BSD 3-Clause", classifiers = classifiers, py_modules = ['QuantLib.__init__','QuantLib.QuantLib'], diff --git a/R/DESCRIPTION b/R/DESCRIPTION index cb5db8d541..9a7ee5a88b 100644 --- a/R/DESCRIPTION +++ b/R/DESCRIPTION @@ -8,4 +8,4 @@ Description: This package provides the SWIG-generated QuantLib bindings for R Depends: methods SystemRequirements: QuantLib library, Boost library License: QuantLib License -URL: http://quantlib.org +URL: https://www.quantlib.org diff --git a/R/DESCRIPTION.in b/R/DESCRIPTION.in index 9d0ac7489c..409967858a 100644 --- a/R/DESCRIPTION.in +++ b/R/DESCRIPTION.in @@ -8,4 +8,4 @@ Description: This package provides the SWIG-generated QuantLib bindings for R Depends: methods SystemRequirements: QuantLib library, Boost library License: QuantLib License -URL: http://quantlib.org +URL: https://www.quantlib.org diff --git a/README.md b/README.md index 82061370c9..e6694145a5 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ QuantLib-SWIG: language bindings for QuantLib QuantLib-SWIG provides the means to use QuantLib from a number of languages including Python, Ruby, Perl, C# and Java. -The QuantLib project () is aimed at providing a +The QuantLib project () is aimed at providing a comprehensive software framework for quantitative finance. QuantLib is a free/open-source library for modeling, trading, and risk management in real-life. @@ -26,7 +26,7 @@ Software. Download and usage ------------------ -QuantLib-SWIG can be downloaded from . +QuantLib-SWIG can be downloaded from . On Linux/Unix, you can run: @@ -56,7 +56,7 @@ patch available, you can open a pull request instead (see You can also use the `quantlib-users` and `quantlib-dev` mailing lists for feedback, questions, etc. More information and instructions for -subscribing are at . +subscribing are at . Contributing From 808d4386d2d4d9b8a1fc28edf20d1c36d2b5a1ba Mon Sep 17 00:00:00 2001 From: Marcin Rybacki Date: Mon, 21 Mar 2022 12:26:43 +0100 Subject: [PATCH 013/322] Exposed natural cubic spline interpolation. --- SWIG/discountcurve.i | 4 ++-- SWIG/interpolation.i | 15 ++++----------- SWIG/piecewiseyieldcurve.i | 2 ++ SWIG/zerocurve.i | 2 -- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/SWIG/discountcurve.i b/SWIG/discountcurve.i index 7e6f3503ea..9df7417cee 100644 --- a/SWIG/discountcurve.i +++ b/SWIG/discountcurve.i @@ -32,7 +32,7 @@ using QuantLib::InterpolatedDiscountCurve; %shared_ptr(InterpolatedDiscountCurve); %shared_ptr(InterpolatedDiscountCurve); %shared_ptr(InterpolatedDiscountCurve); -%shared_ptr(InterpolatedDiscountCurve); +%shared_ptr(InterpolatedDiscountCurve); template class InterpolatedDiscountCurve : public YieldTermStructure { @@ -55,6 +55,6 @@ class InterpolatedDiscountCurve : public YieldTermStructure { %template(MonotonicLogCubicDiscountCurve) InterpolatedDiscountCurve; %template(NaturalCubicDiscountCurve) InterpolatedDiscountCurve; %template(KrugerLogDiscountCurve) InterpolatedDiscountCurve; -%template(AkimaLogDiscountCurve) InterpolatedDiscountCurve; +%template(NaturalLogCubicDiscountCurve) InterpolatedDiscountCurve; #endif diff --git a/SWIG/interpolation.i b/SWIG/interpolation.i index 529cd88cc1..6a0fd666fd 100644 --- a/SWIG/interpolation.i +++ b/SWIG/interpolation.i @@ -177,12 +177,6 @@ class Kruger : public Cubic { : Cubic(QuantLib::CubicInterpolation::Kruger) {} }; -class Akima : public Cubic { - public: - Akima() - : Cubic(QuantLib::CubicInterpolation::Akima) {} -}; - class DefaultLogCubic : public QuantLib::LogCubic { public: DefaultLogCubic() @@ -205,10 +199,10 @@ class KrugerLog : public QuantLib::LogCubic { QuantLib::CubicInterpolation::SecondDerivative, 0.0) {} }; -class AkimaLog : public QuantLib::LogCubic { +class SplineLogCubic : public QuantLib::LogCubic { public: - AkimaLog() - : QuantLib::LogCubic(QuantLib::CubicInterpolation::Akima, false, + SplineLogCubic() + : QuantLib::LogCubic(QuantLib::CubicInterpolation::Spline, false, QuantLib::CubicInterpolation::SecondDerivative, 0.0, QuantLib::CubicInterpolation::SecondDerivative, 0.0) {} }; @@ -224,10 +218,9 @@ struct MonotonicCubic {}; struct DefaultLogCubic {}; struct MonotonicLogCubic {}; struct SplineCubic {}; +struct SplineLogCubic {}; struct Kruger {}; struct KrugerLog {}; -struct Akima {}; -struct AkimaLog {}; struct ConvexMonotone { ConvexMonotone(Real quadraticity = 0.3, Real monotonicity = 0.7, diff --git a/SWIG/piecewiseyieldcurve.i b/SWIG/piecewiseyieldcurve.i index c22ef763b8..79158da307 100644 --- a/SWIG/piecewiseyieldcurve.i +++ b/SWIG/piecewiseyieldcurve.i @@ -132,6 +132,8 @@ export_piecewise_curve(PiecewiseSplineCubicDiscount,Discount,SplineCubic); export_piecewise_curve(PiecewiseKrugerZero,ZeroYield,Kruger); export_piecewise_curve(PiecewiseKrugerLogDiscount,Discount,KrugerLog); export_piecewise_curve(PiecewiseConvexMonotoneZero,ZeroYield,ConvexMonotone); +export_piecewise_curve(PiecewiseNaturalCubicZero,ZeroYield,SplineCubic); +export_piecewise_curve(PiecewiseNaturalLogCubicDiscount,Discount,SplineLogCubic); // global boostrapper diff --git a/SWIG/zerocurve.i b/SWIG/zerocurve.i index 4e8342e21f..5ea246d077 100644 --- a/SWIG/zerocurve.i +++ b/SWIG/zerocurve.i @@ -34,7 +34,6 @@ using QuantLib::InterpolatedZeroCurve; %shared_ptr(InterpolatedZeroCurve); %shared_ptr(InterpolatedZeroCurve); %shared_ptr(InterpolatedZeroCurve); -%shared_ptr(InterpolatedZeroCurve); template class InterpolatedZeroCurve : public YieldTermStructure { @@ -62,7 +61,6 @@ class InterpolatedZeroCurve : public YieldTermStructure { %template(LogCubicZeroCurve) InterpolatedZeroCurve; %template(MonotonicCubicZeroCurve) InterpolatedZeroCurve; %template(KrugerZeroCurve) InterpolatedZeroCurve; -%template(AkimaZeroCurve) InterpolatedZeroCurve; #endif From e6f7cdce741447177711c157c1b19067d6e186bf Mon Sep 17 00:00:00 2001 From: Marcin Rybacki Date: Mon, 21 Mar 2022 12:46:17 +0100 Subject: [PATCH 014/322] Exposed BondForward class. --- SWIG/forward.i | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/SWIG/forward.i b/SWIG/forward.i index 071b23cd81..599831cee6 100644 --- a/SWIG/forward.i +++ b/SWIG/forward.i @@ -59,6 +59,7 @@ class Forward : public Instrument{ // FixedRateBondForward %{ using QuantLib::FixedRateBondForward; +using QuantLib::BondForward; using QuantLib::FixedRateBond; using QuantLib::BusinessDayConvention; using QuantLib::Position; @@ -88,4 +89,26 @@ class FixedRateBondForward : public Forward { }; +%shared_ptr(BondForward) +class BondForward : public Forward { + public: + BondForward( + const Date& valueDate, + const Date& maturityDate, + Position::Type type, + Real strike, + Natural settlementDays, + const DayCounter& dayCounter, + const Calendar& calendar, + BusinessDayConvention businessDayConvention, + const ext::shared_ptr& bond, + const Handle& discountCurve = + Handle(), + const Handle& incomeDiscountCurve = + Handle()); + + Real forwardPrice(); + Real cleanForwardPrice(); +}; + #endif From f8e46a6758036f1bc1fa71b7ccc1f298b906c30c Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 22 Mar 2022 10:19:58 +0100 Subject: [PATCH 015/322] Expose inheritance relation --- SWIG/forward.i | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/SWIG/forward.i b/SWIG/forward.i index 599831cee6..a47efbfdd5 100644 --- a/SWIG/forward.i +++ b/SWIG/forward.i @@ -58,18 +58,17 @@ class Forward : public Instrument{ // FixedRateBondForward %{ -using QuantLib::FixedRateBondForward; using QuantLib::BondForward; +using QuantLib::FixedRateBondForward; using QuantLib::FixedRateBond; using QuantLib::BusinessDayConvention; using QuantLib::Position; %} -%shared_ptr(FixedRateBondForward) -class FixedRateBondForward : public Forward { - public: - FixedRateBondForward( - const Date& valueDate, +%shared_ptr(BondForward) +class BondForward : public Forward { + public: + BondForward(const Date& valueDate, const Date& maturityDate, Position::Type type, Real strike, @@ -77,22 +76,20 @@ class FixedRateBondForward : public Forward { const DayCounter& dayCounter, const Calendar& calendar, BusinessDayConvention businessDayConvention, - const ext::shared_ptr& fixedBond, + const ext::shared_ptr& bond, const Handle& discountCurve = Handle(), const Handle& incomeDiscountCurve = Handle()); - Real forwardPrice(); - - Real cleanForwardPrice(); - + Real forwardPrice(); + Real cleanForwardPrice(); }; -%shared_ptr(BondForward) -class BondForward : public Forward { - public: - BondForward( +%shared_ptr(FixedRateBondForward) +class FixedRateBondForward : public BondForward { + public: + FixedRateBondForward( const Date& valueDate, const Date& maturityDate, Position::Type type, @@ -101,14 +98,11 @@ class BondForward : public Forward { const DayCounter& dayCounter, const Calendar& calendar, BusinessDayConvention businessDayConvention, - const ext::shared_ptr& bond, + const ext::shared_ptr& fixedBond, const Handle& discountCurve = Handle(), const Handle& incomeDiscountCurve = Handle()); - - Real forwardPrice(); - Real cleanForwardPrice(); }; #endif From 808f793402d4dfe380a2f28db8aaba77002b5b07 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 22 Mar 2022 10:20:37 +0100 Subject: [PATCH 016/322] Require newest QuantLib version --- SWIG/ql.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SWIG/ql.i b/SWIG/ql.i index 8bcce62db7..8cc2bf67bd 100644 --- a/SWIG/ql.i +++ b/SWIG/ql.i @@ -30,7 +30,7 @@ %{ #include -#if QL_HEX_VERSION < 0x01250000 +#if QL_HEX_VERSION < 0x01260000 #error using an old version of QuantLib, please update #endif From 428a690fad613dad5cf35f0547784186befaa200 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Wed, 23 Mar 2022 14:11:36 +0100 Subject: [PATCH 017/322] Use normalized period to generate hash --- CSharp/examples/Times/Times.cs | 3 --- SWIG/date.i | 5 +++-- SWIG/ql.i | 2 +- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/CSharp/examples/Times/Times.cs b/CSharp/examples/Times/Times.cs index eebfd773df..a8a42e07cf 100644 --- a/CSharp/examples/Times/Times.cs +++ b/CSharp/examples/Times/Times.cs @@ -197,9 +197,6 @@ private static void RunTestCases() #endregion - Console.WriteLine("test Period.ToString()"); - testCase(tenor01Y.ToString() == tenor12M.ToString()); - Console.WriteLine("test Period.GetHashCode()"); testCase(tenor01Y.GetHashCode() == tenor12M.GetHashCode()); diff --git a/SWIG/date.i b/SWIG/date.i index b14ae09640..0d9f39d505 100644 --- a/SWIG/date.i +++ b/SWIG/date.i @@ -183,7 +183,7 @@ enum Frequency { } public override int GetHashCode() { - return ToString().GetHashCode(); + return normalized().ToString().GetHashCode(); } public int CompareTo(object obj) { @@ -275,6 +275,7 @@ class Period { Integer length() const; TimeUnit units() const; Frequency frequency() const; + Period normalized() const; %extend { Period(const std::string& str) { return new Period(PeriodParser::parse(str)); @@ -340,7 +341,7 @@ class Period { #if defined(SWIGPYTHON) %pythoncode %{ def __hash__(self): - return hash(str(self)) + return hash(str(self.normalized())) %} #endif }; diff --git a/SWIG/ql.i b/SWIG/ql.i index 8bcce62db7..8cc2bf67bd 100644 --- a/SWIG/ql.i +++ b/SWIG/ql.i @@ -30,7 +30,7 @@ %{ #include -#if QL_HEX_VERSION < 0x01250000 +#if QL_HEX_VERSION < 0x01260000 #error using an old version of QuantLib, please update #endif From fb9b6041d3359f380d4cfeb0003f760749c5f3dc Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Mar 2022 18:00:57 +0000 Subject: [PATCH 018/322] Bump peter-evans/create-pull-request from 3 to 4 Bumps [peter-evans/create-pull-request](https://github.com/peter-evans/create-pull-request) from 3 to 4. - [Release notes](https://github.com/peter-evans/create-pull-request/releases) - [Commits](https://github.com/peter-evans/create-pull-request/compare/v3...v4) --- updated-dependencies: - dependency-name: peter-evans/create-pull-request dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/copyrights.yml | 2 +- .github/workflows/misspell.yml | 2 +- .github/workflows/namespaces.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/copyrights.yml b/.github/workflows/copyrights.yml index 865c342d2b..758d57d8a8 100644 --- a/.github/workflows/copyrights.yml +++ b/.github/workflows/copyrights.yml @@ -11,7 +11,7 @@ jobs: - name: Check run: | ./tools/check_copyrights.sh - - uses: peter-evans/create-pull-request@v3 + - uses: peter-evans/create-pull-request@v4 with: token: ${{ secrets.GITHUB_TOKEN }} branch: update-copyright-list-${{ github.ref }} diff --git a/.github/workflows/misspell.yml b/.github/workflows/misspell.yml index d0237ba080..8168bad0e2 100644 --- a/.github/workflows/misspell.yml +++ b/.github/workflows/misspell.yml @@ -9,7 +9,7 @@ jobs: steps: - uses: actions/checkout@v3 - uses: sobolevn/misspell-fixer-action@master - - uses: peter-evans/create-pull-request@v3 + - uses: peter-evans/create-pull-request@v4 with: token: ${{ secrets.GITHUB_TOKEN }} branch: misspell-fixes-${{ github.ref }} diff --git a/.github/workflows/namespaces.yml b/.github/workflows/namespaces.yml index fb56537344..60d0abe013 100644 --- a/.github/workflows/namespaces.yml +++ b/.github/workflows/namespaces.yml @@ -16,7 +16,7 @@ jobs: sed -i -e 's/boost::tuple/ext::tuple/g' SWIG/* sed -i -e 's/boost::get/ext::get/g' SWIG/* sed -i -e 's/boost::function/ext::function/g' SWIG/* - - uses: peter-evans/create-pull-request@v3 + - uses: peter-evans/create-pull-request@v4 with: token: ${{ secrets.GITHUB_TOKEN }} branch: fix-boost-namespace-${{ github.ref }} From 98fd7fc416bf02fffa9325fff0d4889c1b414c09 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Thu, 31 Mar 2022 15:53:17 +0200 Subject: [PATCH 019/322] Export SpreadFittingMethod class --- SWIG/fittedbondcurve.i | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/SWIG/fittedbondcurve.i b/SWIG/fittedbondcurve.i index 3920bbbbaf..8048137912 100644 --- a/SWIG/fittedbondcurve.i +++ b/SWIG/fittedbondcurve.i @@ -37,6 +37,7 @@ std::vector > convert_bond_helpers( } %} +%shared_ptr(FittingMethod) class FittingMethod { public: virtual ~FittingMethod() = 0; @@ -80,8 +81,10 @@ using QuantLib::NelsonSiegelFitting; using QuantLib::SvenssonFitting; using QuantLib::CubicBSplinesFitting; using QuantLib::SimplePolynomialFitting; +using QuantLib::SpreadFittingMethod; %} +%shared_ptr(ExponentialSplinesFitting) class ExponentialSplinesFitting : public FittingMethod { public: ExponentialSplinesFitting(bool constrainAtZero = true, @@ -93,16 +96,19 @@ class ExponentialSplinesFitting : public FittingMethod { Real fixedKappa = Null()); }; +%shared_ptr(NelsonSiegelFitting) class NelsonSiegelFitting : public FittingMethod { public: NelsonSiegelFitting(const Array& weights = Array()); }; +%shared_ptr(SvenssonFitting) class SvenssonFitting : public FittingMethod { public: SvenssonFitting(const Array& weights = Array()); }; +%shared_ptr(CubicBSplinesFitting) class CubicBSplinesFitting : public FittingMethod { public: CubicBSplinesFitting(const std::vector - + diff --git a/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj b/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj index a1c17596e1..7503700c35 100644 --- a/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj +++ b/CSharp/examples/FiniteDifferenceMethods/FiniteDifferenceMethods.csproj @@ -11,7 +11,7 @@ - + diff --git a/CSharp/examples/Times/Times.csproj b/CSharp/examples/Times/Times.csproj index a1c17596e1..7503700c35 100644 --- a/CSharp/examples/Times/Times.csproj +++ b/CSharp/examples/Times/Times.csproj @@ -11,7 +11,7 @@ - + From 7942858b27772ea9807e3b2310434ae3331692b2 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Mon, 17 Oct 2022 16:12:13 +0200 Subject: [PATCH 092/322] Update codec in setup.py --- Python/setup.py | 4 ++-- Python/setup.py.in | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/setup.py b/Python/setup.py index f30b36c522..3b1171a290 100644 --- a/Python/setup.py +++ b/Python/setup.py @@ -1,4 +1,4 @@ -# -*- coding: iso-8859-1 -*- +# -*- coding: utf-8 -*- """ Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 StatPro Italia srl @@ -30,7 +30,7 @@ class test(Command): # Original version of this class posted - # by Berthold Höllmann to distutils-sig@python.org + # by Berthold Höllmann to distutils-sig@python.org description = "test the distribution prior to install" user_options = [ diff --git a/Python/setup.py.in b/Python/setup.py.in index d85352599b..69c5d814dc 100644 --- a/Python/setup.py.in +++ b/Python/setup.py.in @@ -1,4 +1,4 @@ -# -*- coding: iso-8859-1 -*- +# -*- coding: utf-8 -*- """ Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 StatPro Italia srl @@ -30,7 +30,7 @@ from distutils.ccompiler import get_default_compiler class test(Command): # Original version of this class posted - # by Berthold Höllmann to distutils-sig@python.org + # by Berthold Höllmann to distutils-sig@python.org description = "test the distribution prior to install" user_options = [ From 62487d5f4a06a0cc9fd18ee93d920dcc09fe44e8 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 18 Oct 2022 18:40:04 +0200 Subject: [PATCH 093/322] Avoid date dependency on Python test --- Python/test/termstructures.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/test/termstructures.py b/Python/test/termstructures.py index 261b2525c0..84d6d7da43 100644 --- a/Python/test/termstructures.py +++ b/Python/test/termstructures.py @@ -310,9 +310,9 @@ def testLazyObject(self): self.termStructure.recalculate() - # Check that rates have changed - for i in range(len(self.termStructure.nodes())): - self.assertNotEqual(nodes[i][1], self.termStructure.nodes()[i][1]) + # Check that dates have changed (except the reference, which is fixed) + for i in range(1, len(self.termStructure.nodes())): + self.assertNotEqual(nodes[i][0], self.termStructure.nodes()[i][0]) ql.Settings.instance().evaluationDate = evaluationDate From 3b0c78f3bde02a3c1ebe502d00b3ba23b04d4572 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Mon, 12 Apr 2021 11:12:19 +0200 Subject: [PATCH 094/322] Set version to 1.28 final. --- Python/setup.py | 2 +- configure.ac | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Python/setup.py b/Python/setup.py index 3b1171a290..223d23b996 100644 --- a/Python/setup.py +++ b/Python/setup.py @@ -212,7 +212,7 @@ def finalize_options(self): ] setup(name = "QuantLib", - version = "1.28-rc", + version = "1.28", description = "Python bindings for the QuantLib library", long_description = """ QuantLib (https://www.quantlib.org/) is a C++ library for financial quantitative diff --git a/configure.ac b/configure.ac index 3035fb59d1..fabbb03935 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ # Process this file with autoconf to produce a configure script. -AC_INIT([QuantLib-SWIG], [1.28-rc], +AC_INIT([QuantLib-SWIG], [1.28], [quantlib-dev@lists.sourceforge.net], [QuantLib-SWIG]) AC_PREREQ(2.50) From e8e707a7176982afb9efb613d08eff63c7a5b696 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Thu, 20 Oct 2022 14:45:18 +0200 Subject: [PATCH 095/322] Update changelog --- ChangeLog.txt | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/ChangeLog.txt b/ChangeLog.txt index 173f6dfe04..9526f73454 100644 --- a/ChangeLog.txt +++ b/ChangeLog.txt @@ -1,3 +1,66 @@ +commit 3b0c78f3bde02a3c1ebe502d00b3ba23b04d4572 +Author: Luigi Ballabio +Date: Mon, 12 Apr 2021 11:12:19 +0200 + + Set version to 1.28 final. + + Python/setup.py | 2 +- + configure.ac | 2 +- + 2 files changed, 2 insertions(+), 2 deletions(-) + +commit 62487d5f4a06a0cc9fd18ee93d920dcc09fe44e8 +Author: Luigi Ballabio +Date: Tue, 18 Oct 2022 18:40:04 +0200 + + Avoid date dependency on Python test + + Python/test/termstructures.py | 6 +++--- + 1 file changed, 3 insertions(+), 3 deletions(-) + +commit 7942858b27772ea9807e3b2310434ae3331692b2 +Author: Luigi Ballabio +Date: Mon, 17 Oct 2022 16:12:13 +0200 + + Update codec in setup.py + + Python/setup.py | 4 ++-- + Python/setup.py.in | 4 ++-- + 2 files changed, 4 insertions(+), 4 deletions(-) + +commit a5956bd6d86af88b2b1f0988dcda22acca54cd52 +Author: Luigi Ballabio +Date: Thu, 13 Oct 2022 18:28:17 +0200 + + Update Visual Studio projects + + CSharp/QuantLib.props | 1 + + CSharp/cpp/QuantLibWrapper.vcxproj | 9 +++++---- + CSharp/examples/BermudanSwaption/BermudanSwaption.csproj | 2 +- + CSharp/examples/EquityOption/EquityOption.csproj | 2 +- + .../FiniteDifferenceMethods/FiniteDifferenceMethods.csproj | 2 +- + CSharp/examples/Times/Times.csproj | 2 +- + 6 files changed, 10 insertions(+), 8 deletions(-) + +commit c3012cb6e8d9fb337affc7bff91a701ac7ff2c8f +Author: Luigi Ballabio +Date: Thu, 14 Apr 2022 18:29:12 +0200 + + Set version to 1.28 rc + + Python/setup.py | 2 +- + configure.ac | 2 +- + 2 files changed, 2 insertions(+), 2 deletions(-) + +commit 677f6aa77533b95d6a062dffc8f84bc55b49dace +Author: Luigi Ballabio +Date: Mon, 10 Oct 2022 21:25:24 +0200 + + Update news and changelog + + ChangeLog.txt | 505 +++++++++++++++++++++++++++++----------------------------- + News.md | 56 ++++--- + 2 files changed, 283 insertions(+), 278 deletions(-) + commit 2a1de41f18370f1211af7005761c723f9f916eb5 Merge: d5e1f8c 2837a32 Author: Luigi Ballabio From 89c8fa00f23d34b44729789e3786851ef1b504f9 Mon Sep 17 00:00:00 2001 From: klausspanderen Date: Sat, 22 Oct 2022 20:02:46 +0200 Subject: [PATCH 096/322] removed redundant make function --- SWIG/options.i | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/SWIG/options.i b/SWIG/options.i index fe2ad022c2..c07659ed03 100644 --- a/SWIG/options.i +++ b/SWIG/options.i @@ -1004,29 +1004,15 @@ class QdPlusAmericanEngine: public PricingEngine { public: enum SolverType {Brent, Newton, Ridder, Halley, SuperHalley}; + #if !defined(SWIGJAVA) && !defined(SWIGCSHARP) + %feature("kwargs") QdPlusAmericanEngine; + #endif explicit QdPlusAmericanEngine( - ext::shared_ptr, + ext::shared_ptr process, Size interpolationPoints = 8, SolverType solverType = Halley, Real eps = 1e-6, - Size maxIter = Null()); - - #if !defined(SWIGJAVA) && !defined(SWIGCSHARP) - %feature("kwargs") make; - %extend { - static ext::shared_ptr make( - const ext::shared_ptr& process, - Size interpolationPoints = 8, - SolverType solverType = Halley, - Real eps = 1e-6, - Size maxIter = Null()) { - - return ext::shared_ptr( - new QdPlusAmericanEngine( - process, interpolationPoints, solverType, eps, maxIter)); - } - } - #endif + Size maxIter = Null()); }; %{ From 1e6587da9a227f298ae9eae0c3240bfd8a474579 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 18 Jan 2022 11:02:58 +0100 Subject: [PATCH 097/322] Set version to 1.29-dev. --- Python/setup.py | 2 +- R/DESCRIPTION | 2 +- configure.ac | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Python/setup.py b/Python/setup.py index 223d23b996..c8eff560f2 100644 --- a/Python/setup.py +++ b/Python/setup.py @@ -212,7 +212,7 @@ def finalize_options(self): ] setup(name = "QuantLib", - version = "1.28", + version = "1.29-dev", description = "Python bindings for the QuantLib library", long_description = """ QuantLib (https://www.quantlib.org/) is a C++ library for financial quantitative diff --git a/R/DESCRIPTION b/R/DESCRIPTION index 320aaf8b7c..fbb4ce67e6 100644 --- a/R/DESCRIPTION +++ b/R/DESCRIPTION @@ -1,6 +1,6 @@ Package: QuantLib Title: QuantLib bindings for R -Version: 1.28 +Version: 1.29 Date: $Date$ Maintainer: Dirk Eddelbuettel Author: The QuantLib Group diff --git a/configure.ac b/configure.ac index fabbb03935..4a154490f1 100644 --- a/configure.ac +++ b/configure.ac @@ -1,5 +1,5 @@ # Process this file with autoconf to produce a configure script. -AC_INIT([QuantLib-SWIG], [1.28], +AC_INIT([QuantLib-SWIG], [1.29-dev], [quantlib-dev@lists.sourceforge.net], [QuantLib-SWIG]) AC_PREREQ(2.50) From e505ae6820c6017370b6873b002d45e15fe8ae1c Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 25 Oct 2022 16:47:34 +0200 Subject: [PATCH 098/322] Avoid deprecated features removed in version 1.29 --- Python/test/bonds.py | 2 +- Python/test/daycounters.py | 2 +- Python/test/ratehelpers.py | 12 ++++++------ SWIG/calendars.i | 2 +- SWIG/inflation.i | 1 - SWIG/ql.i | 14 +++++++------- SWIG/ratehelpers.i | 21 --------------------- 7 files changed, 16 insertions(+), 38 deletions(-) diff --git a/Python/test/bonds.py b/Python/test/bonds.py index e6cd7545bb..e0f6e55c7b 100644 --- a/Python/test/bonds.py +++ b/Python/test/bonds.py @@ -249,7 +249,7 @@ def testFromDateInfo(self): faceAmount=self.face_amount, coupons=self.coupons, issueDate=self.issue_date, - couponCalendar=ql.UnitedStates(), + couponCalendar=ql.UnitedStates(ql.UnitedStates.GovernmentBond), startDate=ql.Date(2, 1, 2010), maturityDate=self.maturity_date, tenor=ql.Period(3, ql.Months), diff --git a/Python/test/daycounters.py b/Python/test/daycounters.py index 3a89d7bbaf..730c3130bf 100644 --- a/Python/test/daycounters.py +++ b/Python/test/daycounters.py @@ -6,7 +6,7 @@ class DayCountersTest(unittest.TestCase): def runTest(self): "Testing daycounters" - calendar = ql.UnitedStates() + calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) # # Check that SWIG signature for Business252 calendar allows to diff --git a/Python/test/ratehelpers.py b/Python/test/ratehelpers.py index 0694916220..618d2058ac 100644 --- a/Python/test/ratehelpers.py +++ b/Python/test/ratehelpers.py @@ -333,7 +333,7 @@ def build_pln_fx_swap_curve(self, base_ccy_yts, fx_swaps, fx_spot): calendar = ql.JointCalendar(ql.TARGET(), ql.Poland()) spot_date_lag = 2 - trading_calendar = ql.UnitedStates() + trading_calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) # build rate helpers @@ -441,7 +441,7 @@ def testFxMarketConventionsForCrossRate(self): spot_date = ql.Date(5, 7, 2016) self.build_curves(today) - us_calendar = ql.UnitedStates() + us_calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) joint_calendar = ql.JointCalendar(ql.TARGET(), ql.Poland()) @@ -477,7 +477,7 @@ def testFxMarketConventionsForCrossRateONPeriod(self): # dates base_ccy_yts = ql.RelinkableYieldTermStructureHandle() - us_calendar = ql.UnitedStates() + us_calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) joint_calendar = ql.JointCalendar(ql.TARGET(), ql.Poland()) @@ -506,7 +506,7 @@ def testFxMarketConventionsForCrossRateAdjustedSpotDate(self): today = ql.Date(30, 6, 2016) spot_date = ql.Date(5, 7, 2016) self.build_curves(today) - us_calendar = ql.UnitedStates() + us_calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) joint_calendar = ql.JointCalendar(ql.TARGET(), ql.Poland()) settlement_calendar = ql.JointCalendar(joint_calendar, us_calendar) @@ -545,7 +545,7 @@ def testFxMarketConventionsForDatesInEURUSD_ON_Period(self): # and one day in US, therefore it is sufficient to pass only Target # as a base calendar calendar = ql.TARGET() - trading_calendar = ql.UnitedStates() + trading_calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) on_rate_helper = ql.FxSwapRateHelper( ql.QuoteHandle(ql.SimpleQuote(fwd_points)), @@ -585,7 +585,7 @@ def testFxMarketConventionsForDatesInEURUSD_ShortEnd(self): # as a base calendar. Passing joint calendar would result in wrong # spot date of the trade calendar = ql.TARGET() - trading_calendar = ql.UnitedStates() + trading_calendar = ql.UnitedStates(ql.UnitedStates.GovernmentBond) rate_helper = ql.FxSwapRateHelper( ql.QuoteHandle(ql.SimpleQuote(fwd_points)), diff --git a/SWIG/calendars.i b/SWIG/calendars.i index bd62fa026a..12d739bf5c 100644 --- a/SWIG/calendars.i +++ b/SWIG/calendars.i @@ -294,7 +294,7 @@ namespace QuantLib { public: enum Market { Settlement, NYSE, GovernmentBond, NERC, LiborImpact, FederalReserve }; - UnitedStates(Market m = Settlement); + UnitedStates(Market m); }; // others diff --git a/SWIG/inflation.i b/SWIG/inflation.i index 7f2833009f..e62fb1f640 100644 --- a/SWIG/inflation.i +++ b/SWIG/inflation.i @@ -75,7 +75,6 @@ class InflationTermStructure : public TermStructure { virtual Frequency frequency() const; virtual bool indexIsInterpolated() const; virtual Rate baseRate() const; - virtual Handle nominalTermStructure() const; virtual Date baseDate() const; void setSeasonality(const ext::shared_ptr& seasonality = ext::shared_ptr()); diff --git a/SWIG/ql.i b/SWIG/ql.i index 2285a30839..1cedd93bfd 100644 --- a/SWIG/ql.i +++ b/SWIG/ql.i @@ -51,18 +51,18 @@ #pragma message(\ "Quantlib has not been compiled with the thread-safe " \ "observer pattern being enabled. This can lead to spurious " \ - "crashes or pure virtual function call within the JVM or .NET " \ + "crashes or pure virtual function calls within the JVM or .NET " \ "ecosystem due to the async garbage collector. Please consider " \ "enabling QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN " \ "in ql/userconfig.hpp.") #else #warning \ - Quantlib has not been compiled with the thread-safe \ - observer pattern being enabled. This can lead to spurious \ - crashes or pure virtual function call within the JVM or .NET \ - ecosystem due to the async garbage collector. Please consider \ - passing --enable-thread-safe-observer-pattern when using the \ - GNU autoconf configure script. +Quantlib has not been compiled with the thread-safe \ +observer pattern being enabled. This can lead to spurious \ +crashes or pure virtual function calls within the JVM or .NET \ +ecosystem due to the async garbage collector. Please consider \ +passing --enable-thread-safe-observer-pattern when using the \ +GNU autoconf configure script. #endif #endif #endif diff --git a/SWIG/ratehelpers.i b/SWIG/ratehelpers.i index 3b89a86239..190e5a9d7d 100644 --- a/SWIG/ratehelpers.i +++ b/SWIG/ratehelpers.i @@ -46,7 +46,6 @@ using QuantLib::DatedOISRateHelper; using QuantLib::FxSwapRateHelper; using QuantLib::OvernightIndexFutureRateHelper; using QuantLib::SofrFutureRateHelper; -using QuantLib::CrossCurrencyBasisSwapRateHelper; using QuantLib::ConstNotionalCrossCurrencyBasisSwapRateHelper; using QuantLib::MtMCrossCurrencyBasisSwapRateHelper; using QuantLib::IborIborBasisSwapRateHelper; @@ -412,22 +411,6 @@ class SofrFutureRateHelper : public OvernightIndexFutureRateHelper { Real convexityAdjustment = 0.0); }; -%shared_ptr(CrossCurrencyBasisSwapRateHelper) -class CrossCurrencyBasisSwapRateHelper : public RateHelper { - public: - CrossCurrencyBasisSwapRateHelper(const Handle& basis, - const Period& tenor, - Natural fixingDays, - Calendar calendar, - BusinessDayConvention convention, - bool endOfMonth, - ext::shared_ptr baseCurrencyIndex, - ext::shared_ptr quoteCurrencyIndex, - Handle collateralCurve, - bool isFxBaseCurrencyCollateralCurrency, - bool isBasisOnFxBaseCurrencyLeg); -}; - %shared_ptr(ConstNotionalCrossCurrencyBasisSwapRateHelper) class ConstNotionalCrossCurrencyBasisSwapRateHelper : public RateHelper { public: @@ -519,10 +502,6 @@ namespace std { const ext::shared_ptr as_oisratehelper(const ext::shared_ptr helper) { return ext::dynamic_pointer_cast(helper); } - const ext::shared_ptr as_crosscurrencybasisswapratehelper( - const ext::shared_ptr helper) { - return ext::dynamic_pointer_cast(helper); - } const ext::shared_ptr as_constnotionalcrosscurrencybasisswapratehelper( const ext::shared_ptr helper) { return ext::dynamic_pointer_cast(helper); From 1ebede8002edd733a0b3326d8a8927389d9168cf Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Wed, 26 Oct 2022 10:27:28 +0200 Subject: [PATCH 099/322] Look for python3 before python --- configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index 4a154490f1..92c880ec40 100644 --- a/configure.ac +++ b/configure.ac @@ -47,7 +47,7 @@ if test "x$SWIG" != x; then fi fi -AC_PATH_PROG([PYTHON], [python]) +AC_PATH_PROG([PYTHON], [python3 python]) AM_CONDITIONAL(HAVE_PYTHON, test "x${PYTHON}" != "x") AC_ARG_ENABLE([python], AS_HELP_STRING([--disable-python], From 5e863240d2d5041950af5893955c6ed6906cab84 Mon Sep 17 00:00:00 2001 From: klausspanderen Date: Tue, 1 Nov 2022 18:50:06 +0100 Subject: [PATCH 100/322] fixed interface changes --- Python/examples/american-option.py | 2 +- SWIG/options.i | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/Python/examples/american-option.py b/Python/examples/american-option.py index 701d114cac..9b9049ff5b 100644 --- a/Python/examples/american-option.py +++ b/Python/examples/american-option.py @@ -116,7 +116,7 @@ # %% option.setPricingEngine(ql.QdFpAmericanEngine( - process, ql.QdFpIterationSchemeStdFactory_accurateScheme())) + process, ql.QdFpAmericanEngine_accurateScheme())) results.append(("QD+ fixed point", option.NPV())) diff --git a/SWIG/options.i b/SWIG/options.i index c07659ed03..8f9d91f0c1 100644 --- a/SWIG/options.i +++ b/SWIG/options.i @@ -1020,7 +1020,6 @@ using QuantLib::QdFpLegendreScheme; using QuantLib::QdFpIterationScheme; using QuantLib::QdFpLegendreTanhSinhScheme; using QuantLib::QdFpTanhSinhIterationScheme; -using QuantLib::QdFpIterationSchemeStdFactory; using QuantLib::QdFpAmericanEngine; %} @@ -1049,13 +1048,6 @@ class QdFpTanhSinhIterationScheme : public QdFpIterationScheme { }; -class QdFpIterationSchemeStdFactory { - public: - static ext::shared_ptr fastScheme(); - static ext::shared_ptr accurateScheme(); - static ext::shared_ptr highPrecisionScheme(); -}; - %shared_ptr(QdFpAmericanEngine) class QdFpAmericanEngine : public PricingEngine { public: @@ -1064,8 +1056,12 @@ class QdFpAmericanEngine : public PricingEngine { explicit QdFpAmericanEngine( ext::shared_ptr bsProcess, ext::shared_ptr iterationScheme = - QdFpIterationSchemeStdFactory::accurateScheme(), + accurateScheme(), FixedPointEquation fpEquation = Auto); + + static ext::shared_ptr fastScheme(); + static ext::shared_ptr accurateScheme(); + static ext::shared_ptr highPrecisionScheme(); }; From 00d95ee504bbc51f1b7dc80bc4aae27d4d4d14a5 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Wed, 2 Nov 2022 18:15:27 +0100 Subject: [PATCH 101/322] Move installation to build script --- .build/r.build | 4 +++- R/Makefile.am | 7 +------ R/demo/00Index | 6 +++--- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/.build/r.build b/.build/r.build index 5ad99bd22d..2dfb35e322 100755 --- a/.build/r.build +++ b/.build/r.build @@ -7,4 +7,6 @@ echo 'CXX=clang++' >> ~/.R/Makevars ./autogen.sh \ && ./configure CXXFLAGS='-O0' \ && make -C R \ -&& make -C R check +&& R CMD INSTALL ./R.Rcheck/QuantLib \ +&& echo Test curves.R && Rscript ./R/demo/curves.R \ +&& echo Test european-option.R && Rscript ./R/demo/european-option.R diff --git a/R/Makefile.am b/R/Makefile.am index b297cd1f2a..eae6c20c11 100644 --- a/R/Makefile.am +++ b/R/Makefile.am @@ -16,12 +16,7 @@ all-local: .build-stamp cd .. && R CMD check R && cd - touch .build-stamp -check-local: .build-stamp - cd ../R.Rcheck/QuantLib && R CMD INSTALL . - pwd && echo Test Curves && Rscript ./demo/curves.R - pwd && echo Test European Option && Rscript ./demo/european-option.R - echo Remove TestInstall QuantLib && R CMD REMOVE QuantLib - +check-local: .build-stamp install-exec-local: .build-stamp R CMD INSTALL . diff --git a/R/demo/00Index b/R/demo/00Index index b85a4ded63..5c1a77a64b 100644 --- a/R/demo/00Index +++ b/R/demo/00Index @@ -1,8 +1,8 @@ european-option European Option -fd-option Finite-Differences Option +fd-option Finite-Differences Option graph Graph demo scatter Scatter plot wireframe Wireframe -bonds Zero Coupon, Fixed Rate and Floating Rate Bonds +bonds Zero Coupon, Fixed Rate and Floating Rate Bonds bates_vol_surface Bates Stochastic Volatility - +curves Sanity check for exported curves From 59ee67b2511d5047d7f8d14c438159a508dd4a1f Mon Sep 17 00:00:00 2001 From: AndLLA <44858649+AndLLA@users.noreply.github.com> Date: Thu, 3 Nov 2022 22:15:44 +0100 Subject: [PATCH 102/322] fix linkTo method --- R/demo/bonds.R | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/R/demo/bonds.R b/R/demo/bonds.R index c6eecd5875..37fae2c9d0 100644 --- a/R/demo/bonds.R +++ b/R/demo/bonds.R @@ -149,7 +149,6 @@ discountingTermStructure <- RelinkableYieldTermStructureHandle() ## the one used for forward rate forecasting forecastingTermStructure <- RelinkableYieldTermStructureHandle() - ######################################## ## BONDS TO BE PRICED # ######################################## @@ -237,11 +236,25 @@ invisible(setCouponPricer(Bond_cashflows(floatingRateBond), pricer)) ## Yield curve bootstrapping -invisible(RelinkableQuoteHandle_linkTo(forecastingTermStructure, depoSwapTermStructure)) -invisible(RelinkableQuoteHandle_linkTo(discountingTermStructure, bondDiscountingTermStructure)) +if (FALSE) { + # equivalent to the method in else + invisible(forecastingTermStructure$linkTo(depoSwapTermStructure)) + invisible(discountingTermStructure$linkTo(bondDiscountingTermStructure)) +} else { + # equivalent to the previous method + invisible(RelinkableYieldTermStructureHandle_linkTo(forecastingTermStructure, depoSwapTermStructure)) + invisible(RelinkableYieldTermStructureHandle_linkTo(discountingTermStructure, bondDiscountingTermStructure)) +} + ## We are using the depo & swap curve to estimate the future Libor rates -invisible(RelinkableQuoteHandle_linkTo(liborTermStructure, depoSwapTermStructure)) +if (FALSE) { + # equivalent to the method in else + liborTermStructure$linkTo(depoSwapTermStructure) +} else { + # equivalent to the previous method + invisible(RelinkableYieldTermStructureHandle_linkTo(liborTermStructure, depoSwapTermStructure)) +} ## df <- data.frame(zeroCoupon=c(Instrument_NPV(zeroCouponBond), From 143a44e0d0cda1fe50178fb6774b657c43075cee Mon Sep 17 00:00:00 2001 From: AndLLA <44858649+AndLLA@users.noreply.github.com> Date: Thu, 3 Nov 2022 22:25:46 +0100 Subject: [PATCH 103/322] enable bonds.R in tests --- .build/r.build | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.build/r.build b/.build/r.build index 2dfb35e322..53d3ba32c6 100755 --- a/.build/r.build +++ b/.build/r.build @@ -9,4 +9,5 @@ echo 'CXX=clang++' >> ~/.R/Makevars && make -C R \ && R CMD INSTALL ./R.Rcheck/QuantLib \ && echo Test curves.R && Rscript ./R/demo/curves.R \ -&& echo Test european-option.R && Rscript ./R/demo/european-option.R +&& echo Test european-option.R && Rscript ./R/demo/european-option.R \ +&& echo Test bonds.R && Rscript ./R/demo/bonds.R From d682ad59f0293cb7bf2b331b3e1c14cd4c12ad20 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Sat, 5 Nov 2022 11:38:10 +0100 Subject: [PATCH 104/322] Remove unused code --- R/demo/bonds.R | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/R/demo/bonds.R b/R/demo/bonds.R index 37fae2c9d0..0b889bfda0 100644 --- a/R/demo/bonds.R +++ b/R/demo/bonds.R @@ -236,25 +236,11 @@ invisible(setCouponPricer(Bond_cashflows(floatingRateBond), pricer)) ## Yield curve bootstrapping -if (FALSE) { - # equivalent to the method in else - invisible(forecastingTermStructure$linkTo(depoSwapTermStructure)) - invisible(discountingTermStructure$linkTo(bondDiscountingTermStructure)) -} else { - # equivalent to the previous method - invisible(RelinkableYieldTermStructureHandle_linkTo(forecastingTermStructure, depoSwapTermStructure)) - invisible(RelinkableYieldTermStructureHandle_linkTo(discountingTermStructure, bondDiscountingTermStructure)) -} - +invisible(RelinkableYieldTermStructureHandle_linkTo(forecastingTermStructure, depoSwapTermStructure)) +invisible(RelinkableYieldTermStructureHandle_linkTo(discountingTermStructure, bondDiscountingTermStructure)) ## We are using the depo & swap curve to estimate the future Libor rates -if (FALSE) { - # equivalent to the method in else - liborTermStructure$linkTo(depoSwapTermStructure) -} else { - # equivalent to the previous method - invisible(RelinkableYieldTermStructureHandle_linkTo(liborTermStructure, depoSwapTermStructure)) -} +invisible(RelinkableYieldTermStructureHandle_linkTo(liborTermStructure, depoSwapTermStructure)) ## df <- data.frame(zeroCoupon=c(Instrument_NPV(zeroCouponBond), From acaf4c22821aa3293f613756cd08f824b8abbfd9 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Sat, 5 Nov 2022 11:44:39 +0100 Subject: [PATCH 105/322] Require QuantLib 1.29 --- SWIG/ql.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SWIG/ql.i b/SWIG/ql.i index 1cedd93bfd..e38279f14a 100644 --- a/SWIG/ql.i +++ b/SWIG/ql.i @@ -30,7 +30,7 @@ %{ #include -#if QL_HEX_VERSION < 0x01280000 +#if QL_HEX_VERSION < 0x01290000 #error using an old version of QuantLib, please update #endif From 4aba9aa51d56085502817f109653dbe592a22b38 Mon Sep 17 00:00:00 2001 From: Marcin Rybacki Date: Sat, 5 Nov 2022 12:38:35 +0100 Subject: [PATCH 106/322] Exposed lagged fixing function. --- Python/test/inflation.py | 35 +++++++++++++++++++++++++++++++++++ SWIG/inflation.i | 8 ++++++++ 2 files changed, 43 insertions(+) diff --git a/Python/test/inflation.py b/Python/test/inflation.py index e3ad1be1b0..7cdcca0407 100644 --- a/Python/test/inflation.py +++ b/Python/test/inflation.py @@ -375,6 +375,41 @@ def test_inflation_curve_base_fixing(self): msg=fail_msg, delta=EPSILON) + def test_lagged_fixing_method(self): + """Testing lagged fixing method""" + + inflation_idx = build_hicp_index( + EU_FIXING_DATA, self.inflation_ts_handle) + inflation_ts = build_inflation_term_structure( + VALUATION_DATE, + EUR_BEI_SWAP_RATES, + inflation_idx, + ql.CPI.Flat, + self.nominal_ts_handle) + self.inflation_ts_handle.linkTo(inflation_ts) + + maturity_date = ql.Date(25, ql.October, 2027) + lag = ql.Period(3, ql.Months) + indexation = ql.CPI.Flat + + actual_fixing = ql.laggedFixing(inflation_idx, maturity_date, lag, indexation) + expected_fixing = inflation_idx.fixing(ql.Date(1, ql.July, 2027)) + + fail_msg = """ Failed to replicate lagged fixing: + index: {inflation_idx} + actual fixing: {actual_fixing} + expected fixing: {expected_fixing} + tolerance: {tolerance} + """.format(inflation_idx=inflation_idx.familyName(), + actual_fixing=actual_fixing, + expected_fixing=expected_fixing, + tolerance=EPSILON) + self.assertAlmostEquals( + first=actual_fixing, + second=expected_fixing, + msg=fail_msg, + delta=EPSILON) + if __name__ == '__main__': print('testing QuantLib ' + ql.__version__) diff --git a/SWIG/inflation.i b/SWIG/inflation.i index 7f2833009f..0f1eedb6da 100644 --- a/SWIG/inflation.i +++ b/SWIG/inflation.i @@ -264,6 +264,14 @@ struct CPI { enum InterpolationType { AsIndex, Flat, Linear }; }; +%inline %{ + Real laggedFixing(const ext::shared_ptr& index, + const Date& date, + const Period& observationLag, + CPI::InterpolationType interpolationType) { + return QuantLib::CPI::laggedFixing(index, date, observationLag, interpolationType); + } +%} // cashflows From ba44c0377cdcd737ab2c111b9b27da89fcdae81a Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Sat, 5 Nov 2022 13:51:55 +0100 Subject: [PATCH 107/322] Export integral class --- SWIG/integrals.i | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/SWIG/integrals.i b/SWIG/integrals.i index 65b8be59fc..e2d52e1918 100644 --- a/SWIG/integrals.i +++ b/SWIG/integrals.i @@ -41,6 +41,7 @@ using QuantLib::GaussLegendreIntegration; using QuantLib::GaussChebyshevIntegration; using QuantLib::GaussChebyshev2ndIntegration; using QuantLib::GaussGegenbauerIntegration; +using QuantLib::TanhSinhIntegral; %} %define INTEGRATION_METHODS @@ -188,12 +189,6 @@ class GaussGegenbauerIntegration: public GaussianQuadrature { GAUSSIAN_QUADRATURE_METHODS; }; - -#ifdef QL_BOOST_HAS_TANH_SINH -%{ -using QuantLib::TanhSinhIntegral; -%} - class TanhSinhIntegral { public: TanhSinhIntegral( @@ -203,6 +198,5 @@ class TanhSinhIntegral { ); INTEGRATION_METHODS; }; -#endif #endif From aedf6d96026a38e53123c6f33ee0cd21ffa330e3 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Sat, 5 Nov 2022 13:52:18 +0100 Subject: [PATCH 108/322] Fix static method call --- Python/examples/american-option.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/examples/american-option.py b/Python/examples/american-option.py index 9b9049ff5b..8c7cfa0f10 100644 --- a/Python/examples/american-option.py +++ b/Python/examples/american-option.py @@ -116,7 +116,7 @@ # %% option.setPricingEngine(ql.QdFpAmericanEngine( - process, ql.QdFpAmericanEngine_accurateScheme())) + process, ql.QdFpAmericanEngine.accurateScheme())) results.append(("QD+ fixed point", option.NPV())) From 0f3e1a1610960d17302fbd6140e80b0a8422450d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 5 Nov 2022 13:39:42 +0000 Subject: [PATCH 109/322] Update copyright list in license --- LICENSE.TXT | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE.TXT b/LICENSE.TXT index 40a47c4eb8..afd2cc7244 100644 --- a/LICENSE.TXT +++ b/LICENSE.TXT @@ -14,7 +14,7 @@ QuantLib-SWIG is Copyright (C) 2009 Joseph Malicki Copyright (C) 2010 Andrea Odetti Copyright (C) 2010, 2011 Lluis Pujol Bajador - Copyright (C) 2010, 2011, 2012, 2013, 2014, 2015, 2018, 2019, 2020, 2021 Klaus Spanderen + Copyright (C) 2010, 2011, 2012, 2013, 2014, 2015, 2018, 2019, 2020, 2021, 2022 Klaus Spanderen Copyright (C) 2011, 2012 Tawanda Gwena Copyright (C) 2012 Francis Duffy Copyright (C) 2013 Simon Shakeshaft From 6d4cc8e2a62c04c714c71c0718c0802c43a0c57f Mon Sep 17 00:00:00 2001 From: Marcin Rybacki Date: Sat, 5 Nov 2022 16:06:39 +0100 Subject: [PATCH 110/322] Implemented PR feedback. --- Python/test/inflation.py | 2 +- SWIG/inflation.i | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/Python/test/inflation.py b/Python/test/inflation.py index 7cdcca0407..a8c68ef9b7 100644 --- a/Python/test/inflation.py +++ b/Python/test/inflation.py @@ -392,7 +392,7 @@ def test_lagged_fixing_method(self): lag = ql.Period(3, ql.Months) indexation = ql.CPI.Flat - actual_fixing = ql.laggedFixing(inflation_idx, maturity_date, lag, indexation) + actual_fixing = ql.CPI.laggedFixing(inflation_idx, maturity_date, lag, indexation) expected_fixing = inflation_idx.fixing(ql.Date(1, ql.July, 2027)) fail_msg = """ Failed to replicate lagged fixing: diff --git a/SWIG/inflation.i b/SWIG/inflation.i index 0f1eedb6da..01599476ab 100644 --- a/SWIG/inflation.i +++ b/SWIG/inflation.i @@ -262,16 +262,12 @@ using QuantLib::CPI; struct CPI { enum InterpolationType { AsIndex, Flat, Linear }; -}; -%inline %{ - Real laggedFixing(const ext::shared_ptr& index, - const Date& date, - const Period& observationLag, - CPI::InterpolationType interpolationType) { - return QuantLib::CPI::laggedFixing(index, date, observationLag, interpolationType); - } -%} + static Real laggedFixing(const ext::shared_ptr& index, + const Date& date, + const Period& observationLag, + InterpolationType interpolationType); +}; // cashflows From e940d7299e5b90d9ce7cc87405326cfa775ea752 Mon Sep 17 00:00:00 2001 From: AndLLA <44858649+AndLLA@users.noreply.github.com> Date: Sat, 5 Nov 2022 19:11:09 +0100 Subject: [PATCH 111/322] more r tests --- .build/r.build | 25 ++- R/demo/american-option.R | 81 +++++++++ R/demo/basket-option.R | 104 +++++++++++ R/demo/cashflows.R | 144 +++++++++++++++ R/demo/cds.R | 116 ++++++++++++ R/demo/gaussian1d-models.R | 361 +++++++++++++++++++++++++++++++++++++ R/demo/global-bootstrap.R | 152 ++++++++++++++++ 7 files changed, 976 insertions(+), 7 deletions(-) create mode 100644 R/demo/american-option.R create mode 100644 R/demo/basket-option.R create mode 100644 R/demo/cashflows.R create mode 100644 R/demo/cds.R create mode 100644 R/demo/gaussian1d-models.R create mode 100644 R/demo/global-bootstrap.R diff --git a/.build/r.build b/.build/r.build index 53d3ba32c6..a25fef99e3 100755 --- a/.build/r.build +++ b/.build/r.build @@ -1,13 +1,24 @@ #!/bin/bash +set -e mkdir -p ~/.R echo 'CC=clang' > ~/.R/Makevars echo 'CXX=clang++' >> ~/.R/Makevars -./autogen.sh \ -&& ./configure CXXFLAGS='-O0' \ -&& make -C R \ -&& R CMD INSTALL ./R.Rcheck/QuantLib \ -&& echo Test curves.R && Rscript ./R/demo/curves.R \ -&& echo Test european-option.R && Rscript ./R/demo/european-option.R \ -&& echo Test bonds.R && Rscript ./R/demo/bonds.R +pwd + +echo Make Library +./autogen.sh +./configure CXXFLAGS='-O0' +make -C R + +echo Install Library +R CMD INSTALL ./R.Rcheck/QuantLib + +echo Execute Scripts in demo folder +for fn in ./R/demo/*.R +do +echo Test $fn +Rscript "$fn" +done + diff --git a/R/demo/american-option.R b/R/demo/american-option.R new file mode 100644 index 0000000000..4bfafb922d --- /dev/null +++ b/R/demo/american-option.R @@ -0,0 +1,81 @@ + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +settlementDate <- Date(15, "May", 1998) +settlementDate <- Calendar_adjust(calendar, settlementDate) + +fixingDays <- 3 +settlementDays <- 3 +todaysDate <- Calendar_advance(calendar, settlementDate, -fixingDays, "Days") +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +cat('Today : ', todaysDate$`__str__`(), "\n") +cat('Settlement Date: ', settlementDate$`__str__`(), "\n") + + +## option +exercise = AmericanExercise(todaysDate, Date(17, "May", 1999)) +payoff = PlainVanillaPayoff("Put", 40.0) +option = VanillaOption(payoff, exercise) + + +# ### Market data + +# %% +underlying = SimpleQuote(36.0) +dividendYield = FlatForward(todaysDate, 0.00, Actual365Fixed()) +volatility = BlackConstantVol(todaysDate, calendar, 0.20, Actual365Fixed()) +riskFreeRate = FlatForward(todaysDate, 0.06, Actual365Fixed()) + +# %% +process = BlackScholesMertonProcess( + QuoteHandle(underlying), + YieldTermStructureHandle(dividendYield), + YieldTermStructureHandle(riskFreeRate), + BlackVolTermStructureHandle(volatility) +) + +# ### Pricing +# We'll collect tuples of method name, option value, and estimated error from the analytic formula. + +# %% +results = NULL + +# #### Analytic approximations + +option$setPricingEngine(BaroneAdesiWhaleyApproximationEngine(process)) +results = rbind(results, data.frame("method"="Barone-Adesi-Whaley", "NPV"=option$NPV())) + +option$setPricingEngine(BjerksundStenslandApproximationEngine(process)) +results = rbind(results, data.frame("method"="Bjerksund-Stensland", "NPV"=option$NPV())) + + +# #### Finite-difference method + +timeSteps = 801 +gridPoints = 800 + +option$setPricingEngine(FdBlackScholesVanillaEngine(process, timeSteps, gridPoints)) +results = rbind(results, data.frame("method"="finite differences", "NPV"=option$NPV())) + + +# #### Binomial method + +timeSteps = 801 + +# %% +listEngineFuncsNames = lsf.str("package:QuantLib") +listEngineFuncsNames = listEngineFuncsNames[grepl(pattern = "^Binomial", x = listEngineFuncsNames)] +listEngineFuncsNames = listEngineFuncsNames[grepl(pattern = "VanillaEngine$", x = listEngineFuncsNames)] + +for (engineFuncName in listEngineFuncsNames) { + eval(parse(text=paste0("option$setPricingEngine(", engineFuncName, "(process, timeSteps))"))) + results = rbind(results, data.frame("method"=engineFuncName, "NPV"=option$NPV())) +} + + +# ### Results +print(results) diff --git a/R/demo/basket-option.R b/R/demo/basket-option.R new file mode 100644 index 0000000000..9cd367208d --- /dev/null +++ b/R/demo/basket-option.R @@ -0,0 +1,104 @@ + +# inspired by python example with the same name + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +todaysDate <- Date(15, "May", 1998) +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +settlementDays <- 3 +settlementDate <- Calendar_advance(calendar, todaysDate, settlementDays, "Days") + +cat('Today : ', todaysDate$`__str__`(), "\n") +cat('Settlement Date: ', settlementDate$`__str__`(), "\n") + +riskFreeRate = FlatForward(settlementDate, 0.05, Actual365Fixed()) + + +# ### Option parameters +exerciseDate = Date(17, "May", 1999) +exercise = EuropeanExercise(exerciseDate) +payoff = PlainVanillaPayoff("Call", 8.0) + + +# ### Market data +underlying1 = SimpleQuote(7.0) +volatility1 = BlackConstantVol(todaysDate, calendar, 0.10, Actual365Fixed()) +dividendYield1 = FlatForward(settlementDate, 0.05, Actual365Fixed()) +underlying2 = SimpleQuote(7.0) +volatility2 = BlackConstantVol(todaysDate, calendar, 0.10, Actual365Fixed()) +dividendYield2 = FlatForward(settlementDate, 0.05, Actual365Fixed()) + + +process1 = BlackScholesMertonProcess( + QuoteHandle(underlying1), + YieldTermStructureHandle(dividendYield1), + YieldTermStructureHandle(riskFreeRate), + BlackVolTermStructureHandle(volatility1) +) + +process2 = BlackScholesMertonProcess( + QuoteHandle(underlying2), + YieldTermStructureHandle(dividendYield2), + YieldTermStructureHandle(riskFreeRate), + BlackVolTermStructureHandle(volatility2) +) + +corrMatrix = Matrix(2, 2) +invisible(Matrix_setitem(corrMatrix, 0, 0, 1.0)) +invisible(Matrix_setitem(corrMatrix, 1, 1, 1.0)) +invisible(Matrix_setitem(corrMatrix, 1, 0, 0.5)) +invisible(Matrix_setitem(corrMatrix, 0, 1, 0.5)) +cat(corrMatrix$`__str__`()) + +procVector = StochasticProcess1DVector(2) +invisible(StochasticProcess1DVector___setitem__(self = procVector, i = 0, x = process1)) +invisible(StochasticProcess1DVector___setitem__(self = procVector, i = 1, x = process2)) + +process = StochasticProcessArray(array = procVector, correlation = corrMatrix) + +# ### Pricing - European + +basketoption = BasketOption(MaxBasketPayoff(payoff), exercise) +basketoption$setPricingEngine( + MCPREuropeanBasketEngine(process=process, timeSteps=NA, timeStepsPerYear=1, brownianBridge=F, antitheticVariate=F, requiredSamples=NA, requiredTolerance=0.02, maxSamples=10000, seed=42) +) +print(basketoption$NPV()) + +basketoption = BasketOption(MinBasketPayoff(payoff), exercise) +basketoption$setPricingEngine( + MCPREuropeanBasketEngine(process=process, timeSteps=NA, timeStepsPerYear=1, brownianBridge=F, antitheticVariate=F, requiredSamples=NA, requiredTolerance=0.02, maxSamples=10000, seed=42) +) +print(basketoption$NPV()) + +basketoption = BasketOption(AverageBasketPayoff(payoff, 2), exercise) +basketoption$setPricingEngine( + MCPREuropeanBasketEngine(process=process, timeSteps=NA, timeStepsPerYear=1, brownianBridge=F, antitheticVariate=F, requiredSamples=NA, requiredTolerance=0.02, maxSamples=10000, seed=42) +) +print(basketoption$NPV()) + + +# ### Pricing - American + +americanExercise = AmericanExercise(settlementDate, exerciseDate) +americanbasketoption = BasketOption(MaxBasketPayoff(payoff), americanExercise) +americanbasketoption$setPricingEngine( + MCPRAmericanBasketEngine( + process=process, + timeSteps=10, + timeStepsPerYear=NA, + brownianBridge=F, + antitheticVariate=F, + requiredSamples=50000, + requiredTolerance=0.02, + maxSamples=100000, + seed=42, + nCalibrationSamples=5000, + polynomOrder=5, + polynomType=LsmBasisSystem_Hermite_get() + ) +) +print(americanbasketoption$NPV()) diff --git a/R/demo/cashflows.R b/R/demo/cashflows.R new file mode 100644 index 0000000000..f1017f1ea2 --- /dev/null +++ b/R/demo/cashflows.R @@ -0,0 +1,144 @@ + +# inspired by python example with the same name + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +todaysDate <- Date(19, "October", 2020) +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +settlementDays <- 3 +settlementDate <- Calendar_advance(calendar, todaysDate, settlementDays, "Days") + +cat('Today : ', todaysDate$`__str__`(), "\n") +cat('Settlement Date: ', settlementDate$`__str__`(), "\n") + +# ### Term structure construction + +# %% +dates = DateVector() +DateVector_append(dates, DateParser_parseISO("2020-10-19")) +DateVector_append(dates, DateParser_parseISO("2020-11-19")) + +DateVector_append(dates, DateParser_parseISO("2021-01-19")) +DateVector_append(dates, DateParser_parseISO("2021-04-19")) +DateVector_append(dates, DateParser_parseISO("2021-10-19")) + +DateVector_append(dates, DateParser_parseISO("2022-04-19")) +DateVector_append(dates, DateParser_parseISO("2022-10-19")) + +DateVector_append(dates, DateParser_parseISO("2023-10-19")) +DateVector_append(dates, DateParser_parseISO("2025-10-19")) +DateVector_append(dates, DateParser_parseISO("2030-10-19")) +DateVector_append(dates, DateParser_parseISO("2035-10-19")) +DateVector_append(dates, DateParser_parseISO("2040-10-19")) + +DateVector_size(dates) + +rates = c( + -0.004, + -0.002, + 0.001, + 0.005, + 0.009, + 0.010, + 0.010, + 0.012, + 0.017, + 0.019, + 0.028, + 0.032 +) + +length(rates) + +forecast_curve = ZeroCurve(dates, rates, Actual365Fixed()) +forecast_handle = YieldTermStructureHandle(forecast_curve) + +# ### Swap construction +# +# We'll use an overnight swap as an example. +# We're keeping the initialization simple, +# but the analysis work in the same way for more complex ones, +# as well as for other kinds of swaps and bonds (once we extract the cashflows from them using the proper methods). + +# %% +swapBuilder = MakeOIS(swapTenor=Period(5, "Years"), + overnightIndex=Eonia(forecast_handle), + fixedRate=0.002) + +swap = MakeOIS_makeOIS(swapBuilder) + +# ### Cash-flow analysis +# +# The fixed-rate coupons can be extracted from the swap using the `fixedLeg` method. +# + +fixed_leg = OvernightIndexedSwap_fixedLeg(swap) +CashFlows_maturityDate(fixed_leg) + +df = NULL +for (i in seq(1, fixed_leg$size())) { + cfl = fixed_leg[i][[1]] + df = rbind(df, data.frame(date=Date_ISO(CashFlow_date(cfl)), amount=CashFlow_amount(cfl))) +} +print(df) + + +# +# If we want to extract more information, we need to upcast the coupons to a more specific class. +# This can be done by using the `as_coupon` or the `as_fixed_rate_coupon` method. +# + +df = NULL +for (i in seq(1, fixed_leg$size())) { + cfl = fixed_leg[i][[1]] + cflCoupon = as_coupon(cfl) + cflCouponFix = as_fixed_rate_coupon(cfl) + cflCouponFixIr = FixedRateCoupon_interestRate(cflCouponFix) + + df = rbind(df, data.frame(date=Date_ISO(CashFlow_date(cfl)), amount=CashFlow_amount(cfl), + accrualStartDate=Date_ISO(Coupon_accrualStartDate(cflCoupon)), + accrualEndDate=Date_ISO(Coupon_accrualEndDate(cflCoupon)), + accrualPeriod=Coupon_accrualPeriod(cflCoupon), + accrualDays=Coupon_accrualDays(cflCoupon), + accrualDayCounter=DayCounter_name(Coupon_dayCounter(cflCoupon)), + accruedAmount=Coupon_accruedAmount(self = cflCoupon, todaysDate), + rate=InterestRate_rate(cflCouponFixIr), rateDayCount=DayCounter_name(InterestRate_dayCounter(cflCouponFixIr)) + )) +} +print(df) + + + +# %% +floating_leg = swap$overnightLeg() + +# %% +df = NULL +for (i in seq(1, floating_leg$size())) { + cfl = floating_leg[i][[1]] + cflCoupon = as_coupon(cfl) + cflCouponFloat = as_floating_rate_coupon(cfl) + cflCouponFloatIdx = FloatingRateCoupon_index(cflCouponFloat) + + + df = rbind(df, data.frame(date=Date_ISO(CashFlow_date(cfl)), amount=CashFlow_amount(cfl), + accrualStartDate=Date_ISO(Coupon_accrualStartDate(cflCoupon)), + accrualEndDate=Date_ISO(Coupon_accrualEndDate(cflCoupon)), + accrualPeriod=Coupon_accrualPeriod(cflCoupon), + accrualDays=Coupon_accrualDays(cflCoupon), + accrualDayCounter=DayCounter_name(Coupon_dayCounter(cflCoupon)), + accruedAmount=Coupon_accruedAmount(self = cflCoupon, todaysDate), + spread=FloatingRateCoupon_spread(cflCouponFloat), + gearing=FloatingRateCoupon_gearing(cflCouponFloat), + adjFix=FloatingRateCoupon_adjustedFixing(cflCouponFloat), + dtFix=Date_ISO(FloatingRateCoupon_fixingDate(cflCouponFloat)), + convexityAdj=FloatingRateCoupon_convexityAdjustment(cflCouponFloat) + )) +} + +print(df) + diff --git a/R/demo/cds.R b/R/demo/cds.R new file mode 100644 index 0000000000..5cf66ff39f --- /dev/null +++ b/R/demo/cds.R @@ -0,0 +1,116 @@ + +# inspired by python example with the same name + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +todaysDate <- DateParser_parseISO("2007-05-15") +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +settlementDays <- 3 +settlementDate <- Calendar_advance(calendar, todaysDate, settlementDays, "Days") + +cat('Today : ', Date_ISO(todaysDate), "\n") +cat('Settlement Date: ', Date_ISO(settlementDate), "\n") + +risk_free_rate = YieldTermStructureHandle(FlatForward(todaysDate, 0.01, Actual365Fixed())) + +# ### CDS parameters + +recovery_rate = 0.5 +quoted_spreads = c(0.0150, 0.0150, 0.0150, 0.0150) + +tenors = PeriodVector() +tenors$append(Period(3, "Months")) +tenors$append(Period(6, "Months")) +tenors$append(Period(1, "Years")) +tenors$append(Period(2, "Years")) + +maturities = DateVector() +for (i in seq(1, tenors$size())) { + maturities$append( + Calendar_adjust(calendar, + Calendar_advance(calendar, todaysDate, tenors[i][[1]]), + "Following") + ) +} + +instruments = DefaultProbabilityHelperVector() +for (i in seq(1, length(quoted_spreads))) { + s = quoted_spreads[i] + tenor = tenors[i][[1]] + + it = SpreadCdsHelper( + QuoteHandle(SimpleQuote(s)), + tenor, + 0, + calendar, + "Quarterly", + "Following", + DateGeneration_TwentiethIMM_get(), + Actual365Fixed(), + recovery_rate, + risk_free_rate + ) + + instruments$append(it) +} + +hazard_curve = PiecewiseFlatHazardRate(todaysDate, instruments, Actual365Fixed()) + +print("Calibrated hazard rate values: ") +for (i in seq(1, hazard_curve$dates()$size())) { + print(paste("hazard rate on ", + Date_ISO(hazard_curve$dates()[i][[1]]), + "is ", + HazardRateCurve_hazardRates(hazard_curve)[i])) +} + +print(paste("1Y survival probability:", + DefaultProbabilityTermStructure_survivalProbability(hazard_curve, Calendar_advance(calendar, todaysDate, Period(1, "Years"))), + "expected 0.9704 " +)) + +print(paste("2Y survival probability:", + DefaultProbabilityTermStructure_survivalProbability(hazard_curve, Calendar_advance(calendar, todaysDate, Period(2, "Years"))), + "expected 0.9418 " +)) + +# ### Reprice instruments + +nominal = 1000000.0 +probability = DefaultProbabilityTermStructureHandle(hazard_curve) + +# We'll create a cds for every maturity: + +print("Repricing of quoted CDSs employed for calibration: ") +for (i in seq(1, length(quoted_spreads))) { + maturity = maturities[i][[1]] + s = quoted_spreads[i] + tenor = tenors[i][[1]] + + schedule = Schedule( + todaysDate, + maturity, + Period(3, "Months"), # "Quarterly", + calendar, + "Following", + "Unadjusted", + DateGeneration_TwentiethIMM_get(), + F + ) + + cds = CreditDefaultSwap(Protection_Seller_get(), nominal, s, schedule, "Following", Actual365Fixed()) + engine = MidPointCdsEngine(probability, recovery_rate, risk_free_rate) + cds$setPricingEngine(engine) + + print(paste("fair spread: ", Period___str__(tenor), cds$fairSpread())) + print(paste(" NPV: ", cds$NPV())) + print(paste(" default leg: ", cds$defaultLegNPV())) + print(paste(" coupon leg: ", cds$couponLegNPV())) + print("") + +} + diff --git a/R/demo/gaussian1d-models.R b/R/demo/gaussian1d-models.R new file mode 100644 index 0000000000..f9b647e64f --- /dev/null +++ b/R/demo/gaussian1d-models.R @@ -0,0 +1,361 @@ + +# inspired by python example with the same name + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +todaysDate <- DateParser_parseISO("2014-04-30") +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +settlementDays <- 3 +settlementDate <- Calendar_advance(calendar, todaysDate, settlementDays, "Days") + +cat('Today : ', Date_ISO(todaysDate), "\n") +cat('Settlement Date: ', Date_ISO(settlementDate), "\n") + +refDate = todaysDate + +# ### Calculations + +# This exercise tries to replicate the Quantlib C++ `Gaussian1dModel` example on how to use the GSR and Markov Functional model. + +# We assume a multicurve setup, for simplicity with flat yield term structures. +# +# The discounting curve is an Eonia curve at a level of 2% and the forwarding curve is an Euribor 6m curve at a level of 2.5%. +# +# For the volatility we assume a flat swaption volatility at 20%. + + +forward6mQuote = QuoteHandle(SimpleQuote(0.025)) +oisQuote = QuoteHandle(SimpleQuote(0.02)) +volQuote = QuoteHandle(SimpleQuote(0.2)) + +# %% +dc = Actual365Fixed() +yts6m = FlatForward(refDate, forward6mQuote, dc) +ytsOis = FlatForward(refDate, oisQuote, dc) +yts6m$enableExtrapolation() +ytsOis$enableExtrapolation() + +hyts6m = RelinkableYieldTermStructureHandle(yts6m) +t0_curve = YieldTermStructureHandle(yts6m) +t0_Ois = YieldTermStructureHandle(ytsOis) +euribor6m = Euribor6M(hyts6m) +swaptionVol = ConstantSwaptionVolatility(0, calendar, "ModifiedFollowing", volQuote, Actual365Fixed()) + + +# %% +effectiveDate = Calendar_advance(calendar, refDate, 2, "Days") +print(Date_ISO(effectiveDate)) + +maturityDate = Calendar_advance(calendar, effectiveDate, 10, "Years") +print(Date_ISO(maturityDate)) + +# %% +fixedSchedule = Schedule(effectiveDate, + maturityDate, + Period(1, "Years"), + calendar, + "ModifiedFollowing", + "ModifiedFollowing", + DateGeneration_Forward_get(), F) + +# %% +floatSchedule = Schedule(effectiveDate, + maturityDate, + Period(6, "Months"), + calendar, + "ModifiedFollowing", + "ModifiedFollowing", + DateGeneration_Forward_get(), F) + + +# We consider a standard 10-years Bermudan payer swaption with yearly exercises at a strike of 4%. + +# %% +fixedNominal = rep(1, fixedSchedule$size()-1) +floatingNominal = rep(1, floatSchedule$size()-1) +strike = rep(0.04, fixedSchedule$size()-1) +gearing = rep(1, floatSchedule$size()-1) +spread = rep(0, floatSchedule$size()-1) + +# %% +underlying = NonstandardSwap( + Swap_Payer_get(), + fixedNominal, floatingNominal, fixedSchedule, strike, + Thirty360(Thirty360_BondBasis_get()), floatSchedule, + euribor6m, gearing, spread, Actual360(), F, F, "ModifiedFollowing") + +# %% +exerciseDates = Schedule_dates(self = fixedSchedule, .copy = T) +for (i in seq(0, exerciseDates$size()-1)) { # C Style vector numbering + DateVector___setitem__(exerciseDates, i, Calendar_advance(calendar, DateVector___getitem__(exerciseDates, i), -2, "Days")) +} + +DateVector___delitem__(exerciseDates, 0) +DateVector___delitem__(exerciseDates, DateVector___len__(exerciseDates)-1) +for (i in seq(1, exerciseDates$size())) { # R style vector numbering + print(exerciseDates[i][[1]]) +} + +exercise = BermudanExercise(exerciseDates) +swaption = NonstandardSwaption(underlying,exercise,Settlement_Physical_get()) + +# The model is a one factor Hull White model with piecewise volatility adapted to our exercise dates. +# +# The reversion is just kept constant at a level of 1%. + +stepDates = DateVector(exerciseDates) +DateVector___delitem__(stepDates, DateVector___len__(stepDates)-1) + +sigmas = QuoteHandleVector() +for (i in seq(1, 9)) { + QuoteHandleVector_append(sigmas, QuoteHandle(SimpleQuote(0.01))) +} + +reversion = QuoteHandleVector() +QuoteHandleVector_append(reversion, QuoteHandle(SimpleQuote(0.01))) + +# +# The model's curve is set to the 6m forward curve. +# Note that the model adapts automatically to other curves where appropriate +# (e.g. if an index requires a different forwarding curve) or where explicitly specified (e.g. in a swaption pricing engine). + + +gsr = Gsr(t0_curve, stepDates, sigmas, reversion) +swaptionEngine = Gaussian1dSwaptionEngine(gsr, 64, 7.0, T, F, t0_Ois) +nonstandardSwaptionEngine = Gaussian1dNonstandardSwaptionEngine( + gsr, 64, 7.0, T, F, QuoteHandle(SimpleQuote(0)), t0_Ois) + +# %% +swaption$setPricingEngine(nonstandardSwaptionEngine) + +# %% +swapBase = EuriborSwapIsdaFixA(Period(10, 'Years'), t0_curve, t0_Ois) +basket = swaption$calibrationBasket(swapBase, swaptionVol, 'Naive') + +# %% +for (i in seq(1, basket$size())) { + basket_i = basket[i][[1]] + BlackCalibrationHelper_setPricingEngine(basket_i, swaptionEngine) +} + + +# %% +method = LevenbergMarquardt() +ec = EndCriteria(1000, 10, 1e-8, 1e-8, 1e-8) + +# %% +gsr$calibrateVolatilitiesIterative(basket, method, ec) + + +# %% [markdown] +# The engine can generate a calibration basket in two modes. +# +# The first one is called Naive and generates ATM swaptions adapted to the exercise dates of the swaption and its maturity date. The resulting basket looks as follows: + +# %% +basket_data = function(basket) { + df = NULL + for (i in seq(1, basket$size())) { + basket_i = basket[i][[1]] + h = as_swaption_helper(basket_i) + hopt = SwaptionHelper_swaption(h) + df = rbind(df, data.frame(expiry=Date_ISO(SwaptionHelper_swaptionExpiryDate(h)), + maturity=Date_ISO(SwaptionHelper_swaptionMaturityDate(h)), + nominal=SwaptionHelper_swaptionNominal(h), + strike=SwaptionHelper_swaptionStrike(h), + optType=Swaption_type(hopt) + + )) + } + df +} + +print(basket_data(basket)) + + + + +# +# Let's calibrate our model to this basket. +# We use a specialized calibration method calibrating the sigma function one by one to the calibrating vanilla swaptions. The result of this is as follows: + +# %% +calibration_data = function(basket, volatilities) { + # volatilities = gsr$volatility() + df = NULL + for (i in seq(1, basket$size())) { + basket_i = basket[i][[1]] + vola_i = volatilities[i][[1]] + h = as_swaption_helper(basket_i) + hopt = SwaptionHelper_swaption(h) + modelPrice = basket_i$modelValue() + modelImpVol = BlackCalibrationHelper_impliedVolatility(self = basket_i, targetValue = modelPrice, accuracy = 1e-6, maxEvaluations = 1000, minVol = 0.0, maxVol = 2.0) + marketPrice = basket_i$marketValue() + + df = rbind(df, data.frame(expiry=Date_ISO(SwaptionHelper_swaptionExpiryDate(h)), + modelSigma=vola_i, + modelPrice=modelPrice, + marketPrice=marketPrice, + modelImpVol=modelImpVol, + marketImpVol=QuoteHandle_value(basket_i$volatility()) + )) + } + + df +} + +print(calibration_data(basket, gsr$volatility())) + +# %% [markdown] +# Bermudan swaption NPV (ATM calibrated GSR): + +# %% +print(swaption$NPV()) + + +# +# There is another mode to generate a calibration basket called `MaturityStrikeByDeltaGamma`. +# This means that the maturity, the strike and the nominal of the calibrating swaptions are obtained matching the NPV, +# first derivative and second derivative of the swap you will exercise into at at each bermudan call date. +# The derivatives are taken with respect to the model's state variable. +# +# Let's try this in our case. + +# %% +basket = swaption$calibrationBasket(swapBase, swaptionVol, 'MaturityStrikeByDeltaGamma') +print(basket_data(basket)) + +# %% +for (i in seq(1, basket$size())) { + basket_i = basket[i][[1]] + BlackCalibrationHelper_setPricingEngine(basket_i, swaptionEngine) +} + + +# %% [markdown] +# The calibrated nominal is close to the exotics nominal. The expiries and maturity dates of the vanillas are the same as in the case above. The difference is the strike which is now equal to the exotics strike. +# +# Let's see how this affects the exotics NPV. The recalibrated model is: + +# %% +gsr$calibrateVolatilitiesIterative(basket, method, ec) +print(calibration_data(basket, gsr$volatility())) + +# %% [markdown] +# Bermudan swaption NPV (deal strike calibrated GSR): + +# %% +print(swaption$NPV()) + +# +# We can do more complicated things. +# Let's e.g. modify the nominal schedule to be linear amortizing and see what the effect on the generated calibration basket is: + +# %% +for (i in seq(1,fixedSchedule$size()-1)) { + tmp = 1.0 - i/ (fixedSchedule$size()) + fixedNominal[i] = tmp + floatingNominal[i*2-1] = tmp + floatingNominal[i*2] = tmp +} + +# %% +underlying2 = NonstandardSwap(Swap_Payer_get(), + fixedNominal, floatingNominal, fixedSchedule, strike, + Thirty360(Thirty360_BondBasis_get()), floatSchedule, + euribor6m, gearing, spread, Actual360(), F, F, "ModifiedFollowing") + +# %% +swaption2 = NonstandardSwaption(underlying2, exercise, Settlement_Physical_get()) + +# %% +swaption2$setPricingEngine(nonstandardSwaptionEngine) +basket = swaption2$calibrationBasket(swapBase, swaptionVol, 'MaturityStrikeByDeltaGamma') + +# %% +print(basket_data(basket)) + +# +# The notional is weighted over the underlying exercised into and the maturity is adjusted downwards. The rate, on the other hand, is not affected. + +# +# You can also price exotic bond's features. +# If you have e.g. a Bermudan callable fixed bond you can set up the call right as a swaption +# to enter into a one leg swap with notional reimbursement at maturity. +# The exercise should then be written as a rebated exercise paying the notional in case of exercise. The calibration basket looks like this: + +# %% +fixedNominal2 = rep(1, fixedSchedule$size()-1) +floatingNominal2 = rep(0, fixedSchedule$size()*2-2) #null the second leg + +# %% +underlying3 = NonstandardSwap(Swap_Receiver_get(), + fixedNominal2, floatingNominal2, fixedSchedule, strike, + Thirty360(Thirty360_BondBasis_get()), floatSchedule, + euribor6m, gearing, spread, Actual360(), F, T, "ModifiedFollowing") + +# %% +rebateAmount = rep(-1, exerciseDates$size()) +exercise2 = RebatedExercise(exercise, rebateAmount, 2, calendar) +swaption3 = NonstandardSwaption(underlying3, exercise2, Settlement_Physical_get()) + +# %% +oas0 = SimpleQuote(0) +oas100 = SimpleQuote(0.01) +oas = RelinkableQuoteHandle(oas0) + +# %% +nonstandardSwaptionEngine2 = Gaussian1dNonstandardSwaptionEngine( + gsr, 64, 7.0, T, F, oas, t0_curve) # Change discounting to 6m + +# %% +swaption3$setPricingEngine(nonstandardSwaptionEngine2) +basket = swaption3$calibrationBasket(swapBase, swaptionVol, 'MaturityStrikeByDeltaGamma') + +# %% +print(basket_data(basket)) + +# %% [markdown] +# Note that nominals are not exactly 1.0 here. This is because we do our bond discounting on 6m level while the swaptions are still discounted on OIS level. (You can try this by changing the OIS level to the 6m level, which will produce nominals near 1.0). +# +# The NPV of the call right is (after recalibrating the model): + +# %% +for (i in seq(1, basket$size())) { + basket_i = basket[i][[1]] + BlackCalibrationHelper_setPricingEngine(basket_i, swaptionEngine) +} + +# %% +gsr$calibrateVolatilitiesIterative(basket, method, ec) + +# %% +print(swaption3$NPV()) + +# %% [markdown] +# Up to now, no credit spread is included in the pricing. We can do so by specifying an oas in the pricing engine. Let's set the spread level to 100bp and regenerate the calibration basket. + +# %% +oas$linkTo(oas100) +basket = swaption3$calibrationBasket(swapBase, swaptionVol, 'MaturityStrikeByDeltaGamma') +print(basket_data(basket)) + +# %% [markdown] +# The adjusted basket takes the credit spread into account. This is consistent to a hedge where you would have a margin on the float leg around 100bp,too. + +# %% +for (i in seq(1, basket$size())) { + basket_i = basket[i][[1]] + BlackCalibrationHelper_setPricingEngine(basket_i, swaptionEngine) +} + +# %% +gsr$calibrateVolatilitiesIterative(basket, method, ec) + +# %% +print(swaption3$NPV()) + diff --git a/R/demo/global-bootstrap.R b/R/demo/global-bootstrap.R new file mode 100644 index 0000000000..3abe69abe5 --- /dev/null +++ b/R/demo/global-bootstrap.R @@ -0,0 +1,152 @@ + +# inspired by python example with the same name + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +todaysDate <- DateParser_parseISO("2019-09-26") +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +settlementDays <- 2 +settlementDate <- Calendar_advance(calendar, todaysDate, settlementDays, "Days") + +cat('Today : ', Date_ISO(todaysDate), "\n") +cat('Settlement Date: ', Date_ISO(settlementDate), "\n") + +spot = settlementDate + +# %% [markdown] +# ### Data +# +# We'll use the following data as input: + +# %% +refMktRates = c( + -0.373, + -0.388, + -0.402, + -0.418, + -0.431, + -0.441, + -0.45, + -0.457, + -0.463, + -0.469, + -0.461, + -0.463, + -0.479, + -0.4511, + -0.45418, + -0.439, + -0.4124, + -0.37703, + -0.3335, + -0.28168, + -0.22725, + -0.1745, + -0.12425, + -0.07746, + 0.0385, + 0.1435, + 0.17525, + 0.17275, + 0.1515, + 0.1225, + 0.095, + 0.0644 +) + +# ### Market instruments + +# %% +index = Euribor6M() + +# The first market rate is for the 6-months deposit... + +# %% +helpers = RateHelperVector() + +helpers$append( + DepositRateHelper( + refMktRates[1] / 100.0, Period(6, "Months"), 2, calendar, "ModifiedFollowing", T, Actual360() + ) +) + +# ...the next 12 are for FRAs... + +# %% +for (i in seq(2, 13)) { + helpers$append( + FraRateHelper(refMktRates[i] / 100.0, i + 1, index) + ) +} + +# ...and the others are swap rates. + +# %% +swapTenors = c(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 15, 20, 25, 30, 35, 40, 45, 50) + +for (i in seq(14, length(refMktRates))) { + r = refMktRates[i] + tenor = swapTenors[i-13] + helpers$append( + SwapRateHelper( + r / 100.0, Period(tenor, "Years"), calendar, "Annual", "ModifiedFollowing", Thirty360(Thirty360_BondBasis_get()), index + ) + ) +} + +# We'll also add a few synthetic helpers: + +# %% +additional_helpers = RateHelperVector() +for (i in seq(0, 6)){ + additional_helpers$append( + FraRateHelper(-0.004, 12 + i, index) + ) +} + +# %% +additional_dates = DateVector() +for (i in seq(0, 4)){ + additional_dates$append( + Calendar_advance(calendar, spot, Period(i+1, "Months")) + ) +} + + + +# ### Global bootstrap +# +# This curve takes into account the market instruments, as well as the passed additional ones. + +# %% +curve = GlobalLinearSimpleZeroCurve( + spot, helpers, Actual365Fixed(), GlobalBootstrap(additional_helpers, additional_dates, 1.0e-4) +) +curve$enableExtrapolation() + + +# ### Report +df = NULL +for (i in seq(1, helpers$size())) { + h = helpers[i][[1]] + pillar = RateHelper_pillarDate(h) + + day_counter = Actual360() + compounding = "Simple" + if (i > 13) { + day_counter = Thirty360(Thirty360_BondBasis_get()) + compounding = "SimpleThenCompounded" + } + + r = YieldTermStructure_zeroRate(curve, pillar, day_counter, compounding, "Annual") + + df = rbind(df, data.frame( + pillar=Date_ISO(pillar), zeroRate=InterestRate_rate(r)*100.0 + )) +} +print(df) + From 72ec5837dbdd5b708a8a5028cd6c2a2fd8f00ace Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 8 Nov 2022 15:25:58 +0100 Subject: [PATCH 112/322] Separate CI steps for build, install and check --- .build/csharp.build | 6 ------ .build/java-new.build | 9 --------- .build/java-old.build | 8 -------- .build/python3.build | 12 ------------ .build/r.build | 24 ------------------------ .build/scala.build | 7 ------- .ci/csharp.build | 6 ++++++ .ci/csharp.check | 4 ++++ .ci/csharp.install | 2 ++ .ci/java-new.build | 9 +++++++++ .ci/java-new.check | 4 ++++ .ci/java-new.install | 2 ++ .ci/java-old.build | 8 ++++++++ .ci/java-old.check | 4 ++++ .ci/java-old.install | 2 ++ .ci/python3.build | 7 +++++++ .ci/python3.check | 9 +++++++++ .ci/python3.install | 6 ++++++ .ci/r.build | 10 ++++++++++ .ci/r.check | 9 +++++++++ .ci/r.install | 4 ++++ .ci/scala.build | 7 +++++++ .ci/scala.check | 4 ++++ .ci/scala.install | 2 ++ .github/workflows/linux.yml | 13 ++++++++----- 25 files changed, 107 insertions(+), 71 deletions(-) delete mode 100755 .build/csharp.build delete mode 100755 .build/java-new.build delete mode 100755 .build/java-old.build delete mode 100755 .build/python3.build delete mode 100755 .build/r.build delete mode 100755 .build/scala.build create mode 100755 .ci/csharp.build create mode 100755 .ci/csharp.check create mode 100755 .ci/csharp.install create mode 100755 .ci/java-new.build create mode 100755 .ci/java-new.check create mode 100755 .ci/java-new.install create mode 100755 .ci/java-old.build create mode 100755 .ci/java-old.check create mode 100755 .ci/java-old.install create mode 100755 .ci/python3.build create mode 100755 .ci/python3.check create mode 100755 .ci/python3.install create mode 100755 .ci/r.build create mode 100755 .ci/r.check create mode 100755 .ci/r.install create mode 100755 .ci/scala.build create mode 100755 .ci/scala.check create mode 100755 .ci/scala.install diff --git a/.build/csharp.build b/.build/csharp.build deleted file mode 100755 index 9d6208d082..0000000000 --- a/.build/csharp.build +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -./autogen.sh \ -&& ./configure CC=clang CXX=clang++ CXXFLAGS='-O2' \ -&& make -C CSharp \ -&& make -C CSharp check diff --git a/.build/java-new.build b/.build/java-new.build deleted file mode 100755 index c14429701f..0000000000 --- a/.build/java-new.build +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash - -./autogen.sh \ -&& ./configure --disable-java-finalizer --enable-java-autocloseable \ - --with-jdk-include=/usr/lib/jvm/default-java/include \ - --with-jdk-system-include=/usr/lib/jvm/default-java/include/linux \ - CC=clang CXX=clang++ CXXFLAGS='-O2' \ -&& make -C Java \ -&& make -C Java check diff --git a/.build/java-old.build b/.build/java-old.build deleted file mode 100755 index 339b89e629..0000000000 --- a/.build/java-old.build +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash - -./autogen.sh \ -&& ./configure --with-jdk-include=/usr/lib/jvm/default-java/include \ - --with-jdk-system-include=/usr/lib/jvm/default-java/include/linux \ - CC=clang CXX=clang++ CXXFLAGS='-O2' \ -&& make -C Java \ -&& make -C Java check diff --git a/.build/python3.build b/.build/python3.build deleted file mode 100755 index 2e90868c42..0000000000 --- a/.build/python3.build +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -./autogen.sh \ -&& ./configure PYTHON=/usr/bin/python3 CC=clang CXX=clang++ CXXFLAGS='-O1' \ -&& make -C Python \ -&& make -C Python check \ -&& make -C Python wheel \ -&& pip install Python/dist/QuantLib-*.whl \ -&& grep -v QuantLib requirements.txt > Python/examples/requirements.txt \ -&& pip install -r Python/examples/requirements.txt \ -&& for i in Python/examples/*.py ; do echo "$i" && /usr/bin/python3 "$i" || break -1 ; done - diff --git a/.build/r.build b/.build/r.build deleted file mode 100755 index a25fef99e3..0000000000 --- a/.build/r.build +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -set -e - -mkdir -p ~/.R -echo 'CC=clang' > ~/.R/Makevars -echo 'CXX=clang++' >> ~/.R/Makevars - -pwd - -echo Make Library -./autogen.sh -./configure CXXFLAGS='-O0' -make -C R - -echo Install Library -R CMD INSTALL ./R.Rcheck/QuantLib - -echo Execute Scripts in demo folder -for fn in ./R/demo/*.R -do -echo Test $fn -Rscript "$fn" -done - diff --git a/.build/scala.build b/.build/scala.build deleted file mode 100755 index fc38491ada..0000000000 --- a/.build/scala.build +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/bash - -./autogen.sh \ -&& ./configure --with-jdk-include=/usr/lib/jvm/default-java/include \ - --with-jdk-system-include=/usr/lib/jvm/default-java/include/linux CXXFLAGS='-O2' \ -&& make -C Java \ -&& make -C Scala check diff --git a/.ci/csharp.build b/.ci/csharp.build new file mode 100755 index 0000000000..e991b6a2dc --- /dev/null +++ b/.ci/csharp.build @@ -0,0 +1,6 @@ +#!/bin/bash +set -e + +./autogen.sh +./configure CC=clang CXX=clang++ CXXFLAGS='-O2' +make -C CSharp diff --git a/.ci/csharp.check b/.ci/csharp.check new file mode 100755 index 0000000000..763d849012 --- /dev/null +++ b/.ci/csharp.check @@ -0,0 +1,4 @@ +#!/bin/bash +set -e + +make -C CSharp check diff --git a/.ci/csharp.install b/.ci/csharp.install new file mode 100755 index 0000000000..2005ff9b31 --- /dev/null +++ b/.ci/csharp.install @@ -0,0 +1,2 @@ +#!/bin/bash +set -e diff --git a/.ci/java-new.build b/.ci/java-new.build new file mode 100755 index 0000000000..0cb9cc4c07 --- /dev/null +++ b/.ci/java-new.build @@ -0,0 +1,9 @@ +#!/bin/bash +set -e + +./autogen.sh +./configure --disable-java-finalizer --enable-java-autocloseable \ + --with-jdk-include=/usr/lib/jvm/default-java/include \ + --with-jdk-system-include=/usr/lib/jvm/default-java/include/linux \ + CC=clang CXX=clang++ CXXFLAGS='-O2' +make -C Java diff --git a/.ci/java-new.check b/.ci/java-new.check new file mode 100755 index 0000000000..a288402dae --- /dev/null +++ b/.ci/java-new.check @@ -0,0 +1,4 @@ +#!/bin/bash +set -e + +make -C Java check diff --git a/.ci/java-new.install b/.ci/java-new.install new file mode 100755 index 0000000000..2005ff9b31 --- /dev/null +++ b/.ci/java-new.install @@ -0,0 +1,2 @@ +#!/bin/bash +set -e diff --git a/.ci/java-old.build b/.ci/java-old.build new file mode 100755 index 0000000000..af3f87f42b --- /dev/null +++ b/.ci/java-old.build @@ -0,0 +1,8 @@ +#!/bin/bash +set -e + +./autogen.sh +./configure --with-jdk-include=/usr/lib/jvm/default-java/include \ + --with-jdk-system-include=/usr/lib/jvm/default-java/include/linux \ + CC=clang CXX=clang++ CXXFLAGS='-O2' +make -C Java diff --git a/.ci/java-old.check b/.ci/java-old.check new file mode 100755 index 0000000000..a288402dae --- /dev/null +++ b/.ci/java-old.check @@ -0,0 +1,4 @@ +#!/bin/bash +set -e + +make -C Java check diff --git a/.ci/java-old.install b/.ci/java-old.install new file mode 100755 index 0000000000..2005ff9b31 --- /dev/null +++ b/.ci/java-old.install @@ -0,0 +1,2 @@ +#!/bin/bash +set -e diff --git a/.ci/python3.build b/.ci/python3.build new file mode 100755 index 0000000000..aa36b29f50 --- /dev/null +++ b/.ci/python3.build @@ -0,0 +1,7 @@ +#!/bin/bash +set -e + +./autogen.sh +./configure PYTHON=/usr/bin/python3 CC=clang CXX=clang++ CXXFLAGS='-O1' +make -C Python +make -C Python wheel diff --git a/.ci/python3.check b/.ci/python3.check new file mode 100755 index 0000000000..766409de80 --- /dev/null +++ b/.ci/python3.check @@ -0,0 +1,9 @@ +#!/bin/bash +set -e + +make -C Python check +for i in Python/examples/*.py +do + echo "$i" + /usr/bin/python3 "$i" || break -1 +done diff --git a/.ci/python3.install b/.ci/python3.install new file mode 100755 index 0000000000..1da38a0837 --- /dev/null +++ b/.ci/python3.install @@ -0,0 +1,6 @@ +#!/bin/bash +set -e + +pip install Python/dist/QuantLib-*.whl +grep -v QuantLib requirements.txt > Python/examples/requirements.txt +pip install -r Python/examples/requirements.txt diff --git a/.ci/r.build b/.ci/r.build new file mode 100755 index 0000000000..6d98589087 --- /dev/null +++ b/.ci/r.build @@ -0,0 +1,10 @@ +#!/bin/bash +set -e + +mkdir -p ~/.R +echo 'CC=clang' > ~/.R/Makevars +echo 'CXX=clang++' >> ~/.R/Makevars + +./autogen.sh +./configure CXXFLAGS='-O0' +make -C R diff --git a/.ci/r.check b/.ci/r.check new file mode 100755 index 0000000000..b6d2aaa0c8 --- /dev/null +++ b/.ci/r.check @@ -0,0 +1,9 @@ +#!/bin/bash +set -e + +echo Execute Scripts in demo folder +for fn in ./R/demo/*.R +do + echo $fn + Rscript "$fn" || break -1 +done diff --git a/.ci/r.install b/.ci/r.install new file mode 100755 index 0000000000..8e6262c45a --- /dev/null +++ b/.ci/r.install @@ -0,0 +1,4 @@ +#!/bin/bash +set -e + +R CMD INSTALL ./R.Rcheck/QuantLib diff --git a/.ci/scala.build b/.ci/scala.build new file mode 100755 index 0000000000..a1a36510a7 --- /dev/null +++ b/.ci/scala.build @@ -0,0 +1,7 @@ +#!/bin/bash +set -e + +./autogen.sh +./configure --with-jdk-include=/usr/lib/jvm/default-java/include \ + --with-jdk-system-include=/usr/lib/jvm/default-java/include/linux CXXFLAGS='-O2' +make -C Java diff --git a/.ci/scala.check b/.ci/scala.check new file mode 100755 index 0000000000..eb0eeb228f --- /dev/null +++ b/.ci/scala.check @@ -0,0 +1,4 @@ +#!/bin/bash +set -e + +make -C Scala check diff --git a/.ci/scala.install b/.ci/scala.install new file mode 100755 index 0000000000..2005ff9b31 --- /dev/null +++ b/.ci/scala.install @@ -0,0 +1,2 @@ +#!/bin/bash +set -e diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 9046b7a0df..5fba4dc29b 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -17,10 +17,13 @@ jobs: - language: scala container: ghcr.io/lballabio/quantlib-swig-devenv:${{ matrix.language }} steps: - - name: Set up git permissions - run: | - git config --global --add safe.directory $GITHUB_WORKSPACE - uses: actions/checkout@v3 - - name: Build and check + - name: Build + run: | + ./.ci/${{ matrix.language }}${{ matrix.config }}.build + - name: Install + run: | + ./.ci/${{ matrix.language }}${{ matrix.config }}.install + - name: Check run: | - ./.build/${{ matrix.language }}${{ matrix.config }}.build + ./.ci/${{ matrix.language }}${{ matrix.config }}.check From 739b7fda32d7c35444983bd3424a5b897f44e3b9 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 8 Nov 2022 16:13:42 +0100 Subject: [PATCH 113/322] Move common methods to base class --- SWIG/integrals.i | 35 +++++++++++------------------------ 1 file changed, 11 insertions(+), 24 deletions(-) diff --git a/SWIG/integrals.i b/SWIG/integrals.i index e2d52e1918..f6048b4671 100644 --- a/SWIG/integrals.i +++ b/SWIG/integrals.i @@ -59,21 +59,6 @@ using QuantLib::TanhSinhIntegral; } %enddef -%define GAUSSIAN_QUADRATURE_METHODS - %extend { - #if defined(SWIGPYTHON) - Real __call__(PyObject* pyFunction) { - UnaryFunction f(pyFunction); - return (*self)(f); - } - #elif defined(SWIGJAVA) || defined(SWIGCSHARP) - Real calculate(UnaryFunctionDelegate* f) { - return (*self)(UnaryFunction(f)); - } - #endif - } -%enddef - class SegmentIntegral { public: SegmentIntegral(Size intervals); @@ -138,55 +123,57 @@ class GaussianQuadrature { Array x() { return self->x(); } + #if defined(SWIGPYTHON) + Real __call__(PyObject* pyFunction) { + UnaryFunction f(pyFunction); + return (*self)(f); + } + #elif defined(SWIGJAVA) || defined(SWIGCSHARP) + Real calculate(UnaryFunctionDelegate* f) { + return (*self)(UnaryFunction(f)); + } + #endif } }; class GaussLaguerreIntegration: public GaussianQuadrature { public: GaussLaguerreIntegration(Size n, Real s = 0.0); - GAUSSIAN_QUADRATURE_METHODS; }; -class GaussHermiteIntegration { +class GaussHermiteIntegration: public GaussianQuadrature { public: GaussHermiteIntegration(Size n, Real mu = 0.0); - GAUSSIAN_QUADRATURE_METHODS; }; class GaussJacobiIntegration: public GaussianQuadrature { public: GaussJacobiIntegration(Size n, Real alpha, Real beta); - GAUSSIAN_QUADRATURE_METHODS; }; class GaussHyperbolicIntegration: public GaussianQuadrature { public: GaussHyperbolicIntegration(Size n); - GAUSSIAN_QUADRATURE_METHODS; }; class GaussLegendreIntegration: public GaussianQuadrature { public: GaussLegendreIntegration(Size n); - GAUSSIAN_QUADRATURE_METHODS; }; class GaussChebyshevIntegration: public GaussianQuadrature { public: GaussChebyshevIntegration(Size n); - GAUSSIAN_QUADRATURE_METHODS; }; class GaussChebyshev2ndIntegration: public GaussianQuadrature { public: GaussChebyshev2ndIntegration(Size n); - GAUSSIAN_QUADRATURE_METHODS; }; class GaussGegenbauerIntegration: public GaussianQuadrature { public: GaussGegenbauerIntegration(Size n, Real lambda); - GAUSSIAN_QUADRATURE_METHODS; }; class TanhSinhIntegral { From 3586b57b52ee64920750e0a4c865f1fab61b0ff5 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Thu, 10 Nov 2022 10:02:07 +0100 Subject: [PATCH 114/322] Export YoY inflation coupons and related classes --- SWIG/inflation.i | 131 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 127 insertions(+), 4 deletions(-) diff --git a/SWIG/inflation.i b/SWIG/inflation.i index a6e8f47e11..1e90d136e0 100644 --- a/SWIG/inflation.i +++ b/SWIG/inflation.i @@ -143,7 +143,6 @@ class CustomRegion : public Region { }; %shared_ptr(InflationIndex) - class InflationIndex : public Index { protected: InflationIndex(); @@ -158,7 +157,6 @@ class InflationIndex : public Index { }; %shared_ptr(ZeroInflationIndex) - class ZeroInflationIndex : public InflationIndex { public: ZeroInflationIndex(const std::string& familyName, @@ -174,8 +172,13 @@ class ZeroInflationIndex : public InflationIndex { ext::shared_ptr clone(const Handle& h) const; }; -%shared_ptr(YoYInflationIndex) +%inline %{ + ext::shared_ptr as_zero_inflation_index(const ext::shared_ptr& i) { + return ext::dynamic_pointer_cast(i); + } +%} +%shared_ptr(YoYInflationIndex) class YoYInflationIndex : public InflationIndex { public: YoYInflationIndex(const std::string& familyName, @@ -606,6 +609,22 @@ class PiecewiseYoYInflationCurve : public YoYInflationTermStructure { // utilities +%{ +using QuantLib::inflationPeriod; +using QuantLib::inflationYearFraction; +%} + +%template(DatePair) std::pair; + +std::pair inflationPeriod(const Date & d, + Frequency f); + +Time inflationYearFraction(Frequency f, + bool indexIsInterpolated, + const DayCounter& dayCount, + const Date& d1, const Date& d2); + + %inline %{ Date inflationBaseDate(const Date& referenceDate, @@ -622,7 +641,87 @@ class PiecewiseYoYInflationCurve : public YoYInflationTermStructure { %} -// inflation coupons +// year-on-year inflation coupons + +%{ +using QuantLib::YoYInflationCoupon; +using QuantLib::CappedFlooredYoYInflationCoupon; +using QuantLib::YoYInflationCouponPricer; +using QuantLib::setCouponPricer; +using QuantLib::BlackYoYInflationCouponPricer; +using QuantLib::UnitDisplacedBlackYoYInflationCouponPricer; +using QuantLib::BachelierYoYInflationCouponPricer; +%} + +%shared_ptr(YoYInflationCouponPricer) +class YoYInflationCouponPricer { + private: + YoYInflationCouponPricer(); +}; + +void setCouponPricer(const Leg&, const ext::shared_ptr&); + +%shared_ptr(YoYInflationCoupon) +class YoYInflationCoupon : public InflationCoupon { + public: + YoYInflationCoupon(const Date& paymentDate, + Real nominal, + const Date& startDate, + const Date& endDate, + Natural fixingDays, + const ext::shared_ptr& index, + const Period& observationLag, + const DayCounter& dayCounter, + Real gearing = 1.0, + Spread spread = 0.0, + const Date& refPeriodStart = Date(), + const Date& refPeriodEnd = Date()); + Real gearing() const; + Spread spread() const; + Rate adjustedFixing() const; + ext::shared_ptr yoyIndex() const; +}; + +%inline %{ + ext::shared_ptr as_yoy_inflation_coupon( + const ext::shared_ptr& cf) { + return ext::dynamic_pointer_cast(cf); + } +%} + +%shared_ptr(CappedFlooredYoYInflationCoupon) +class CappedFlooredYoYInflationCoupon : public YoYInflationCoupon { + public: + CappedFlooredYoYInflationCoupon(const Date& paymentDate, + Real nominal, + const Date& startDate, + const Date& endDate, + Natural fixingDays, + const ext::shared_ptr& index, + const Period& observationLag, + const DayCounter& dayCounter, + Real gearing = 1.0, + Spread spread = 0.0, + const Rate cap = Null(), + const Rate floor = Null(), + const Date& refPeriodStart = Date(), + const Date& refPeriodEnd = Date()); + Rate rate() const; + Rate cap() const; + Rate floor() const; + Rate effectiveCap() const; + Rate effectiveFloor() const; + Rate underlyingRate() const; + bool isCapped() const; + bool isFloored() const; +}; + +%inline %{ + ext::shared_ptr as_capped_floored_yoy_inflation_coupon( + const ext::shared_ptr& cf) { + return ext::dynamic_pointer_cast(cf); + } +%} %{ Leg _yoyInflationLeg(const Schedule& schedule, @@ -663,6 +762,30 @@ Leg _yoyInflationLeg(const Schedule& schedule, const std::vector& caps = std::vector(), const std::vector& floors = std::vector()); +%shared_ptr(BlackYoYInflationCouponPricer) +class BlackYoYInflationCouponPricer : public YoYInflationCouponPricer { + public: + BlackYoYInflationCouponPricer( + const Handle& capletVol, + const Handle& nominalTermStructure); +}; + +%shared_ptr(UnitDisplacedBlackYoYInflationCouponPricer) +class UnitDisplacedBlackYoYInflationCouponPricer : public YoYInflationCouponPricer { + public: + UnitDisplacedBlackYoYInflationCouponPricer( + const Handle& capletVol, + const Handle& nominalTermStructure); +}; + +%shared_ptr(BachelierYoYInflationCouponPricer) +class BachelierYoYInflationCouponPricer : public YoYInflationCouponPricer { + public: + BachelierYoYInflationCouponPricer( + const Handle& capletVol, + const Handle& nominalTermStructure); +}; + // inflation instruments From d63083d310e66f79196893af5a6aaa0adb6257ed Mon Sep 17 00:00:00 2001 From: AndLLA <44858649+AndLLA@users.noreply.github.com> Date: Sun, 13 Nov 2022 17:03:13 +0100 Subject: [PATCH 115/322] add swap to R demos --- R/demo/swap.R | 340 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 340 insertions(+) create mode 100644 R/demo/swap.R diff --git a/R/demo/swap.R b/R/demo/swap.R new file mode 100644 index 0000000000..942559d316 --- /dev/null +++ b/R/demo/swap.R @@ -0,0 +1,340 @@ + +# inspired by python example with the same name + +suppressMessages(library(QuantLib)) + +## global data +calendar <- TARGET() + +todaysDate <- DateParser_parseISO("2001-09-06") +invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) + +settlementDate <- DateParser_parseISO("2001-09-08") + +cat('Today : ', Date_ISO(todaysDate), "\n") +cat('Settlement Date: ', Date_ISO(settlementDate), "\n") + + +# ### Market quotes + +# %% +deposits = list( + "3M" = 0.0363 +) + +# %% +FRAs = list( + "3x6" = 0.037125, + "6x9" = 0.037125, + "9x12" =0.037125 +) + + +# %% +futures = list( + "2001-12-19" = 96.2875, + "2002-03-20" = 96.7875, + "2002-06-19" = 96.9875, + "2002-09-18" = 96.6875, + "2002-12-18" = 96.4875, + "2003-03-19" = 96.3875, + "2003-06-18" = 96.2875, + "2003-09-17" = 96.0875 +) + +# %% +swaps = list( +# "2Y" = 0.037125, + "3Y" = 0.0398, + "5Y" = 0.0443, + "10Y" = 0.05165, + "15Y" = 0.055175 + +) + +allHelpers_DepoFutSwap = RateHelperVector() +allHelpers_DepoFraSwap = RateHelperVector() + +# Rate Helpers - Depos + +for (it in names(deposits)) { + itVal = deposits[[it]] + + dayCounter = Actual360() + settlementDays = 2 + + dh = DepositRateHelper( + QuoteHandle(SimpleQuote(itVal)), + PeriodParser_parse(it), + settlementDays, + calendar, + "ModifiedFollowing", + F, + dayCounter + ) + + RateHelperVector_append(allHelpers_DepoFutSwap, dh) + RateHelperVector_append(allHelpers_DepoFraSwap, dh) +} + +# Rate Helpers - FRAs + +for (it in names(FRAs)) { + itVal = FRAs[[it]] + + itSplit = strsplit(x = it, split = "x", fixed = T)[[1]] + n = as.numeric(itSplit[1]) + m = as.numeric(itSplit[2]) + + dayCounter = Actual360() + months = 3 + settlementDays = 2 + + dh = FraRateHelper( + QuoteHandle(SimpleQuote(itVal)), n, m, settlementDays, calendar, "ModifiedFollowing", F, dayCounter + ) + + RateHelperVector_append(allHelpers_DepoFraSwap, dh) +} + + +# Rate Helpers - Futures + +for (it in names(futures)) { + itVal = futures[[it]] + + dayCounter = Actual360() + months = 3 + settlementDays = 2 + + dh = FuturesRateHelper( + QuoteHandle(SimpleQuote(itVal)), + DateParser_parseISO(it), + months, + calendar, + "ModifiedFollowing", + T, + dayCounter, + QuoteHandle(SimpleQuote(0.0)) + ) + + RateHelperVector_append(allHelpers_DepoFutSwap, dh) +} + + +# +# The discount curve for the swaps will come from elsewhere. +# -> A real application would use some kind of risk-free curve; here we're using a flat one for convenience. +# + +# %% +discountTermStructure = YieldTermStructureHandle(FlatForward(settlementDate, 0.04, Actual360())) + +# %% +settlementDays = 2 +fixedLegFrequency = "Annual" +fixedLegTenor = PeriodParser_parse("1Y") +fixedLegAdjustment = "Unadjusted" +fixedLegDayCounter = Thirty360(Thirty360_BondBasis_get()) +floatingLegFrequency = "Quarterly" +floatingLegTenor = PeriodParser_parse("3M") +floatingLegAdjustment = "ModifiedFollowing" + +for (it in names(swaps)) { + itVal = swaps[[it]] + + dh = SwapRateHelper( + QuoteHandle(SimpleQuote(itVal)), + PeriodParser_parse(it), + calendar, + fixedLegFrequency, + fixedLegAdjustment, + fixedLegDayCounter, + Euribor3M(), + QuoteHandle(), + PeriodParser_parse("0D"), + discountTermStructure + ) + + RateHelperVector_append(allHelpers_DepoFutSwap, dh) + RateHelperVector_append(allHelpers_DepoFraSwap, dh) +} + +# ### Term structure construction + +printCurve <- function(curve, helpers) { + df = NULL + for (i in seq(1, helpers$size())) { + h = helpers[i][[1]] + pillar = RateHelper_pillarDate(h) + + day_counter = Actual365Fixed() + compounding = "Continuous" + + r = YieldTermStructure_zeroRate(curve, pillar, day_counter, compounding, "Annual") + + df = rbind(df, data.frame( + pillar=Date_ISO(pillar), zeroRate=InterestRate_rate(r)*100.0 + )) + } + print(df) +} + + +# %% +forecastTermStructure = RelinkableYieldTermStructureHandle() + +# %% +depoFuturesSwapCurve = PiecewiseFlatForward(settlementDate, allHelpers_DepoFutSwap, Actual360()) +printCurve(depoFuturesSwapCurve, allHelpers_DepoFutSwap) + +# %% +depoFraSwapCurve = PiecewiseFlatForward(settlementDate, allHelpers_DepoFraSwap, Actual360()) +printCurve(depoFraSwapCurve, allHelpers_DepoFraSwap) + + + +# ### Swap pricing + +# %% +swapEngine = DiscountingSwapEngine(discountTermStructure) + +# %% +nominal = 1000000 +length = 5 +maturity = Calendar_advance(calendar, settlementDate, length, "Years") +payFixed = T + +# %% +fixedLegFrequency = "Annual" +fixedLegAdjustment = "Unadjusted" +fixedLegDayCounter = Thirty360(Thirty360_BondBasis_get()) +fixedRate = 0.04 + +# %% +floatingLegFrequency = "Quarterly" +spread = 0.0 +fixingDays = 2 +index = Euribor3M(forecastTermStructure) +floatingLegAdjustment = "ModifiedFollowing" +floatingLegDayCounter = index$dayCounter() + +# %% +fixedSchedule = Schedule( + settlementDate, + maturity, + fixedLegTenor, + calendar, + fixedLegAdjustment, + fixedLegAdjustment, + DateGeneration_Forward_get(), + F +) +floatingSchedule = Schedule( + settlementDate, + maturity, + floatingLegTenor, + calendar, + floatingLegAdjustment, + floatingLegAdjustment, + DateGeneration_Forward_get(), + F +) + +# We'll build a 5-years swap starting spot... + +# %% +spot = VanillaSwap( + Swap_Payer_get(), + nominal, + fixedSchedule, + fixedRate, + fixedLegDayCounter, + floatingSchedule, + index, + spread, + floatingLegDayCounter +) +spot$setPricingEngine(swapEngine) + + + +# ...and one starting 1 year forward. + +# %% +forwardStart = Calendar_advance(calendar, settlementDate, 1, "Years") +forwardEnd = Calendar_advance(calendar, forwardStart, length, "Years") +fixedSchedule = Schedule( + forwardStart, + forwardEnd, + fixedLegTenor, + calendar, + fixedLegAdjustment, + fixedLegAdjustment, + DateGeneration_Forward_get(), + F +) +floatingSchedule = Schedule( + forwardStart, + forwardEnd, + floatingLegTenor, + calendar, + floatingLegAdjustment, + floatingLegAdjustment, + DateGeneration_Forward_get(), + F +) + +# %% +forward = VanillaSwap( + Swap_Payer_get(), + nominal, + fixedSchedule, + fixedRate, + fixedLegDayCounter, + floatingSchedule, + index, + spread, + floatingLegDayCounter +) +forward$setPricingEngine(swapEngine) + + +# We'll price them both on the bootstrapped curves. +# +# This is the quoted 5-years market rate; we expect the fair rate of the spot swap to match it. + +# %% +print(swaps["5Y"]) + +showSwap <- function(swap) { + print(paste("NPV = ", swap$NPV())) + print(paste("Fair spread = ", (swap$fairSpread()*100))) + print(paste("Fair rate = ", (swap$fairRate()*100))) +} + + +# %% [markdown] +# These are the results for the 5-years spot swap on the deposit/futures/swap curve... + +# %% +forecastTermStructure$linkTo(depoFuturesSwapCurve) +showSwap(spot) + +# ...and these are on the deposit/fra/swap curve. + +# %% +forecastTermStructure$linkTo(depoFraSwapCurve) +showSwap(spot) + +# %% [markdown] +# The same goes for the 1-year forward swap, except for the fair rate not matching the spot rate. + +# %% +forecastTermStructure$linkTo(depoFuturesSwapCurve) +showSwap(forward) + +# %% +forecastTermStructure$linkTo(depoFraSwapCurve) +showSwap(forward) + From 7aea2e1e98815cc404ab58cafbdab045e270d9ae Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Tue, 15 Nov 2022 16:16:59 +0100 Subject: [PATCH 116/322] Add hook in setup.py to select runtime via environment variable --- Python/setup.py | 4 ++-- Python/setup.py.in | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/setup.py b/Python/setup.py index c8eff560f2..f1f351c890 100644 --- a/Python/setup.py +++ b/Python/setup.py @@ -145,12 +145,12 @@ def finalize_options(self): extra_link_args = ['/subsystem:windows', machinetype] if self.debug: - if self.static: + if self.static or 'QL_STATIC_RUNTIME' in os.environ: extra_compile_args.append('/MTd') else: extra_compile_args.append('/MDd') else: - if self.static: + if self.static or 'QL_STATIC_RUNTIME' in os.environ: extra_compile_args.append('/MT') else: extra_compile_args.append('/MD') diff --git a/Python/setup.py.in b/Python/setup.py.in index 69c5d814dc..c175828e5a 100644 --- a/Python/setup.py.in +++ b/Python/setup.py.in @@ -145,12 +145,12 @@ class my_build_ext(build_ext): extra_link_args = ['/subsystem:windows', machinetype] if self.debug: - if self.static: + if self.static or 'QL_STATIC_RUNTIME' in os.environ: extra_compile_args.append('/MTd') else: extra_compile_args.append('/MDd') else: - if self.static: + if self.static or 'QL_STATIC_RUNTIME' in os.environ: extra_compile_args.append('/MT') else: extra_compile_args.append('/MD') From 04a1eeee71d7034cf76f603d3a657e8b4b2a8f99 Mon Sep 17 00:00:00 2001 From: AndLLA <44858649+AndLLA@users.noreply.github.com> Date: Wed, 16 Nov 2022 20:22:17 +0100 Subject: [PATCH 117/322] fix reporting for swap --- R/demo/swap.R | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/R/demo/swap.R b/R/demo/swap.R index 942559d316..7e6e300a2f 100644 --- a/R/demo/swap.R +++ b/R/demo/swap.R @@ -9,7 +9,8 @@ calendar <- TARGET() todaysDate <- DateParser_parseISO("2001-09-06") invisible(Settings_instance()$setEvaluationDate(d=todaysDate)) -settlementDate <- DateParser_parseISO("2001-09-08") +settlementDays = 2 +settlementDate = Calendar_advance(calendar, todaysDate, settlementDays, "Days") cat('Today : ', Date_ISO(todaysDate), "\n") cat('Settlement Date: ', Date_ISO(settlementDate), "\n") @@ -61,7 +62,6 @@ for (it in names(deposits)) { itVal = deposits[[it]] dayCounter = Actual360() - settlementDays = 2 dh = DepositRateHelper( QuoteHandle(SimpleQuote(itVal)), @@ -88,8 +88,7 @@ for (it in names(FRAs)) { dayCounter = Actual360() months = 3 - settlementDays = 2 - + dh = FraRateHelper( QuoteHandle(SimpleQuote(itVal)), n, m, settlementDays, calendar, "ModifiedFollowing", F, dayCounter ) @@ -105,8 +104,7 @@ for (it in names(futures)) { dayCounter = Actual360() months = 3 - settlementDays = 2 - + dh = FuturesRateHelper( QuoteHandle(SimpleQuote(itVal)), DateParser_parseISO(it), @@ -131,7 +129,7 @@ for (it in names(futures)) { discountTermStructure = YieldTermStructureHandle(FlatForward(settlementDate, 0.04, Actual360())) # %% -settlementDays = 2 + fixedLegFrequency = "Annual" fixedLegTenor = PeriodParser_parse("1Y") fixedLegAdjustment = "Unadjusted" @@ -167,14 +165,15 @@ printCurve <- function(curve, helpers) { for (i in seq(1, helpers$size())) { h = helpers[i][[1]] pillar = RateHelper_pillarDate(h) - + day_counter = Actual365Fixed() compounding = "Continuous" r = YieldTermStructure_zeroRate(curve, pillar, day_counter, compounding, "Annual") + disc = YieldTermStructure_discount(curve, pillar) df = rbind(df, data.frame( - pillar=Date_ISO(pillar), zeroRate=InterestRate_rate(r)*100.0 + pillar=Date_ISO(pillar), zeroRate=InterestRate_rate(r)*100.0, df=disc, impliedRate=RateHelper_impliedQuote(h) )) } print(df) @@ -188,6 +187,7 @@ forecastTermStructure = RelinkableYieldTermStructureHandle() depoFuturesSwapCurve = PiecewiseFlatForward(settlementDate, allHelpers_DepoFutSwap, Actual360()) printCurve(depoFuturesSwapCurve, allHelpers_DepoFutSwap) + # %% depoFraSwapCurve = PiecewiseFlatForward(settlementDate, allHelpers_DepoFraSwap, Actual360()) printCurve(depoFraSwapCurve, allHelpers_DepoFraSwap) @@ -209,7 +209,7 @@ payFixed = T fixedLegFrequency = "Annual" fixedLegAdjustment = "Unadjusted" fixedLegDayCounter = Thirty360(Thirty360_BondBasis_get()) -fixedRate = 0.04 +fixedRate = swaps[["5Y"]] # 0.04 # %% floatingLegFrequency = "Quarterly" From 5691b876405d7238fbe80605add3e17e9ee68295 Mon Sep 17 00:00:00 2001 From: klausspanderen Date: Sat, 19 Nov 2022 11:44:06 +0100 Subject: [PATCH 118/322] added Andreasen-Huge local volatility test case --- Python/test/QuantLibTestSuite.py | 3 +- Python/test/volatilities.py | 60 ++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/Python/test/QuantLibTestSuite.py b/Python/test/QuantLibTestSuite.py index 66ec4210be..c9b3c4914e 100644 --- a/Python/test/QuantLibTestSuite.py +++ b/Python/test/QuantLibTestSuite.py @@ -45,7 +45,7 @@ from extrapolation import ExtrapolationTest from fdm import FdmTest from swaption import SwaptionTest -from volatilities import SviSmileSectionTest, SwaptionVolatilityCubeTest +from volatilities import SviSmileSectionTest, SwaptionVolatilityCubeTest, AndreasenHugeVolatilityTest from inflation import InflationTest from coupons import ( CashFlowsTest, @@ -101,6 +101,7 @@ def test(): suite.addTest(unittest.makeSuite(ZeroCouponSwapTest, "test")) suite.addTest(unittest.makeSuite(CurrencyTest, "test")) suite.addTest(unittest.makeSuite(SviSmileSectionTest, "test")) + suite.addTest(unittest.makeSuite(AndreasenHugeVolatilityTest, "test")) result = unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/Python/test/volatilities.py b/Python/test/volatilities.py index 2086e87eab..e5bacc389b 100644 --- a/Python/test/volatilities.py +++ b/Python/test/volatilities.py @@ -17,6 +17,7 @@ """ import unittest +import math import QuantLib as ql @@ -564,9 +565,68 @@ def test_svi_interpolated_smile_section(self): self.assertAlmostEqual(interpolated_smile.volatility(257.328), 0.739775, places=5) +class AndreasenHugeVolatilityTest(unittest.TestCase): + def testLocalVolCalibration(self): + """ Testing Andreasen-Huge Local Volatility calibration""" + + today = ql.Date.todaysDate() + ql.Settings.instance().evaluationDate = today + + spot = ql.QuoteHandle(ql.SimpleQuote(100)) + + dc = ql.Actual365Fixed() + qTS = ql.YieldTermStructureHandle(ql.FlatForward(today, 0.025, dc)) + rTS = ql.YieldTermStructureHandle(ql.FlatForward(today, 0.05, dc)) + + vol_data = [ + # maturity in days, strike, volatility + (30, 75, 0.13), + (30, 100, 0.26), + (30, 125, 0.3), + (180, 80, 0.4), + (180, 150, 0.6), + (365, 110, 0.5)] + + calibration_set = ql.CalibrationSet( + [( + ql.VanillaOption( + ql.PlainVanillaPayoff(ql.Option.Call, strike), + ql.EuropeanExercise(today + ql.Period(maturity_in_days, ql.Days)) + ), + ql.SimpleQuote(volatility) + ) for maturity_in_days, strike, volatility in vol_data] + ) + + local_vol = ql.LocalVolTermStructureHandle( + ql.AndreasenHugeLocalVolAdapter( + ql.AndreasenHugeVolatilityInterpl(calibration_set, spot, rTS, qTS) + ) + ) + + option = calibration_set[-2][0] # maturity in days: 180, strike: 150, vol: 0.6 + + dummy_vol = ql.BlackVolTermStructureHandle() + local_vol_process = ql.GeneralizedBlackScholesProcess(spot, qTS, rTS, dummy_vol, local_vol) + + option.setPricingEngine(ql.MCEuropeanEngine( + local_vol_process, "lowdiscrepancy", + timeSteps=75, brownianBridge=True, requiredSamples=16000, seed=42) + ) + + t = dc.yearFraction(today, option.exercise().lastDate()) + fwd = spot.value() * qTS.discount(t) / rTS.discount(t) + vol = calibration_set[-2][1].value() + + expected = ql.BlackCalculator( + ql.as_plain_vanilla_payoff(option.payoff()), fwd, vol * math.sqrt(t), rTS.discount(t)).value() + + self.assertAlmostEqual(expected, option.NPV(), delta=0.2) + + if __name__ == "__main__": print("testing QuantLib " + ql.__version__) suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(SwaptionVolatilityCubeTest, "test")) suite.addTest(unittest.makeSuite(SviSmileSectionTest, "test")) + suite.addTest(unittest.makeSuite(AndreasenHugeVolatilityTest, "test")) unittest.TextTestRunner(verbosity=2).run(suite) From 0e089acb87e9c636cd33714e2713be90bf85ceea Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Wed, 23 Nov 2022 13:08:54 +0100 Subject: [PATCH 119/322] Enabled autodoc feature in Python --- SWIG/quantlib.i | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/SWIG/quantlib.i b/SWIG/quantlib.i index 595de750f0..4d254bde92 100644 --- a/SWIG/quantlib.i +++ b/SWIG/quantlib.i @@ -89,8 +89,8 @@ import java.lang.AutoCloseable; %typemap(javafinalize) SWIGTYPE %{%} #endif -//#if defined(SWIGPYTHON) -//%feature("autodoc"); -//#endif +#if defined(SWIGPYTHON) +%feature("autodoc"); +#endif %include ql.i From 4b233a714aae28b591771708d98ce8204cfde448 Mon Sep 17 00:00:00 2001 From: Luigi Ballabio Date: Wed, 30 Nov 2022 13:13:09 +0100 Subject: [PATCH 120/322] Added a number of LMM-related classes --- SWIG/lmm.i | 339 +++++++++++++++++++++++++++++++++++++++++++ SWIG/ql.i | 1 + SWIG/randomnumbers.i | 69 +++++++++ SWIG/slv.i | 33 +---- SWIG/vectors.i | 5 +- 5 files changed, 413 insertions(+), 34 deletions(-) create mode 100644 SWIG/lmm.i diff --git a/SWIG/lmm.i b/SWIG/lmm.i new file mode 100644 index 0000000000..b1d568b50b --- /dev/null +++ b/SWIG/lmm.i @@ -0,0 +1,339 @@ +/* + Copyright (C) 2022 StatPro Italia srl + + This file is part of QuantLib, a free-software/open-source library + for financial quantitative analysts and developers - http://quantlib.org/ + + QuantLib is free software: you can redistribute it and/or modify it + under the terms of the QuantLib license. You should have received a + copy of the license along with this program; if not, please email + . The license is also available online at + . + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the license for more details. +*/ + +#ifndef quantlib_lmm_i +#define quantlib_lmm_i + +%include common.i +%include types.i +%include vectors.i +%include linearalgebra.i +%include randomnumbers.i + +%{ +using QuantLib::EvolutionDescription; +%} + +class EvolutionDescription { + public: + %extend { + EvolutionDescription( + const std::vector