File: fdndimblackscholesvanillaengine.cpp

package info (click to toggle)
quantlib 1.41-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 41,480 kB
  • sloc: cpp: 400,885; makefile: 6,547; python: 214; sh: 150; lisp: 86
file content (225 lines) | stat: -rw-r--r-- 9,429 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2024 Klaus Spanderen

 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
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <https://www.quantlib.org/license.shtml>.

 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.
*/

#include <ql/exercise.hpp>
#include <ql/processes/blackscholesprocess.hpp>
#include <ql/math/matrixutilities/getcovariance.hpp>
#include <ql/math/distributions/normaldistribution.hpp>
#include <ql/math/matrixutilities/symmetricschurdecomposition.hpp>
#include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp>
#include <ql/methods/finitedifferences/meshers/predefined1dmesher.hpp>
#include <ql/methods/finitedifferences/operators/fdmwienerop.hpp>
#include <ql/methods/finitedifferences/solvers/fdmndimsolver.hpp>
#include <ql/methods/finitedifferences/utilities/fdminnervaluecalculator.hpp>
#include <ql/methods/finitedifferences/stepconditions/fdmstepconditioncomposite.hpp>
#include <ql/pricingengines/basket/fdndimblackscholesvanillaengine.hpp>
#include <ql/pricingengines/basket/vectorbsmprocessextractor.hpp>
#include <boost/preprocessor/iteration/local.hpp>
#include <utility>

namespace QuantLib {

    namespace detail {
        class FdmPCABasketInnerValue: public FdmInnerValueCalculator {
          public:
            FdmPCABasketInnerValue(
                ext::shared_ptr<BasketPayoff> payoff,
                ext::shared_ptr<FdmMesher> mesher,
                Array logS0, const Array& vols,
                std::vector<ext::shared_ptr<YieldTermStructure>> qTS,
                ext::shared_ptr<YieldTermStructure> rTS,
                Matrix Q, Array l)
            : n_(logS0.size()),
              payoff_(std::move(payoff)),
              mesher_(std::move(mesher)),
              logS0_(std::move(logS0)), v_(vols*vols),
              qTS_(std::move(qTS)),
              rTS_(std::move(rTS)),
              Q_(std::move(Q)), l_(std::move(l)),
              cachedT_(Null<Real>()),
              qf_(n_) { }

            Real innerValue(const FdmLinearOpIterator& iter, Time t) override {
                if (!close_enough(t, cachedT_)) {
                    rf_ = rTS_->discount(t);
                    for (Size i=0; i < n_; ++i)
                        qf_[i] = qTS_[i]->discount(t);
                }
                Array x(n_);
                for (Size i=0; i < n_; ++i)
                    x[i] = mesher_->location(iter, i);

                const Array S = Exp(Q_*x - 0.5*v_*t + logS0_)*qf_/rf_;

                return (*payoff_)(S);
            }
            Real avgInnerValue(const FdmLinearOpIterator& iter, Time t) override {
                return innerValue(iter, t);
            }

          private:
            const Size n_;
            const ext::shared_ptr<BasketPayoff> payoff_;
            const ext::shared_ptr<FdmMesher> mesher_;
            const Array logS0_, v_;
            const std::vector<ext::shared_ptr<YieldTermStructure>> qTS_;
            const ext::shared_ptr<YieldTermStructure> rTS_;
            const Matrix Q_;
            const Array l_;
            Time cachedT_;
            Array qf_;
            DiscountFactor rf_;
        };
    }

    FdndimBlackScholesVanillaEngine::FdndimBlackScholesVanillaEngine(
        std::vector<ext::shared_ptr<GeneralizedBlackScholesProcess> > processes,
        Matrix rho,
        std::vector<Size> xGrids,
        Size tGrid, Size dampingSteps,
        const FdmSchemeDesc& schemeDesc)
    : processes_(std::move(processes)),
      rho_(std::move(rho)),
      xGrids_(std::move(xGrids)),
      tGrid_(tGrid),
      dampingSteps_(dampingSteps),
      schemeDesc_(schemeDesc) {

        QL_REQUIRE(!processes_.empty(), "no Black-Scholes process is given.");
        QL_REQUIRE(rho_.size1() == rho_.size2()
                && rho_.size1() == processes_.size(),
                "correlation matrix has the wrong size.");
        QL_REQUIRE(xGrids_.size() == 1 || xGrids_.size() == processes_.size(),
                "wrong number of xGrids is given.");

        std::for_each(processes_.begin(), processes_.end(),
            [this](const auto& p) { registerWith(p); });
    }

    FdndimBlackScholesVanillaEngine::FdndimBlackScholesVanillaEngine(
        std::vector<ext::shared_ptr<GeneralizedBlackScholesProcess> > processes,
        Matrix rho, Size xGrid, Size tGrid, Size dampingSteps,
        const FdmSchemeDesc& schemeDesc)
    : FdndimBlackScholesVanillaEngine(
        std::move(processes), std::move(rho), std::vector<Size>(1, xGrid), tGrid, dampingSteps, schemeDesc)
    {}


    void FdndimBlackScholesVanillaEngine::calculate() const {
        #ifndef PDE_MAX_SUPPORTED_DIM
        #define PDE_MAX_SUPPORTED_DIM 4
        #endif
        QL_REQUIRE(processes_.size() <= PDE_MAX_SUPPORTED_DIM,
            "This engine does not support " << processes_.size() << " underlyings. "
            << "Max number of underlyings is " << PDE_MAX_SUPPORTED_DIM << ". "
            << "Please change preprocessor constant PDE_MAX_SUPPORTED_DIM and recompile "
            << "if a larger number of underlyings is needed.");

        const Date maturityDate = arguments_.exercise->lastDate();
        const Time maturity = processes_[0]->time(maturityDate);
        const Real sqrtT = std::sqrt(maturity);

        const detail::VectorBsmProcessExtractor pExtractor(processes_);
        const Array s = pExtractor.getSpot();
        const Array dq = pExtractor.getDividendYieldDf(maturityDate);
        const Array stdDev = Sqrt(pExtractor.getBlackVariance(maturityDate));
        const Array vols = stdDev / sqrtT;

        const SymmetricSchurDecomposition schur(
            getCovariance(vols.begin(), vols.end(), rho_));
        const Matrix& Q = schur.eigenvectors();
        const Array& l = schur.eigenvalues();

        const Real eps = 1e-4;
        std::vector<ext::shared_ptr<Fdm1dMesher> > meshers;

        for (Size i=0; i < processes_.size(); ++i) {
            const Size xGrid = (xGrids_.size() > 1)
                ? xGrids_[i]
                : std::max(Size(4), Size(xGrids_[0]*std::pow(l[i]/l[0], 0.1)));
            QL_REQUIRE(xGrid >= 4, "minimum grid size is four");

            const Real xStepStize = (1.0-2*eps)/(xGrid-1);

            std::vector<Real> x(xGrid);
            for (Size j=0; j < xGrid; ++j)
                x[j] = 1.3*std::sqrt(l[i])*sqrtT
                    *InverseCumulativeNormal()(eps + j*xStepStize);

            meshers.emplace_back(ext::make_shared<Predefined1dMesher>(x));
        }

        const ext::shared_ptr<FdmMesherComposite> mesher =
            ext::make_shared<FdmMesherComposite>(meshers);

        const ext::shared_ptr<BasketPayoff> payoff
            = ext::dynamic_pointer_cast<BasketPayoff>(arguments_.payoff);
        QL_REQUIRE(payoff, "basket payoff expected");

        const ext::shared_ptr<YieldTermStructure> rTS =
            processes_[0]->riskFreeRate().currentLink();

        std::vector<ext::shared_ptr<YieldTermStructure>> qTS(processes_.size());
        for (Size i=0; i < processes_.size(); ++i)
            qTS[i] = processes_[i]->dividendYield().currentLink();

        const ext::shared_ptr<FdmInnerValueCalculator> calculator =
            ext::make_shared<detail::FdmPCABasketInnerValue>(
                payoff, mesher,
                Log(s), stdDev/sqrtT,
                qTS, rTS,
                Q, l
            );

        const ext::shared_ptr<FdmStepConditionComposite> conditions
            = FdmStepConditionComposite::vanillaComposite(
                DividendSchedule(), arguments_.exercise,
                mesher, calculator,
                rTS->referenceDate(), rTS->dayCounter());

        const FdmBoundaryConditionSet boundaries;
        const FdmSolverDesc solverDesc
            = { mesher, boundaries, conditions, calculator,
                maturity, tGrid_, dampingSteps_ };

        const bool isEuropean =
            ext::dynamic_pointer_cast<EuropeanExercise>(arguments_.exercise) != nullptr;
        const ext::shared_ptr<FdmWienerOp> op =
            ext::make_shared<FdmWienerOp>(
                mesher,
                (isEuropean)? ext::shared_ptr<YieldTermStructure>() : rTS,
                l);

        switch(processes_.size()) {
            #define BOOST_PP_LOCAL_MACRO(n) \
                case n : \
                    results_.value = ext::make_shared<FdmNdimSolver<n>>( \
                        solverDesc, schemeDesc_, op)->interpolateAt( \
                            std::vector<Real>(processes_.size(), 0.0)); \
                break;
            #define BOOST_PP_LOCAL_LIMITS (1, PDE_MAX_SUPPORTED_DIM)
            #include BOOST_PP_LOCAL_ITERATE()
          default:
            QL_FAIL("Not implemented for " << processes_.size() << " processes");
        }

        if (isEuropean)
            results_.value *= pExtractor.getInterestRateDf(maturityDate);
    }
}