File: fdmhestonfwdop.cpp

package info (click to toggle)
quantlib 1.41-1
  • 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 (230 lines) | stat: -rw-r--r-- 9,741 bytes parent folder | download | duplicates (2)
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
226
227
228
229
230
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2012, 2013 Klaus Spanderen
 Copyright (C) 2014 Johannes Göttker-Schnetmann

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

/*! \file fdmhestonfwdop.cpp
*/

#include <ql/methods/finitedifferences/operators/fdmhestonfwdop.hpp>
#include <ql/methods/finitedifferences/operators/modtriplebandlinearop.hpp>
#include <ql/methods/finitedifferences/meshers/fdmmesher.hpp>
#include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp>
#include <ql/methods/finitedifferences/operators/firstderivativeop.hpp>
#include <ql/methods/finitedifferences/operators/secondderivativeop.hpp>
#include <ql/methods/finitedifferences/operators/secondordermixedderivativeop.hpp>
#include <ql/processes/hestonprocess.hpp>
#include <cmath>
#include <utility>

using std::exp;

namespace QuantLib {

    FdmHestonFwdOp::FdmHestonFwdOp(const ext::shared_ptr<FdmMesher>& mesher,
                                   const ext::shared_ptr<HestonProcess>& process,
                                   FdmSquareRootFwdOp::TransformationType type,
                                   ext::shared_ptr<LocalVolTermStructure> leverageFct,
                                   const Real mixingFactor)
    : type_(type), kappa_(process->kappa()), theta_(process->theta()), sigma_(process->sigma()),
      rho_(process->rho()), v0_(process->v0()), mixedSigma_(mixingFactor * sigma_),
      rTS_(process->riskFreeRate().currentLink()), qTS_(process->dividendYield().currentLink()),
      varianceValues_(0.5 * mesher->locations(1)),
      dxMap_(ext::make_shared<FirstDerivativeOp>(0, mesher)),
      dxxMap_(ext::make_shared<ModTripleBandLinearOp>(TripleBandLinearOp(
          type == FdmSquareRootFwdOp::Log ?
              SecondDerivativeOp(0, mesher).mult(0.5 * Exp(mesher->locations(1))) :
              SecondDerivativeOp(0, mesher).mult(0.5 * mesher->locations(1))))),
      boundary_(ext::make_shared<ModTripleBandLinearOp>(TripleBandLinearOp(
          SecondDerivativeOp(0, mesher).mult(Array(mesher->locations(0).size(), 0.0))))),
      mapX_(ext::make_shared<TripleBandLinearOp>(0, mesher)),
      mapY_(ext::make_shared<FdmSquareRootFwdOp>(mesher, kappa_, theta_, mixedSigma_, 1, type)),
      correlation_(ext::make_shared<NinePointLinearOp>(
          type == FdmSquareRootFwdOp::Log ?
              SecondOrderMixedDerivativeOp(0, 1, mesher)
                  .mult(Array(mesher->layout()->size(), rho_ * mixedSigma_)) :
              SecondOrderMixedDerivativeOp(0, 1, mesher)
                  .mult(rho_ * mixedSigma_ * mesher->locations(1)))),
      leverageFct_(std::move(leverageFct)), mesher_(mesher) {
        // zero flux boundary condition
        const Size n = mesher->layout()->dim()[1];
        const Real lowerBoundaryFactor = mapY_->lowerBoundaryFactor(type);
        const Real upperBoundaryFactor = mapY_->upperBoundaryFactor(type);

        const Real logFacLow = type == FdmSquareRootFwdOp::Log ? Real(exp(mapY_->v(0))) : 1.0;
        const Real logFacUpp = type == FdmSquareRootFwdOp::Log ? Real(exp(mapY_->v(n+1))) : 1.0;

        const Real alpha = -2*rho_/mixedSigma_*lowerBoundaryFactor*logFacLow;
        const Real beta  = -2*rho_/mixedSigma_*upperBoundaryFactor*logFacUpp;

        ModTripleBandLinearOp fDx(FirstDerivativeOp(0, mesher));

        for (const auto& iter : *mesher->layout()) {
            if (iter.coordinates()[1] == 0) {
                const Size idx = iter.index();
                if (!leverageFct_) {
                    dxxMap_->upper(idx) += alpha*fDx.upper(idx);
                    dxxMap_->diag(idx) += alpha*fDx.diag(idx);
                    dxxMap_->lower(idx) += alpha*fDx.lower(idx);
                }
                boundary_->upper(idx)= alpha*fDx.upper(idx);
                boundary_->diag(idx) = alpha*fDx.diag(idx);
                boundary_->lower(idx) = alpha*fDx.lower(idx);
            }
            else if (iter.coordinates()[1] == n-1) {
                const Size idx = iter.index();

                if (!leverageFct_) {
                    dxxMap_->upper(idx)+= beta*fDx.upper(idx);
                    dxxMap_->diag(idx) += beta*fDx.diag(idx);
                    dxxMap_->lower(idx) += beta*fDx.lower(idx);
                }
                boundary_->upper(idx)= beta*fDx.upper(idx);
                boundary_->diag(idx) = beta*fDx.diag(idx);
                boundary_->lower(idx) = beta*fDx.lower(idx);
            }
        }
    }

    Size FdmHestonFwdOp::size() const {
        return 2;
    }

    void FdmHestonFwdOp::setTime(Time t1, Time t2){
        const Rate r = rTS_->forwardRate(t1, t2, Continuous).rate();
        const Rate q = qTS_->forwardRate(t1, t2, Continuous).rate();
        if (leverageFct_ != nullptr) {
            L_ = getLeverageFctSlice(t1, t2);
            Array Lsquare = L_*L_;
            if (type_ == FdmSquareRootFwdOp::Plain) {
                mapX_->axpyb( Array(1, -r + q), *dxMap_,
                    dxxMap_->multR(Lsquare).add(boundary_->multR(L_))
                    .add(dxMap_->multR(rho_*mixedSigma_*L_))
                    .add(dxMap_->mult(varianceValues_).multR(Lsquare)),
                              Array());
            } else if (type_ == FdmSquareRootFwdOp::Power) {
                mapX_->axpyb( Array(1, -r + q), *dxMap_,
                    dxxMap_->multR(Lsquare).add(boundary_->multR(L_))
                    .add(dxMap_->multR(rho_*2.0*kappa_*theta_/(mixedSigma_)*L_))
                    .add(dxMap_->mult(varianceValues_).multR(Lsquare)), Array());
            } else if (type_ == FdmSquareRootFwdOp::Log) {
                mapX_->axpyb( Array(1, -r + q), *dxMap_,
                    dxxMap_->multR(Lsquare).add(boundary_->multR(L_))
                    .add(dxMap_->mult(0.5*Exp(2.0*varianceValues_)).multR(Lsquare)),
                              Array());
            }
        } else {
            if (type_ == FdmSquareRootFwdOp::Plain) {
                mapX_->axpyb( - r + q + rho_*mixedSigma_ + varianceValues_, *dxMap_,
                        *dxxMap_, Array());
            } else if (type_ == FdmSquareRootFwdOp::Power) {
                mapX_->axpyb( - r + q + rho_*2.0*kappa_*theta_/(mixedSigma_) + varianceValues_,
                              *dxMap_, *dxxMap_, Array());
            } else if (type_ == FdmSquareRootFwdOp::Log) {
                mapX_->axpyb( - r + q + 0.5*Exp(2.0*varianceValues_), *dxMap_,
                        *dxxMap_, Array());
            }
        }
    }

    Array FdmHestonFwdOp::apply(const Array& u) const {
        if (leverageFct_ != nullptr) {
            return mapX_->apply(u)
                    + mapY_->apply(u)
                    + correlation_->apply(L_*u);
        } else {
            return mapX_->apply(u)
                    + mapY_->apply(u)
                    + correlation_->apply(u);
        }
    }

    Array FdmHestonFwdOp::apply_mixed(const Array& u) const{
        if (leverageFct_ != nullptr) {
            return correlation_->apply(L_*u);
        } else {
            return correlation_->apply(u);
        }
    }

    Array FdmHestonFwdOp::apply_direction(
        Size direction, const Array& u) const {

        if (direction == 0)
            return mapX_->apply(u) ;
        else if (direction == 1)
            return mapY_->apply(u) ;
        else
            QL_FAIL("direction too large");
    }

    Array FdmHestonFwdOp::solve_splitting(
        Size direction, const Array& u, Real s) const{
        if (direction == 0) {
            return mapX_->solve_splitting(u, s, 1.0);
        }
        else if (direction == 1) {
            return mapY_->solve_splitting(1, u, s);
        }
        else
            QL_FAIL("direction too large");
    }

    Array FdmHestonFwdOp::preconditioner(
        const Array& u, Real dt) const{
        return solve_splitting(1, u, dt);
    }

    Array FdmHestonFwdOp::getLeverageFctSlice(Time t1, Time t2) const {
        Array v(mesher_->layout()->size(), 1.0);

        if (!leverageFct_)
            return v;

        const Real t = 0.5*(t1+t2);
        const Time time = std::min(leverageFct_->maxTime(), t);
                                   //std::max(leverageFct_->minTime(), t));

        for (const auto& iter : *mesher_->layout()) {
            const Size nx = iter.coordinates()[0];

            if (iter.coordinates()[1] == 0) {
                const Real x = std::exp(mesher_->location(iter, 0));
                const Real spot = std::min(leverageFct_->maxStrike(),
                                           std::max(leverageFct_->minStrike(), x));
                v[nx] = std::max(0.01, leverageFct_->localVol(time, spot, true));
            }
            else {
                v[iter.index()] = v[nx];
            }
        }
        return v;
    }

    std::vector<SparseMatrix> FdmHestonFwdOp::toMatrixDecomp() const {

        std::vector<SparseMatrix> retVal(3);

        retVal[0] = mapX_->toMatrix();
        retVal[1] = mapY_->toMatrix();
        retVal[2] = correlation_->toMatrix();

        return retVal;
    }

}