File: _discrete_hedging_8cpp-example.html

package info (click to toggle)
quantlib-refman-html 1.20-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid, trixie
  • size: 103,140 kB
  • sloc: javascript: 13,408; makefile: 35
file content (455 lines) | stat: -rw-r--r-- 43,230 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.20"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>QuantLib: DiscreteHedging.cpp</title>
<link href='https://fonts.googleapis.com/css?family=Merriweather+Sans:800' rel='stylesheet' type='text/css'>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
</script>
<script type="text/javascript" async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="quantlibextra.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectalign" style="padding-left: 0.5em;">
   <div id="projectname"><a href="http://quantlib.org">
       <img alt="QuantLib" src="QL-title.jpg"></a>
   <div id="projectbrief">A free/open-source library for quantitative finance</div>
   <div id="projectnumber">Reference manual - version 1.20</div>
   </div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.20 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
var searchBox = new SearchBox("searchBox", "search",false,'Search');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */
$(function() {
  initMenu('',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
/* @license-end */</script>
<div id="main-nav"></div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div class="header">
  <div class="headertitle">
<div class="title">DiscreteHedging.cpp</div>  </div>
</div><!--header-->
<div class="contents">
<p>This example computes profit and loss of a discrete interval hedging strategy and compares with the outcome with the results of Derman and Kamal's Goldman Sachs Equity Derivatives Research Note "When You Cannot Hedge Continuously: The Corrections to
Black-Scholes". It shows the use of the Monte Carlo framework.</p>
<div class="fragment"><div class="line"><span class="comment">/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */</span></div>
<div class="line"> </div>
<div class="line"><span class="comment">/*  This example computes profit and loss of a discrete interval hedging</span></div>
<div class="line"><span class="comment">    strategy and compares with the results of Derman &amp; Kamal&#39;s (Goldman Sachs</span></div>
<div class="line"><span class="comment">    Equity Derivatives Research) Research Note: &quot;When You Cannot Hedge</span></div>
<div class="line"><span class="comment">    Continuously: The Corrections to Black-Scholes&quot;</span></div>
<div class="line"><span class="comment">    http://www.ederman.com/emanuelderman/GSQSpapers/when_you_cannot_hedge.pdf</span></div>
<div class="line"><span class="comment"></span> </div>
<div class="line"><span class="comment">    Suppose an option hedger sells an European option and receives the</span></div>
<div class="line"><span class="comment">    Black-Scholes value as the options premium.</span></div>
<div class="line"><span class="comment">    Then he follows a Black-Scholes hedging strategy, rehedging at discrete,</span></div>
<div class="line"><span class="comment">    evenly spaced time intervals as the underlying stock changes. At</span></div>
<div class="line"><span class="comment">    expiration, the hedger delivers the option payoff to the option holder,</span></div>
<div class="line"><span class="comment">    and unwinds the hedge. We are interested in understanding the final</span></div>
<div class="line"><span class="comment">    profit or loss of this strategy.</span></div>
<div class="line"><span class="comment"></span> </div>
<div class="line"><span class="comment">    If the hedger had followed the exact Black-Scholes replication strategy,</span></div>
<div class="line"><span class="comment">    re-hedging continuously as the underlying stock evolved towards its final</span></div>
<div class="line"><span class="comment">    value at expiration, then, no matter what path the stock took, the final</span></div>
<div class="line"><span class="comment">    P&amp;L would be exactly zero. When the replication strategy deviates from</span></div>
<div class="line"><span class="comment">    the exact Black-Scholes method, the final P&amp;L may deviate from zero. This</span></div>
<div class="line"><span class="comment">    deviation is called the replication error. When the hedger rebalances at</span></div>
<div class="line"><span class="comment">    discrete rather than continuous intervals, the hedge is imperfect and the</span></div>
<div class="line"><span class="comment">    replication is inexact. The more often hedging occurs, the smaller the</span></div>
<div class="line"><span class="comment">    replication error.</span></div>
<div class="line"><span class="comment"></span> </div>
<div class="line"><span class="comment">    We examine the range of possibilities, computing the replication error.</span></div>
<div class="line"><span class="comment">*/</span></div>
<div class="line"> </div>
<div class="line"><span class="preprocessor">#include &lt;ql/qldefines.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#ifdef BOOST_MSVC</span></div>
<div class="line"><span class="preprocessor">#  include &lt;ql/auto_link.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#endif</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/methods/montecarlo/montecarlomodel.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/processes/blackscholesprocess.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/termstructures/yield/flatforward.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/termstructures/volatility/equityfx/blackconstantvol.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/pricingengines/blackcalculator.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/quotes/simplequote.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/time/calendars/target.hpp&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;ql/time/daycounters/actual365fixed.hpp&gt;</span></div>
<div class="line"> </div>
<div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div>
<div class="line"><span class="preprocessor">#include &lt;iomanip&gt;</span></div>
<div class="line"> </div>
<div class="line"><span class="keyword">using namespace </span><a class="code" href="namespace_quant_lib.html">QuantLib</a>;</div>
<div class="line"> </div>
<div class="line"><span class="preprocessor">#if defined(QL_ENABLE_SESSIONS)</span></div>
<div class="line"><span class="keyword">namespace </span><a class="code" href="namespace_quant_lib.html">QuantLib</a> {</div>
<div class="line"> </div>
<div class="line">    ThreadKey sessionId() { <span class="keywordflow">return</span> 0; }</div>
<div class="line"> </div>
<div class="line">}</div>
<div class="line"><span class="preprocessor">#endif</span></div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line"><span class="comment">/* The ReplicationError class carries out Monte Carlo simulations to evaluate</span></div>
<div class="line"><span class="comment">   the outcome (the replication error) of the discrete hedging strategy over</span></div>
<div class="line"><span class="comment">   different, randomly generated scenarios of future stock price evolution.</span></div>
<div class="line"><span class="comment">*/</span></div>
<div class="line"><span class="keyword">class </span>ReplicationError</div>
<div class="line">{</div>
<div class="line"><span class="keyword">public</span>:</div>
<div class="line">    ReplicationError(Option::Type type,</div>
<div class="line">                     <a name="a0"></a><a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> maturity,</div>
<div class="line">                     <a name="a1"></a><a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> strike,</div>
<div class="line">                     <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> s0,</div>
<div class="line">                     <a name="a2"></a><a class="code" href="group__types.html#gaaa95ab7fe66935e3f7535413fad2a7d3" title="volatility">Volatility</a> sigma,</div>
<div class="line">                     <a name="a3"></a><a class="code" href="group__types.html#gaede435af51236692b1107d7639581d39" title="interest rates">Rate</a> r)</div>
<div class="line">    : maturity_(maturity), payoff_(type, strike), s0_(s0),</div>
<div class="line">      sigma_(sigma), r_(r) {</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// value of the option</span></div>
<div class="line">        <a name="a4"></a><a class="code" href="group__types.html#ga642a971a0bcbbd2fb26c35e1a06e5761" title="discount factor between dates">DiscountFactor</a> rDiscount = std::exp(-r_*maturity_);</div>
<div class="line">        <a class="code" href="group__types.html#ga642a971a0bcbbd2fb26c35e1a06e5761" title="discount factor between dates">DiscountFactor</a> qDiscount = 1.0;</div>
<div class="line">        <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> forward = s0_*qDiscount/rDiscount;</div>
<div class="line">        <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> stdDev = std::sqrt(sigma_*sigma_*maturity_);</div>
<div class="line">        ext::shared_ptr&lt;StrikedTypePayoff&gt; payoff(</div>
<div class="line">                                             <span class="keyword">new</span> <a name="_a5"></a><a class="code" href="class_quant_lib_1_1_plain_vanilla_payoff.html" title="Plain-vanilla payoff.">PlainVanillaPayoff</a>(payoff_));</div>
<div class="line">        <a name="_a6"></a><a class="code" href="class_quant_lib_1_1_black_calculator.html" title="Black 1976 calculator class.">BlackCalculator</a> black(payoff,forward,stdDev,rDiscount);</div>
<div class="line">        std::cout &lt;&lt; <span class="stringliteral">&quot;Option value: &quot;</span> &lt;&lt; black.value() &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// store option&#39;s vega, since Derman and Kamal&#39;s formula needs it</span></div>
<div class="line">        vega_ = black.vega(maturity_);</div>
<div class="line"> </div>
<div class="line">        std::cout &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line">        std::cout &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot; &quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot; &quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;P&amp;L&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;P&amp;L&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(12) &lt;&lt; <span class="stringliteral">&quot;Derman&amp;Kamal&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;P&amp;L&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;P&amp;L&quot;</span> &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line">        std::cout &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;samples&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;trades&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;mean&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;std.dev.&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(12) &lt;&lt; <span class="stringliteral">&quot;formula&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;skewness&quot;</span> &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">                  &lt;&lt; std::setw(8) &lt;&lt; <span class="stringliteral">&quot;kurtosis&quot;</span> &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line">        std::cout &lt;&lt; std::string(78, <span class="charliteral">&#39;-&#39;</span>) &lt;&lt; std::endl;</div>
<div class="line">    }</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// the actual replication error computation</span></div>
<div class="line">    <span class="keywordtype">void</span> compute(<a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> nTimeSteps, <a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> nSamples);</div>
<div class="line"><span class="keyword">private</span>:</div>
<div class="line">    <a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> maturity_;</div>
<div class="line">    <a class="code" href="class_quant_lib_1_1_plain_vanilla_payoff.html" title="Plain-vanilla payoff.">PlainVanillaPayoff</a> payoff_;</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> s0_;</div>
<div class="line">    <a class="code" href="group__types.html#gaaa95ab7fe66935e3f7535413fad2a7d3" title="volatility">Volatility</a> sigma_;</div>
<div class="line">    <a class="code" href="group__types.html#gaede435af51236692b1107d7639581d39" title="interest rates">Rate</a> r_;</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> vega_;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"><span class="comment">// The key for the MonteCarlo simulation is to have a PathPricer that</span></div>
<div class="line"><span class="comment">// implements a value(const Path&amp; path) method.</span></div>
<div class="line"><span class="comment">// This method prices the portfolio for each Path of the random variable</span></div>
<div class="line"><span class="keyword">class </span>ReplicationPathPricer : <span class="keyword">public</span> <a name="_a7"></a><a class="code" href="class_quant_lib_1_1_path_pricer.html" title="base class for path pricers">PathPricer</a>&lt;Path&gt; {</div>
<div class="line">  <span class="keyword">public</span>:</div>
<div class="line">    <span class="comment">// real constructor</span></div>
<div class="line">    ReplicationPathPricer(Option::Type type,</div>
<div class="line">                          <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> strike,</div>
<div class="line">                          <a class="code" href="group__types.html#gaede435af51236692b1107d7639581d39" title="interest rates">Rate</a> r,</div>
<div class="line">                          <a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> maturity,</div>
<div class="line">                          <a class="code" href="group__types.html#gaaa95ab7fe66935e3f7535413fad2a7d3" title="volatility">Volatility</a> sigma)</div>
<div class="line">    : type_(type), strike_(strike),</div>
<div class="line">      r_(r), maturity_(maturity), sigma_(sigma) {</div>
<div class="line">        QL_REQUIRE(strike_ &gt; 0.0, <span class="stringliteral">&quot;strike must be positive&quot;</span>);</div>
<div class="line">        QL_REQUIRE(r_ &gt;= 0.0,</div>
<div class="line">                   <span class="stringliteral">&quot;risk free rate (r) must be positive or zero&quot;</span>);</div>
<div class="line">        QL_REQUIRE(maturity_ &gt; 0.0, <span class="stringliteral">&quot;maturity must be positive&quot;</span>);</div>
<div class="line">        QL_REQUIRE(sigma_ &gt;= 0.0,</div>
<div class="line">                   <span class="stringliteral">&quot;volatility (sigma) must be positive or zero&quot;</span>);</div>
<div class="line"> </div>
<div class="line">    }</div>
<div class="line">    <span class="comment">// The value() method encapsulates the pricing code</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> operator()(<span class="keyword">const</span> <a name="_a8"></a><a class="code" href="class_quant_lib_1_1_path.html" title="single-factor random walk">Path</a>&amp; path) <span class="keyword">const</span>;</div>
<div class="line"> </div>
<div class="line">  <span class="keyword">private</span>:</div>
<div class="line">    Option::Type type_;</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> strike_;</div>
<div class="line">    <a class="code" href="group__types.html#gaede435af51236692b1107d7639581d39" title="interest rates">Rate</a> r_;</div>
<div class="line">    <a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> maturity_;</div>
<div class="line">    <a class="code" href="group__types.html#gaaa95ab7fe66935e3f7535413fad2a7d3" title="volatility">Volatility</a> sigma_;</div>
<div class="line">};</div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line"><span class="comment">// Compute Replication Error as in the Derman and Kamal&#39;s research note</span></div>
<div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span>, <span class="keywordtype">char</span>* []) {</div>
<div class="line"> </div>
<div class="line">    <span class="keywordflow">try</span> {</div>
<div class="line"> </div>
<div class="line">        std::cout &lt;&lt; std::endl;</div>
<div class="line"> </div>
<div class="line">        <a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> maturity = 1.0/12.0;   <span class="comment">// 1 month</span></div>
<div class="line">        <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> strike = 100;</div>
<div class="line">        <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> underlying = 100;</div>
<div class="line">        <a class="code" href="group__types.html#gaaa95ab7fe66935e3f7535413fad2a7d3" title="volatility">Volatility</a> <a name="a9"></a><a class="code" href="group__manips.html#gac402ef7c87f63f7c603ee87210b5750c" title="output volatilities as percentages">volatility</a> = 0.20; <span class="comment">// 20%</span></div>
<div class="line">        <a class="code" href="group__types.html#gaede435af51236692b1107d7639581d39" title="interest rates">Rate</a> riskFreeRate = 0.05; <span class="comment">// 5%</span></div>
<div class="line">        ReplicationError rp(Option::Call, maturity, strike, underlying,</div>
<div class="line">                <a class="code" href="group__manips.html#gac402ef7c87f63f7c603ee87210b5750c" title="output volatilities as percentages">volatility</a>, riskFreeRate);</div>
<div class="line"> </div>
<div class="line">        <a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> scenarios = 50000;</div>
<div class="line">        <a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> hedgesNum;</div>
<div class="line"> </div>
<div class="line">        hedgesNum = 21;</div>
<div class="line">        rp.compute(hedgesNum, scenarios);</div>
<div class="line"> </div>
<div class="line">        hedgesNum = 84;</div>
<div class="line">        rp.compute(hedgesNum, scenarios);</div>
<div class="line"> </div>
<div class="line">        <span class="keywordflow">return</span> 0;</div>
<div class="line">    } <span class="keywordflow">catch</span> (std::exception&amp; e) {</div>
<div class="line">        std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;</div>
<div class="line">        <span class="keywordflow">return</span> 1;</div>
<div class="line">    } <span class="keywordflow">catch</span> (...) {</div>
<div class="line">        std::cerr &lt;&lt; <span class="stringliteral">&quot;unknown error&quot;</span> &lt;&lt; std::endl;</div>
<div class="line">        <span class="keywordflow">return</span> 1;</div>
<div class="line">    }</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line"><span class="comment">/* The actual computation of the Profit&amp;Loss for each single path.</span></div>
<div class="line"><span class="comment"></span> </div>
<div class="line"><span class="comment">   In each scenario N rehedging trades spaced evenly in time over</span></div>
<div class="line"><span class="comment">   the life of the option are carried out, using the Black-Scholes</span></div>
<div class="line"><span class="comment">   hedge ratio.</span></div>
<div class="line"><span class="comment">*/</span></div>
<div class="line"><a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> ReplicationPathPricer::operator()(<span class="keyword">const</span> <a class="code" href="class_quant_lib_1_1_path.html" title="single-factor random walk">Path</a>&amp; path)<span class="keyword"> const </span>{</div>
<div class="line"> </div>
<div class="line">    <a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> n = path.<a name="a10"></a>length()-1;</div>
<div class="line">    QL_REQUIRE(n&gt;0, <span class="stringliteral">&quot;the path cannot be empty&quot;</span>);</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// discrete hedging interval</span></div>
<div class="line">    <a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> dt = maturity_/n;</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// For simplicity, we assume the stock pays no dividends.</span></div>
<div class="line">    <a class="code" href="group__types.html#gaede435af51236692b1107d7639581d39" title="interest rates">Rate</a> stockDividendYield = 0.0;</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// let&#39;s start</span></div>
<div class="line">    <a class="code" href="group__types.html#ga14fb8fca43a68f4168654e1f9f7e22f7" title="continuous quantity with 1-year units">Time</a> t = 0;</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// stock value at t=0</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> stock = path.<a name="a11"></a><a class="code" href="class_quant_lib_1_1_path.html#af78ff4861aaf9bf0524b958dbb4d1b18" title="initial asset value">front</a>();</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// money account at t=0</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> money_account = 0.0;</div>
<div class="line"> </div>
<div class="line"><span class="comment">    /************************/</span></div>
<div class="line"><span class="comment">    /*** the initial deal ***/</span></div>
<div class="line"><span class="comment">    /************************/</span></div>
<div class="line">    <span class="comment">// option fair price (Black-Scholes) at t=0</span></div>
<div class="line">    <a class="code" href="group__types.html#ga642a971a0bcbbd2fb26c35e1a06e5761" title="discount factor between dates">DiscountFactor</a> rDiscount = std::exp(-r_*maturity_);</div>
<div class="line">    <a class="code" href="group__types.html#ga642a971a0bcbbd2fb26c35e1a06e5761" title="discount factor between dates">DiscountFactor</a> qDiscount = std::exp(-stockDividendYield*maturity_);</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> forward = stock*qDiscount/rDiscount;</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> stdDev = std::sqrt(sigma_*sigma_*maturity_);</div>
<div class="line">    ext::shared_ptr&lt;StrikedTypePayoff&gt; payoff(</div>
<div class="line">                                       <span class="keyword">new</span> <a class="code" href="class_quant_lib_1_1_plain_vanilla_payoff.html" title="Plain-vanilla payoff.">PlainVanillaPayoff</a>(type_,strike_));</div>
<div class="line">    <a class="code" href="class_quant_lib_1_1_black_calculator.html" title="Black 1976 calculator class.">BlackCalculator</a> black(payoff,forward,stdDev,rDiscount);</div>
<div class="line">    <span class="comment">// sell the option, cash in its premium</span></div>
<div class="line">    money_account += black.value();</div>
<div class="line">    <span class="comment">// compute delta</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> delta = black.delta(stock);</div>
<div class="line">    <span class="comment">// delta-hedge the option buying stock</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> stockAmount = delta;</div>
<div class="line">    money_account -= stockAmount*stock;</div>
<div class="line"> </div>
<div class="line"><span class="comment">    /**********************************/</span></div>
<div class="line"><span class="comment">    /*** hedging during option life ***/</span></div>
<div class="line"><span class="comment">    /**********************************/</span></div>
<div class="line">    <span class="keywordflow">for</span> (<a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> step = 0; step &lt; n-1; step++){</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// time flows</span></div>
<div class="line">        t += dt;</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// accruing on the money account</span></div>
<div class="line">        money_account *= std::exp( r_*dt );</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// stock growth:</span></div>
<div class="line">        stock = path[step+1];</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// recalculate option value at the current stock value,</span></div>
<div class="line">        <span class="comment">// and the current time to maturity</span></div>
<div class="line">        rDiscount = std::exp(-r_*(maturity_-t));</div>
<div class="line">        qDiscount = std::exp(-stockDividendYield*(maturity_-t));</div>
<div class="line">        forward = stock*qDiscount/rDiscount;</div>
<div class="line">        stdDev = std::sqrt(sigma_*sigma_*(maturity_-t));</div>
<div class="line">        <a class="code" href="class_quant_lib_1_1_black_calculator.html" title="Black 1976 calculator class.">BlackCalculator</a> black(payoff,forward,stdDev,rDiscount);</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// recalculate delta</span></div>
<div class="line">        delta = black.delta(stock);</div>
<div class="line"> </div>
<div class="line">        <span class="comment">// re-hedging</span></div>
<div class="line">        money_account -= (delta - stockAmount)*stock;</div>
<div class="line">        stockAmount = delta;</div>
<div class="line">    }</div>
<div class="line"> </div>
<div class="line"><span class="comment">    /*************************/</span></div>
<div class="line"><span class="comment">    /*** option expiration ***/</span></div>
<div class="line"><span class="comment">    /*************************/</span></div>
<div class="line">    <span class="comment">// last accrual on my money account</span></div>
<div class="line">    money_account *= std::exp( r_*dt );</div>
<div class="line">    <span class="comment">// last stock growth</span></div>
<div class="line">    stock = path[n];</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// the hedger delivers the option payoff to the option holder</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> optionPayoff = <a class="code" href="class_quant_lib_1_1_plain_vanilla_payoff.html" title="Plain-vanilla payoff.">PlainVanillaPayoff</a>(type_, strike_)(stock);</div>
<div class="line">    money_account -= optionPayoff;</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// and unwinds the hedge selling his stock position</span></div>
<div class="line">    money_account += stockAmount*stock;</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// final Profit&amp;Loss</span></div>
<div class="line">    <span class="keywordflow">return</span> money_account;</div>
<div class="line">}</div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line"><span class="comment">// The computation over nSamples paths of the P&amp;L distribution</span></div>
<div class="line"><span class="keywordtype">void</span> ReplicationError::compute(<a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> nTimeSteps, <a class="code" href="group__types.html#gaf38bdb4c54463b1f456655efa95b5c77" title="size of a container">Size</a> nSamples)</div>
<div class="line">{</div>
<div class="line">    QL_REQUIRE(nTimeSteps&gt;0, <span class="stringliteral">&quot;the number of steps must be &gt; 0&quot;</span>);</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// hedging interval</span></div>
<div class="line">    <span class="comment">// Time tau = maturity_ / nTimeSteps;</span></div>
<div class="line"> </div>
<div class="line">    <span class="comment">/* Black-Scholes framework: the underlying stock price evolves</span></div>
<div class="line"><span class="comment">       lognormally with a fixed known volatility that stays constant</span></div>
<div class="line"><span class="comment">       throughout time.</span></div>
<div class="line"><span class="comment">    */</span></div>
<div class="line">    <a name="_a12"></a><a class="code" href="class_quant_lib_1_1_calendar.html" title="calendar class">Calendar</a> calendar = <a name="_a13"></a><a class="code" href="class_quant_lib_1_1_t_a_r_g_e_t.html" title="TARGET calendar">TARGET</a>();</div>
<div class="line">    <a name="_a14"></a><a class="code" href="class_quant_lib_1_1_date.html" title="Concrete date class.">Date</a> today = <a name="a15"></a><a class="code" href="class_quant_lib_1_1_date.html#aa3b3414c408337e640d21c0936602c66" title="today&#39;s date.">Date::todaysDate</a>();</div>
<div class="line">    <a name="_a16"></a><a class="code" href="class_quant_lib_1_1_day_counter.html" title="day counter class">DayCounter</a> dayCount = <a name="_a17"></a><a class="code" href="class_quant_lib_1_1_actual365_fixed.html" title="Actual/365 (Fixed) day count convention.">Actual365Fixed</a>();</div>
<div class="line">    <a name="_a18"></a><a class="code" href="class_quant_lib_1_1_handle.html" title="Shared handle to an observable.">Handle&lt;Quote&gt;</a> stateVariable(</div>
<div class="line">                          ext::shared_ptr&lt;Quote&gt;(<span class="keyword">new</span> <a name="_a19"></a><a class="code" href="class_quant_lib_1_1_simple_quote.html" title="market element returning a stored value">SimpleQuote</a>(s0_)));</div>
<div class="line">    <a name="_a20"></a><a class="code" href="class_quant_lib_1_1_handle.html">Handle&lt;YieldTermStructure&gt;</a> riskFreeRate(</div>
<div class="line">                          ext::shared_ptr&lt;YieldTermStructure&gt;(</div>
<div class="line">                                      <span class="keyword">new</span> <a name="_a21"></a><a class="code" href="class_quant_lib_1_1_flat_forward.html" title="Flat interest-rate curve.">FlatForward</a>(today, r_, dayCount)));</div>
<div class="line">    <a class="code" href="class_quant_lib_1_1_handle.html">Handle&lt;YieldTermStructure&gt;</a> dividendYield(</div>
<div class="line">                          ext::shared_ptr&lt;YieldTermStructure&gt;(</div>
<div class="line">                                      <span class="keyword">new</span> <a class="code" href="class_quant_lib_1_1_flat_forward.html" title="Flat interest-rate curve.">FlatForward</a>(today, 0.0, dayCount)));</div>
<div class="line">    <a class="code" href="class_quant_lib_1_1_handle.html" title="Shared handle to an observable.">Handle&lt;BlackVolTermStructure&gt;</a> <a class="code" href="group__manips.html#gac402ef7c87f63f7c603ee87210b5750c" title="output volatilities as percentages">volatility</a>(</div>
<div class="line">                          ext::shared_ptr&lt;BlackVolTermStructure&gt;(</div>
<div class="line">                               <span class="keyword">new</span> <a name="_a22"></a><a class="code" href="class_quant_lib_1_1_black_constant_vol.html" title="Constant Black volatility, no time-strike dependence.">BlackConstantVol</a>(today, calendar, sigma_, dayCount)));</div>
<div class="line">    ext::shared_ptr&lt;StochasticProcess1D&gt; diffusion(</div>
<div class="line">                   <span class="keyword">new</span> <a name="_a23"></a><a class="code" href="class_quant_lib_1_1_black_scholes_merton_process.html" title="Merton (1973) extension to the Black-Scholes stochastic process.">BlackScholesMertonProcess</a>(stateVariable, dividendYield,</div>
<div class="line">                                                 riskFreeRate, <a class="code" href="group__manips.html#gac402ef7c87f63f7c603ee87210b5750c" title="output volatilities as percentages">volatility</a>));</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// Black Scholes equation rules the path generator:</span></div>
<div class="line">    <span class="comment">// at each step the log of the stock</span></div>
<div class="line">    <span class="comment">// will have drift and sigma^2 variance</span></div>
<div class="line">    <a name="_a24"></a><a class="code" href="class_quant_lib_1_1_inverse_cumulative_rsg.html" title="Inverse cumulative random sequence generator.">PseudoRandom::rsg_type</a> rsg =</div>
<div class="line">        PseudoRandom::make_sequence_generator(nTimeSteps, 0);</div>
<div class="line"> </div>
<div class="line">    <span class="keywordtype">bool</span> brownianBridge = <span class="keyword">false</span>;</div>
<div class="line"> </div>
<div class="line">    <span class="keyword">typedef</span> <a name="_a25"></a><a class="code" href="class_quant_lib_1_1_path_generator.html" title="Generates random paths using a sequence generator.">SingleVariate&lt;PseudoRandom&gt;::path_generator_type</a> generator_type;</div>
<div class="line">    ext::shared_ptr&lt;generator_type&gt; myPathGenerator(<span class="keyword">new</span></div>
<div class="line">        generator_type(diffusion, maturity_, nTimeSteps,</div>
<div class="line">                       rsg, brownianBridge));</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// The replication strategy&#39;s Profit&amp;Loss is computed for each path</span></div>
<div class="line">    <span class="comment">// of the stock. The path pricer knows how to price a path using its</span></div>
<div class="line">    <span class="comment">// value() method</span></div>
<div class="line">    ext::shared_ptr&lt;PathPricer&lt;Path&gt; &gt; myPathPricer(<span class="keyword">new</span></div>
<div class="line">        ReplicationPathPricer(payoff_.optionType(), payoff_.strike(),</div>
<div class="line">                              r_, maturity_, sigma_));</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// a statistics accumulator for the path-dependant Profit&amp;Loss values</span></div>
<div class="line">    <a name="_a26"></a><a class="code" href="class_quant_lib_1_1_generic_risk_statistics.html" title="empirical-distribution risk measures">Statistics</a> statisticsAccumulator;</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// The Monte Carlo model generates paths using myPathGenerator</span></div>
<div class="line">    <span class="comment">// each path is priced using myPathPricer</span></div>
<div class="line">    <span class="comment">// prices will be accumulated into statisticsAccumulator</span></div>
<div class="line">    <a name="_a27"></a><a class="code" href="class_quant_lib_1_1_monte_carlo_model.html" title="General-purpose Monte Carlo model for path samples.">MonteCarloModel&lt;SingleVariate,PseudoRandom&gt;</a></div>
<div class="line">        MCSimulation(myPathGenerator,</div>
<div class="line">                     myPathPricer,</div>
<div class="line">                     statisticsAccumulator,</div>
<div class="line">                     <span class="keyword">false</span>);</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// the model simulates nSamples paths</span></div>
<div class="line">    MCSimulation.addSamples(nSamples);</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// the sampleAccumulator method</span></div>
<div class="line">    <span class="comment">// gives access to all the methods of statisticsAccumulator</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> PLMean  = MCSimulation.sampleAccumulator().mean();</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> PLStDev = MCSimulation.sampleAccumulator().standardDeviation();</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> PLSkew  = MCSimulation.sampleAccumulator().skewness();</div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> PLKurt  = MCSimulation.sampleAccumulator().kurtosis();</div>
<div class="line"> </div>
<div class="line">    <span class="comment">// Derman and Kamal&#39;s formula</span></div>
<div class="line">    <a class="code" href="group__types.html#ga4bdf4bfe76b9ffa6fa64c47d8bfa0c78" title="real number">Real</a> theorStD = std::sqrt(M_PI/4/nTimeSteps)*vega_*sigma_;</div>
<div class="line"> </div>
<div class="line"> </div>
<div class="line">    std::cout &lt;&lt; std::fixed</div>
<div class="line">              &lt;&lt; std::setw(8) &lt;&lt; nSamples &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">              &lt;&lt; std::setw(8) &lt;&lt; nTimeSteps &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">              &lt;&lt; std::setw(8) &lt;&lt; std::setprecision(3) &lt;&lt; PLMean &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">              &lt;&lt; std::setw(8) &lt;&lt; std::setprecision(2) &lt;&lt; PLStDev &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">              &lt;&lt; std::setw(12) &lt;&lt; std::setprecision(2) &lt;&lt; theorStD &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">              &lt;&lt; std::setw(8) &lt;&lt; std::setprecision(2) &lt;&lt; PLSkew &lt;&lt; <span class="stringliteral">&quot; | &quot;</span></div>
<div class="line">              &lt;&lt; std::setw(8) &lt;&lt; std::setprecision(2) &lt;&lt; PLKurt &lt;&lt; std::endl;</div>
<div class="line">}</div>
</div><!-- fragment --> </div><!-- contents -->
<!-- HTML footer for doxygen 1.8.9.1-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by <a href="http://www.doxygen.org/index.html">Doxygen</a>
1.8.20
</small></address>
</body>
</html>