File: analyticbinarybarrierengine.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 (324 lines) | stat: -rw-r--r-- 11,487 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2014 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/instruments/vanillaoption.hpp>
#include <ql/math/distributions/normaldistribution.hpp>
#include <ql/pricingengines/barrier/analyticbinarybarrierengine.hpp>
#include <ql/pricingengines/vanilla/analyticeuropeanengine.hpp>
#include <utility>

namespace QuantLib {

    // calc helper object 
    class AnalyticBinaryBarrierEngine_helper
    {
    
    public:
        AnalyticBinaryBarrierEngine_helper(
             const ext::shared_ptr<GeneralizedBlackScholesProcess>& process,
             const ext::shared_ptr<StrikedTypePayoff> &payoff,
             const ext::shared_ptr<AmericanExercise> &exercise,
             const BarrierOption::arguments &arguments):
        process_(process),
        payoff_(payoff),
        exercise_(exercise),
        arguments_(arguments)
        {
        }

        Real payoffAtExpiry(Real spot, Real variance, Real discount);
    private:
        const ext::shared_ptr<GeneralizedBlackScholesProcess>& process_;
        const ext::shared_ptr<StrikedTypePayoff> &payoff_;
        const ext::shared_ptr<AmericanExercise> &exercise_;
        const BarrierOption::arguments &arguments_;
    };


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

    void AnalyticBinaryBarrierEngine::calculate() const {

        ext::shared_ptr<AmericanExercise> ex =
            ext::dynamic_pointer_cast<AmericanExercise>(arguments_.exercise);
        QL_REQUIRE(ex, "non-American exercise given");
        QL_REQUIRE(ex->payoffAtExpiry(), "payoff must be at expiry");
        QL_REQUIRE(ex->dates()[0] <=
                   process_->blackVolatility()->referenceDate(),
                   "American option with window exercise not handled yet");

        ext::shared_ptr<StrikedTypePayoff> payoff =
            ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
        QL_REQUIRE(payoff, "non-striked payoff given");

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

        Real variance =
            process_->blackVolatility()->blackVariance(ex->lastDate(),
                                                       payoff->strike());
        Real barrier = arguments_.barrier;
        QL_REQUIRE(barrier>0.0,
                   "positive barrier value required");
        Barrier::Type barrierType = arguments_.barrierType;

        // KO degenerate cases
        if ( (barrierType == Barrier::DownOut && spot <= barrier) ||
             (barrierType == Barrier::UpOut && spot >= barrier))
        {
            // knocked out, no value
            results_.value = 0;
            results_.delta = 0;
            results_.gamma = 0;
            results_.vega = 0;
            results_.theta = 0;
            results_.rho = 0;
            results_.dividendRho = 0;
            return;
        }

        // KI degenerate cases
        if ((barrierType == Barrier::DownIn && spot <= barrier) ||
           (barrierType == Barrier::UpIn && spot >= barrier)) {
            // knocked in - is a digital european
            ext::shared_ptr<Exercise> exercise(new EuropeanExercise(
                                             arguments_.exercise->lastDate()));

            ext::shared_ptr<PricingEngine> engine(
                                       new AnalyticEuropeanEngine(process_));

            VanillaOption opt(payoff, exercise);
            opt.setPricingEngine(engine);
            results_.value = opt.NPV();
            results_.delta = opt.delta();
            results_.gamma = opt.gamma();
            results_.vega = opt.vega();
            results_.theta = opt.theta();
            results_.rho = opt.rho();
            results_.dividendRho = opt.dividendRho();
            return;
        }

        Rate riskFreeDiscount =
            process_->riskFreeRate()->discount(ex->lastDate());

        AnalyticBinaryBarrierEngine_helper helper(process_,
           payoff, ex, arguments_);
        results_.value = helper.payoffAtExpiry(spot, variance, riskFreeDiscount);
    }

    Real AnalyticBinaryBarrierEngine_helper::payoffAtExpiry(
         Real spot, Real variance, Real discount)
    {
        Rate dividendDiscount =
            process_->dividendYield()->discount(exercise_->lastDate());

        QL_REQUIRE(spot>0.0,
                   "positive spot value required");

        QL_REQUIRE(discount>0.0,
                   "positive discount required");

        QL_REQUIRE(dividendDiscount>0.0,
                   "positive dividend discount required");

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

        Option::Type type   = payoff_->optionType();
        Real strike = payoff_->strike();
        Real barrier = arguments_.barrier;
        QL_REQUIRE(barrier>0.0,
                   "positive barrier value required");
        Barrier::Type barrierType = arguments_.barrierType;

        Real stdDev = std::sqrt(variance);
        Real mu = std::log(dividendDiscount/discount)/variance - 0.5;
        Real K = 0;

        // binary cash-or-nothing payoff?
        ext::shared_ptr<CashOrNothingPayoff> coo =
            ext::dynamic_pointer_cast<CashOrNothingPayoff>(payoff_);
        if (coo != nullptr) {
            K = coo->cashPayoff();
        }

        // binary asset-or-nothing payoff?
        ext::shared_ptr<AssetOrNothingPayoff> aoo =
            ext::dynamic_pointer_cast<AssetOrNothingPayoff>(payoff_);
        if (aoo != nullptr) {
            mu += 1.0; 
            K = spot * dividendDiscount / discount; // forward
        }

        Real log_S_X = std::log(spot/strike);
        Real log_S_H = std::log(spot/barrier);
        Real log_H_S = std::log(barrier/spot);
        Real log_H2_SX = std::log(barrier*barrier/(spot*strike));
        Real H_S_2mu = std::pow(barrier/spot, 2*mu);

        Real eta = (barrierType == Barrier::DownIn ||
                    barrierType == Barrier::DownOut ? 1.0 : -1.0);
        Real phi = (type == Option::Call ? 1.0 : -1.0);

        Real x1, x2, y1, y2;
        Real cum_x1, cum_x2, cum_y1, cum_y2;
        if (variance>=QL_EPSILON) {

            // we calculate using mu*stddev instead of (mu+1)*stddev
            // because cash-or-nothing don't need it. asset-or-nothing
            // mu is really mu+1
            x1 = phi*(log_S_X/stdDev + mu*stdDev);
            x2 = phi*(log_S_H/stdDev + mu*stdDev);
            y1 = eta*(log_H2_SX/stdDev + mu*stdDev);
            y2 = eta*(log_H_S/stdDev + mu*stdDev);

            CumulativeNormalDistribution f;
            cum_x1 = f(x1);
            cum_x2 = f(x2);
            cum_y1 = f(y1);
            cum_y2 = f(y2);
        } else {
            if (log_S_X>0)
                cum_x1= 1.0;
            else
                cum_x1= 0.0;
            if (log_S_H>0)
                cum_x2= 1.0;
            else
                cum_x2= 0.0;
            if (log_H2_SX>0)
                cum_y1= 1.0;
            else
                cum_y1= 0.0;
            if (log_H_S>0)
                cum_y2= 1.0;
            else
                cum_y2= 0.0;
        }

        Real alpha = 0;

        switch (barrierType) {
            case Barrier::DownIn:
               if (type == Option::Call) {
                  // down-in and call
                  if (strike >= barrier) {
                     // B3 (eta=1, phi=1)
                     alpha = H_S_2mu * cum_y1;  
                  } else {
                     // B1-B2+B4 (eta=1, phi=1)
                     alpha = cum_x1 - cum_x2 + H_S_2mu * cum_y2; 
                  }
               }
               else {
                  // down-in and put 
                  if (strike >= barrier) {
                     // B2-B3+B4 (eta=1, phi=-1)
                     alpha = cum_x2 + H_S_2mu*(-cum_y1 + cum_y2);
                  } else {
                     // B1 (eta=1, phi=-1)
                     alpha = cum_x1;
                  }
               }
               break;

            case Barrier::UpIn:
               if (type == Option::Call) {
                  // up-in and call
                  if (strike >= barrier) {
                     // B1 (eta=-1, phi=1)
                     alpha = cum_x1;  
                  } else {
                     // B2-B3+B4 (eta=-1, phi=1)
                     alpha = cum_x2 + H_S_2mu * (-cum_y1 + cum_y2);
                  }
               }
               else {
                  // up-in and put 
                  if (strike >= barrier) {
                     // B1-B2+B4 (eta=-1, phi=-1)
                     alpha = cum_x1 - cum_x2 + H_S_2mu * cum_y2;
                  } else {
                     // B3 (eta=-1, phi=-1)
                     alpha = H_S_2mu * cum_y1;  
                  }
               }
               break;

            case Barrier::DownOut:
               if (type == Option::Call) {
                  // down-out and call
                  if (strike >= barrier) {
                     // B1-B3 (eta=1, phi=1)
                     alpha = cum_x1 - H_S_2mu * cum_y1; 
                  } else {
                     // B2-B4 (eta=1, phi=1)
                     alpha = cum_x2 - H_S_2mu * cum_y2; 
                  }
               }
               else {
                  // down-out and put 
                  if (strike >= barrier) {
                     // B1-B2+B3-B4 (eta=1, phi=-1)
                     alpha = cum_x1 - cum_x2 + H_S_2mu * (cum_y1-cum_y2);
                  } else {
                     // always 0
                     alpha = 0;  
                  }
               }
               break;
            case Barrier::UpOut:
               if (type == Option::Call) {
                  // up-out and call
                  if (strike >= barrier) {
                     // always 0
                     alpha = 0;  
                  } else {
                     // B1-B2+B3-B4 (eta=-1, phi=1)
                     alpha = cum_x1 - cum_x2 + H_S_2mu * (cum_y1-cum_y2);
                  }
               }
               else {
                  // up-out and put 
                  if (strike >= barrier) {
                     // B2-B4 (eta=-1, phi=-1)
                     alpha = cum_x2 - H_S_2mu * cum_y2;
                  } else {
                     // B1-B3 (eta=-1, phi=-1)
                     alpha = cum_x1 - H_S_2mu * cum_y1;
                  }
               }
               break;
            default:
                QL_FAIL("invalid barrier type");
        }

        return discount * K * alpha;
    }



}