File: analyticdoublebarrierbinaryengine.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 (307 lines) | stat: -rw-r--r-- 11,952 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2015 Thema Consulting SA

 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/pricingengines/barrier/analyticdoublebarrierbinaryengine.hpp>
#include <utility>

using std::fabs;

namespace QuantLib {

   // number of iterations ...
   static Real PI= 3.14159265358979323846264338327950;

    // calc helper object 
    class AnalyticDoubleBarrierBinaryEngine_helper
    {
    
    public:
        AnalyticDoubleBarrierBinaryEngine_helper(
             const ext::shared_ptr<GeneralizedBlackScholesProcess>& process,
             const ext::shared_ptr<CashOrNothingPayoff> &payoff,
             const DoubleBarrierOption::arguments &arguments):
        process_(process),
        payoff_(payoff),
        arguments_(arguments)
        {
        }

        Real payoffAtExpiry(Real spot, Real variance,
                            DoubleBarrier::Type barrierType,
                            Size maxIteration = 100,
                            Real requiredConvergence = 1e-8);
        Real payoffKIKO(Real spot, Real variance,
                        DoubleBarrier::Type barrierType,
                        Size maxIteration = 1000,
                        Real requiredConvergence = 1e-8);

    private:

        const ext::shared_ptr<GeneralizedBlackScholesProcess>& process_;
        const ext::shared_ptr<CashOrNothingPayoff> &payoff_;
        const DoubleBarrierOption::arguments &arguments_;
    };


    // helper object methods
    Real AnalyticDoubleBarrierBinaryEngine_helper::payoffAtExpiry(
         Real spot, Real variance, DoubleBarrier::Type barrierType,
         Size maxIteration, Real requiredConvergence)
    {
        QL_REQUIRE(spot>0.0,
                   "positive spot value required");

        QL_REQUIRE(variance>=0.0,
                   "negative variance not allowed");

        Time residualTime = process_->time(arguments_.exercise->lastDate());
        QL_REQUIRE(residualTime>0.0,
                   "expiration time must be > 0");

        // Option::Type type   = payoff_->optionType(); // this is not used ?
        Real cash = payoff_->cashPayoff();
        Real barrier_lo = arguments_.barrier_lo;
        Real barrier_hi = arguments_.barrier_hi;

        Real sigmaq = variance/residualTime;
        Real r = process_->riskFreeRate()->zeroRate(residualTime, Continuous,
                                             NoFrequency);
        Real q = process_->dividendYield()->zeroRate(residualTime,
                                                   Continuous, NoFrequency);
        Real b = r - q;

        Real alpha = -0.5 * ( 2*b/sigmaq - 1);
        Real beta = -0.25 * std::pow(( 2*b/sigmaq - 1), 2) - 2 * r/sigmaq;
        Real Z = std::log(barrier_hi / barrier_lo);
        Real factor = ((2*PI*cash)/std::pow(Z,2)); // common factor
        Real lo_alpha = std::pow(spot/barrier_lo, alpha); 
        Real hi_alpha = std::pow(spot/barrier_hi, alpha); 

        Real tot = 0, term = 0;
        for (Size i = 1 ; i < maxIteration ; ++i)
        {
           Real term1 = (lo_alpha-std::pow(-1.0, (int)i)*hi_alpha) /
                              (std::pow(alpha,2)+std::pow(i*PI/Z, 2));
           Real term2 = std::sin(i*PI/Z * std::log(spot/barrier_lo));
           Real term3 = std::exp(-0.5*(std::pow(i*PI/Z,2)-beta)*variance);
           term = factor * i * term1 * term2 * term3;
           tot += term;
        }

        // Check if convergence is sufficiently fast (for extreme parameters with big alpha the convergence can be very
        // poor, see for example Hui "One-touch double barrier binary option value")
        QL_REQUIRE(std::fabs(term) < requiredConvergence, "serie did not converge sufficiently fast");

        if (barrierType == DoubleBarrier::KnockOut)
           return std::max(tot, 0.0); // KO
        else {
           Rate discount = process_->riskFreeRate()->discount(
                                             arguments_.exercise->lastDate());
           QL_REQUIRE(discount>0.0,
                        "positive discount required");
           return std::max(cash * discount - tot, 0.0); // KI
        }
    }

    // helper object methods
    Real AnalyticDoubleBarrierBinaryEngine_helper::payoffKIKO(
         Real spot, Real variance, DoubleBarrier::Type barrierType,
         Size maxIteration, Real requiredConvergence)
    {
        QL_REQUIRE(spot>0.0,
                   "positive spot value required");

        QL_REQUIRE(variance>=0.0,
                   "negative variance not allowed");

        Time residualTime = process_->time(arguments_.exercise->lastDate());
        QL_REQUIRE(residualTime>0.0,
                   "expiration time must be > 0");

        Real cash = payoff_->cashPayoff();
        Real barrier_lo = arguments_.barrier_lo;
        Real barrier_hi = arguments_.barrier_hi;
        if (barrierType == DoubleBarrier::KOKI)
           std::swap(barrier_lo, barrier_hi);

        Real sigmaq = variance/residualTime;
        Real r = process_->riskFreeRate()->zeroRate(residualTime, Continuous,
                                             NoFrequency);
        Real q = process_->dividendYield()->zeroRate(residualTime,
                                                   Continuous, NoFrequency);
        Real b = r - q;

        Real alpha = -0.5 * ( 2*b/sigmaq - 1);
        Real beta = -0.25 * std::pow(( 2*b/sigmaq - 1), 2) - 2 * r/sigmaq;
        Real Z = std::log(barrier_hi / barrier_lo);
        Real log_S_L = std::log(spot / barrier_lo);

        Real tot = 0, term = 0;
        for (Size i = 1 ; i < maxIteration ; ++i)
        {
            Real factor = std::pow(i*PI/Z,2)-beta;
            Real term1 = (beta - std::pow(i*PI/Z,2) * std::exp(-0.5*factor*variance)) / factor;
            Real term2 = std::sin(i * PI/Z * log_S_L);
            term = (2.0/(i*PI)) * term1 * term2;
            tot += term;
        }
        tot += 1 - log_S_L / Z;
        tot *= cash*std::pow(spot/barrier_lo, alpha);

        // Check if convergence is sufficiently fast
        QL_REQUIRE(fabs(term) < requiredConvergence, "serie did not converge sufficiently fast");

        return std::max(tot, 0.0);
    }

    AnalyticDoubleBarrierBinaryEngine::AnalyticDoubleBarrierBinaryEngine(
        ext::shared_ptr<GeneralizedBlackScholesProcess> process)
    : process_(std::move(process)) {
        registerWith(process_);
    }

    void AnalyticDoubleBarrierBinaryEngine::calculate() const {

        if (arguments_.barrierType == DoubleBarrier::KIKO ||
            arguments_.barrierType == DoubleBarrier::KOKI) {
            ext::shared_ptr<AmericanExercise> ex =
                ext::dynamic_pointer_cast<AmericanExercise>(
                                                   arguments_.exercise);
            QL_REQUIRE(ex, "KIKO/KOKI options must have American exercise");
            QL_REQUIRE(ex->dates()[0] <=
                       process_->blackVolatility()->referenceDate(),
                       "American option with window exercise not handled yet");
        } else {
            ext::shared_ptr<EuropeanExercise> ex =
                ext::dynamic_pointer_cast<EuropeanExercise>(
                                                   arguments_.exercise);
            QL_REQUIRE(ex, "non-European exercise given");
        }
        ext::shared_ptr<CashOrNothingPayoff> payoff =
            ext::dynamic_pointer_cast<CashOrNothingPayoff>(arguments_.payoff);
        QL_REQUIRE(payoff, "a cash-or-nothing payoff must be given");

        Real spot = process_->stateVariable()->value();
        QL_REQUIRE(spot > 0.0, "negative or null underlying given");

        Real variance =
            process_->blackVolatility()->blackVariance(
                                             arguments_.exercise->lastDate(),
                                             payoff->strike());
        Real barrier_lo = arguments_.barrier_lo;
        Real barrier_hi = arguments_.barrier_hi;
        DoubleBarrier::Type barrierType = arguments_.barrierType;
        QL_REQUIRE(barrier_lo>0.0,
                   "positive low barrier value required");
        QL_REQUIRE(barrier_hi>0.0,
                   "positive high barrier value required");
        QL_REQUIRE(barrier_lo < barrier_hi,
                   "barrier_lo must be < barrier_hi");
        QL_REQUIRE(barrierType == DoubleBarrier::KnockIn ||
                   barrierType == DoubleBarrier::KnockOut ||
                   barrierType == DoubleBarrier::KIKO ||
                   barrierType == DoubleBarrier::KOKI,
                   "Unsupported barrier type");

        // degenerate cases
        switch (barrierType) {
          case DoubleBarrier::KnockOut:
            if (spot <= barrier_lo || spot >= barrier_hi) {
                // knocked out, no value
                results_.value = 0;
                results_.delta = 0;
                results_.gamma = 0;
                results_.vega = 0;
                results_.rho = 0;
                return;
            }
            break;

          case DoubleBarrier::KnockIn:
            if (spot <= barrier_lo || spot >= barrier_hi) {
                // knocked in - pays
                results_.value = payoff->cashPayoff();
                results_.delta = 0;
                results_.gamma = 0;
                results_.vega = 0;
                results_.rho = 0;
                return;
            }
            break;

          case DoubleBarrier::KIKO:
            if (spot >= barrier_hi) {
                // knocked out, no value
                results_.value = 0;
                results_.delta = 0;
                results_.gamma = 0;
                results_.vega = 0;
                results_.rho = 0;
                return;
            } else if (spot <= barrier_lo) {
                // knocked in, pays
                results_.value = payoff->cashPayoff();
                results_.delta = 0;
                results_.gamma = 0;
                results_.vega = 0;
                results_.rho = 0;
                return;
            }
            break;

          case DoubleBarrier::KOKI:
            if (spot <= barrier_lo) {
                // knocked out, no value
                results_.value = 0;
                results_.delta = 0;
                results_.gamma = 0;
                results_.vega = 0;
                results_.rho = 0;
                return;
            } else if (spot >= barrier_hi) {
                // knocked in, pays
                results_.value = payoff->cashPayoff();
                results_.delta = 0;
                results_.gamma = 0;
                results_.vega = 0;
                results_.rho = 0;
                return;
            }
            break;
        }

        AnalyticDoubleBarrierBinaryEngine_helper helper(process_,
           payoff, arguments_);
        switch (barrierType)
        {
          case DoubleBarrier::KnockOut:
          case DoubleBarrier::KnockIn:
            results_.value = helper.payoffAtExpiry(spot, variance, barrierType);
            break;

          case DoubleBarrier::KIKO:
          case DoubleBarrier::KOKI:
            results_.value = helper.payoffKIKO(spot, variance, barrierType);
            break;
        }
    }

}