File: upperboundengine.cpp

package info (click to toggle)
quantlib 1.4-2
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 34,340 kB
  • ctags: 64,765
  • sloc: cpp: 291,654; ansic: 21,484; sh: 11,209; makefile: 4,923; lisp: 86
file content (353 lines) | stat: -rw-r--r-- 14,401 bytes parent folder | download | duplicates (3)
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
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2006 Mark Joshi
 Copyright (C) 2006 StatPro Italia srl

 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
 <http://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/models/marketmodels/callability/upperboundengine.hpp>
#include <ql/models/marketmodels/accountingengine.hpp>
#include <ql/models/marketmodels/products/multistep/callspecifiedmultiproduct.hpp>
#include <ql/models/marketmodels/products/multistep/exerciseadapter.hpp>
#include <ql/models/marketmodels/utilities.hpp>
#include <ql/models/marketmodels/curvestate.hpp>
#include <ql/models/marketmodels/multiproduct.hpp>
#include <ql/models/marketmodels/discounter.hpp>
#include <ql/models/marketmodels/evolver.hpp>
#include <ql/models/marketmodels/callability/exercisevalue.hpp>
#include <algorithm>

namespace QuantLib {

    namespace {

        class DecoratedHedge : public CallSpecifiedMultiProduct {
          public:
            DecoratedHedge(const CallSpecifiedMultiProduct& product)
            : CallSpecifiedMultiProduct(product) {
                savedStates_.reserve(product.evolution().numberOfSteps());

                Size N = product.numberOfProducts();
                numberCashFlowsThisStep_.resize(N);
                cashFlowsGenerated_.resize(N);
                for (Size i=0; i<N; ++i)
                    cashFlowsGenerated_[i].resize(
                            product.maxNumberOfCashFlowsPerProductPerStep());

                clear();
            }

            void reset() {
                CallSpecifiedMultiProduct::reset();
                disableCallability();
                for (Size i=0; i<lastSavedStep_; ++i)
                    CallSpecifiedMultiProduct::nextTimeStep(
                                                     *savedStates_[i],
                                                     numberCashFlowsThisStep_,
                                                     cashFlowsGenerated_);
                enableCallability();
            }

            bool nextTimeStep(
                    const CurveState& currentState,
                    std::vector<Size>& numberCashFlowsThisStep,
                    std::vector<std::vector<CashFlow> >& cashFlowsGenerated) {
                if (recording_)
                    savedStates_.push_back(currentState);
                return CallSpecifiedMultiProduct::nextTimeStep(
                                                     currentState,
                                                     numberCashFlowsThisStep,
                                                     cashFlowsGenerated);
            }

            std::auto_ptr<MarketModelMultiProduct> clone() const {
                return std::auto_ptr<MarketModelMultiProduct>(
                                                   new DecoratedHedge(*this));
            }

            void save() {
                lastSavedStep_ = savedStates_.size();
            }

            void clear() {
                lastSavedStep_ = 0;
                savedStates_.clear();
                recording_ = true;
            }

            void startRecording() {
                recording_ = true;
            }

            void stopRecording() {
                recording_ = false;
            }
          private:
            std::vector<Clone<CurveState> > savedStates_;
            Size lastSavedStep_;
            bool recording_;
            std::vector<Size> numberCashFlowsThisStep_;
            std::vector<std::vector<CashFlow> > cashFlowsGenerated_;
        };

    }



    UpperBoundEngine::UpperBoundEngine(
                   const boost::shared_ptr<MarketModelEvolver>& evolver,
                   const std::vector<boost::shared_ptr<MarketModelEvolver> >&
                                                                 innerEvolvers,
                   const MarketModelMultiProduct& underlying,
                   const MarketModelExerciseValue& rebate,
                   const MarketModelMultiProduct& hedge,
                   const MarketModelExerciseValue& hedgeRebate,
                   const ExerciseStrategy<CurveState>& hedgeStrategy,
                   Real initialNumeraireValue)
    : evolver_(evolver), innerEvolvers_(innerEvolvers),
      composite_(MultiProductComposite()),
      initialNumeraireValue_(initialNumeraireValue) {

        composite_.add(underlying);
        composite_.add(ExerciseAdapter(rebate));
        composite_.add(hedge);
        composite_.add(ExerciseAdapter(hedgeRebate));
        composite_.add(DecoratedHedge(CallSpecifiedMultiProduct(
                           hedge,hedgeStrategy,ExerciseAdapter(hedgeRebate))));
        composite_.finalize();

        underlyingOffset_ = 0;
        underlyingSize_ = underlying.numberOfProducts();
        rebateOffset_ = underlyingSize_;
        rebateSize_ = 1;
        hedgeOffset_ = underlyingSize_+rebateSize_;
        hedgeSize_ = hedge.numberOfProducts();
        hedgeRebateOffset_ = underlyingSize_+rebateSize_+hedgeSize_;
        hedgeRebateSize_ = 1;


        numberOfProducts_ = composite_.numberOfProducts();

        const std::vector<Time>& evolutionTimes =
            composite_.evolution().evolutionTimes();
        numberOfSteps_ = evolutionTimes.size();

        isExerciseTime_.resize(evolutionTimes.size());
        isExerciseTime_ = isInSubset(evolutionTimes,
                                     hedgeStrategy.exerciseTimes());

        numberCashFlowsThisStep_.resize(numberOfProducts_);
        cashFlowsGenerated_.resize(numberOfProducts_);
        for (Size i=0; i<numberOfProducts_; ++i)
            cashFlowsGenerated_[i].resize(
                          composite_.maxNumberOfCashFlowsPerProductPerStep());

        const std::vector<Time>& cashFlowTimes =
            composite_.possibleCashFlowTimes();
        const std::vector<Rate>& rateTimes =
            composite_.evolution().rateTimes();
        Size n =cashFlowTimes.size();
        discounters_.reserve(n);
        for (Size j=0; j<n; ++j)
            discounters_.push_back(MarketModelDiscounter(cashFlowTimes[j],
                                                         rateTimes));
    }


    void UpperBoundEngine::multiplePathValues(Statistics& stats,
                                              Size outerPaths,
                                              Size innerPaths) {
        for (Size i=0; i<outerPaths; ++i) {
            std::pair<Real,Real> result = singlePathValue(innerPaths);
            stats.add(result.first, result.second);
        }
    }


    std::pair<Real,Real> UpperBoundEngine::singlePathValue(Size innerPaths) {

        DecoratedHedge& callable =
            dynamic_cast<DecoratedHedge&>(composite_.item(4));
        const ExerciseStrategy<CurveState>& strategy = callable.strategy();


        Real maximumValue = QL_MIN_REAL;
        Real numerairesHeld = 0.0;
        Real weight = evolver_->startNewPath();
        callable.clear();
        composite_.reset();
        callable.disableCallability();
        Real principalInNumerairePortfolio = 1.0;
        Size exercise = 0;

        for (Size k=0; k<numberOfSteps_; ++k) {
            weight *= evolver_->advanceStep();

            composite_.nextTimeStep(evolver_->currentState(),
                                    numberCashFlowsThisStep_,
                                    cashFlowsGenerated_);

            // First, we accumulate cash flows from both the
            // underlying...
            Real underlyingCashFlows =
                collectCashFlows(k,
                                 principalInNumerairePortfolio,
                                 underlyingOffset_,
                                 underlyingOffset_+underlyingSize_);

            // ...and the hedge
            Real hedgeCashFlows =
                collectCashFlows(k,
                                 principalInNumerairePortfolio,
                                 hedgeOffset_,
                                 hedgeOffset_+hedgeSize_);

            // we do the same for the rebates. Warning: this relies on
            // the fact that on each exercise date an ExerciseAdapter
            // generates a cash-flow equal to the exercise value
            Real rebateCashFlow =
                collectCashFlows(k,
                                 principalInNumerairePortfolio,
                                 rebateOffset_,
                                 rebateOffset_+rebateSize_);

            Real hedgeRebateCashFlow =
                collectCashFlows(k,
                                 principalInNumerairePortfolio,
                                  hedgeRebateOffset_,
                                 hedgeRebateOffset_+hedgeRebateSize_);


            numerairesHeld += underlyingCashFlows - hedgeCashFlows;

            // Second, we do the upper-bound thing
            if (isExerciseTime_[k]) {

                Real unexercisedHedgeValue = 0.0;

                if (k != numberOfSteps_-1) {

                    // Here, we setup the relevant inner evolver and
                    // the decorated callable hedge such that their
                    // reset() method brings them to the current point
                    // rather than the beginning of the path.

                    boost::shared_ptr<MarketModelEvolver> currentEvolver =
                        innerEvolvers_[exercise++];
                    currentEvolver->setInitialState(evolver_->currentState());

                    callable.stopRecording();
                    callable.enableCallability();
                    callable.save();

                    // This allows us to write:
                    AccountingEngine engine(currentEvolver, callable,
                                            1.0); // this causes the result
                                                  // to be in numeraire units
                    SequenceStatisticsInc innerStats(callable.numberOfProducts());
                    engine.multiplePathValues(innerStats, innerPaths);

                    const std::vector<Real>& values = innerStats.mean();
                    unexercisedHedgeValue =
                        std::accumulate(values.begin(), values.end(), 0.0)
                        / principalInNumerairePortfolio;

                    callable.disableCallability();
                    callable.startRecording();

                }

                // Now, we can calculate the total value of our hedged
                // portfolio...
                Real portfolioValue = numerairesHeld;
                if (strategy.exercise(evolver_->currentState())) {
                    // get the rebates...
                    portfolioValue +=
                        rebateCashFlow - hedgeRebateCashFlow;
                    // ...and reinvest to rehedge
                    numerairesHeld +=
                        unexercisedHedgeValue - hedgeRebateCashFlow;
                } else {
                    portfolioValue +=
                        rebateCashFlow - unexercisedHedgeValue;
                }

                // ...and use it to update the maximum value
                maximumValue = std::max(maximumValue, portfolioValue);
            }


            // Lastly, we do the homework for next step (if any)
            if (k<numberOfSteps_-1) {

                // The numeraire might change between steps. This implies
                // that we might have to convert the numeraire bonds for
                // this step into a corresponding amount of numeraire
                // bonds for the next step. This can be done by changing
                // the principal of the numeraire and updating the number
                // of bonds in the numeraire portfolio accordingly.

                Size numeraire = evolver_->numeraires()[k];
                Size nextNumeraire = evolver_->numeraires()[k+1];

                principalInNumerairePortfolio *=
                    evolver_->currentState().discountRatio(numeraire,
                                                           nextNumeraire);
            }

        }

        // finally, we update the maximum with the total accumulated
        // cash flows (in case we never exercised)
        maximumValue = std::max(maximumValue, numerairesHeld);


        // all done; we just convert the result back to cash
        maximumValue *= initialNumeraireValue_;

        return std::make_pair(maximumValue, weight);
    }


    Real UpperBoundEngine::collectCashFlows(Size currentStep,
                                            Real principalInNumerairePortfolio,
                                            Size beginProduct,
                                            Size endProduct) const {
        Size numeraire = evolver_->numeraires()[currentStep];

        Real numeraireUnits = 0.0;
        // For each product in range...
        for (Size i=beginProduct; i<endProduct; ++i) {
            // ...and for each cash flow...
            const std::vector<MarketModelMultiProduct::CashFlow>& cashflows =
                cashFlowsGenerated_[i];
            for (Size j=0; j<numberCashFlowsThisStep_[i]; ++j) {
                // ...convert the cash flow to numeraires.  This is
                // done by calculating the number of numeraire bonds
                // corresponding to such cash flow...
                const MarketModelDiscounter& discounter =
                    discounters_[cashflows[j].timeIndex];
                // ...and adding the newly bought bonds to the total
                numeraireUnits += cashflows[j].amount *
                    discounter.numeraireBonds(evolver_->currentState(),
                                              numeraire);
            }
        }
        return numeraireUnits/principalInNumerairePortfolio;
    }

}