• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lballabio / QuantLib / 30888847534

04 Aug 2026 07:41AM UTC coverage: 74.922% (-0.002%) from 74.924%
30888847534

push

github

web-flow
Return handles by reference from accessors (#2703)

7 of 8 new or added lines in 5 files covered. (87.5%)

5 existing lines in 3 files now uncovered.

60122 of 80246 relevant lines covered (74.92%)

8660979.07 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

94.39
/ql/pricingengines/swaption/basketgeneratingengine.cpp
1
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2

3
/*
4
 Copyright (C) 2013, 2015 Peter Caspers
5

6
 This file is part of QuantLib, a free-software/open-source library
7
 for financial quantitative analysts and developers - http://quantlib.org/
8

9
 QuantLib is free software: you can redistribute it and/or modify it
10
 under the terms of the QuantLib license.  You should have received a
11
 copy of the license along with this program; if not, please email
12
 <quantlib-dev@lists.sf.net>. The license is also available online at
13
 <https://www.quantlib.org/license.shtml>.
14

15
 This program is distributed in the hope that it will be useful, but WITHOUT
16
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17
 FOR A PARTICULAR PURPOSE.  See the license for more details.
18
*/
19

20
#include <ql/pricingengines/swaption/basketgeneratingengine.hpp>
21
#include <ql/rebatedexercise.hpp>
22
#include <ql/math/optimization/levenbergmarquardt.hpp>
23
#include <ql/math/optimization/simplex.hpp>
24
#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>
25
#include <ql/termstructures/volatility/swaption/swaptionvolcube.hpp>
26
#include <ql/quotes/simplequote.hpp>
27
#include <cmath>
28

29
using std::exp;
30
using std::fabs;
31

32
namespace QuantLib {
33

34
    std::vector<ext::shared_ptr<BlackCalibrationHelper>>
35
    BasketGeneratingEngine::calibrationBasket(
6✔
36
        const ext::shared_ptr<Exercise>& exercise,
37
        const ext::shared_ptr<SwapIndex>& standardSwapBase,
38
        const ext::shared_ptr<SwaptionVolatilityStructure>& swaptionVolatility,
39
        const CalibrationBasketType basketType) const {
40

41
        QL_REQUIRE(
12✔
42
            !standardSwapBase->forwardingTermStructure().empty(),
43
            "standard swap base forwarding term structure must not be empty.");
44
        QL_REQUIRE(
12✔
45
            !standardSwapBase->exogenousDiscount() ||
46
                !standardSwapBase->discountingTermStructure().empty(),
47
            "standard swap base discounting term structure must not be empty.");
48

49
        std::vector<ext::shared_ptr<BlackCalibrationHelper> > result;
50

51
        Date today = Settings::instance().evaluationDate();
6✔
52
        Size minIdxAlive = static_cast<Size>(
53
            std::upper_bound(exercise->dates().begin(), exercise->dates().end(),
12✔
54
                             today) -
55
            exercise->dates().begin());
6✔
56

57
        ext::shared_ptr<RebatedExercise> rebEx =
58
            ext::dynamic_pointer_cast<RebatedExercise>(exercise);
6✔
59

60
        for (Size i = minIdxAlive; i < exercise->dates().size(); i++) {
60✔
61

62
            Date expiry = exercise->date(i);
54✔
63
            Real rebate = 0.0;
64
            Date rebateDate = expiry;
54✔
65
            if (rebEx != nullptr) {
54✔
66
                rebate = rebEx->rebate(i);
18✔
67
                rebateDate = rebEx->rebatePaymentDate(i);
18✔
68
            }
69

70
            ext::shared_ptr<SwaptionHelper> helper;
54✔
71

72
            switch (basketType) {
54✔
73

74
            case Naive: {
18✔
75
                Real swapLength = swaptionVolatility->dayCounter().yearFraction(
36✔
76
                    standardSwapBase->valueDate(expiry), underlyingLastDate());
36✔
77
                ext::shared_ptr<SmileSection> sec =
78
                    swaptionVolatility->smileSection(
79
                        expiry,
80
                        static_cast<Size>(std::lround(swapLength * 12.0)) * Months,
18✔
81
                        true);
18✔
82
                Real atmStrike = sec->atmLevel();
18✔
83
                Real atmVol;
84
                if (atmStrike == Null<Real>())
18✔
85
                    atmVol = sec->volatility(0.03);
36✔
86
                else
87
                    atmVol = sec->volatility(atmStrike);
×
88
                Real shift = sec->shift();
18✔
89

90
                helper = ext::make_shared<SwaptionHelper>(
36✔
91
                    expiry, underlyingLastDate(),
36✔
92
                    Handle<Quote>(ext::make_shared<SimpleQuote>(atmVol)),
36✔
93
                    standardSwapBase->iborIndex(),
36✔
94
                    standardSwapBase->fixedLegTenor(),
36✔
95
                    standardSwapBase->dayCounter(),
18✔
96
                    standardSwapBase->iborIndex()->dayCounter(),
36✔
97
                    standardSwapBase->exogenousDiscount()
18✔
98
                        ? standardSwapBase->discountingTermStructure()
18✔
UNCOV
99
                        : standardSwapBase->forwardingTermStructure(),
×
100
                    BlackCalibrationHelper::RelativePriceError, Null<Real>(), 1.0,
36✔
101
                    swaptionVolatility->volatilityType() ,shift);
54✔
102

103
                break;
104
            }
105

106
            case MaturityStrikeByDeltaGamma: {
36✔
107

108
                // determine the npv, first and second order derivatives at
109
                // $y=0$ of the underlying swap
110

111
                const Real h = 0.0001; // finite difference step in $y$, make
36✔
112
                                       // this a parameter of the engine ?
113
                Real zSpreadDsc =
114
                    oas_.empty() ? Real(1.0)
36✔
115
                                 : exp(-oas_->value() *
18✔
116
                                       onefactormodel_->termStructure()
18✔
117
                                           ->dayCounter()
18✔
118
                                           .yearFraction(expiry, rebateDate));
36✔
119

120
                Real npvm = underlyingNpv(expiry, -h) +
36✔
121
                            rebate *
36✔
122
                                onefactormodel_->zerobond(rebateDate, expiry,
36✔
123
                                                          -h, discountCurve_) *
36✔
124
                                zSpreadDsc;
36✔
125
                Real npv = underlyingNpv(expiry, 0.0) +
36✔
126
                           rebate * onefactormodel_->zerobond(
36✔
127
                                        rebateDate, expiry, 0, discountCurve_) *
36✔
128
                               zSpreadDsc;
36✔
129
                Real npvp = underlyingNpv(expiry, h) +
36✔
130
                            rebate *
36✔
131
                                onefactormodel_->zerobond(rebateDate, expiry, h,
36✔
132
                                                          discountCurve_) *
36✔
133
                                zSpreadDsc;
36✔
134

135
                Real delta = (npvp - npvm) / (2.0 * h);
36✔
136
                Real gamma = (npvp - 2.0 * npv + npvm) / (h * h);
36✔
137

138
                QL_REQUIRE(npv * npv + delta * delta + gamma * gamma > 0.0,
36✔
139
                           "(npv,delta,gamma) must have a positive norm");
140

141
                // debug output
142
                // std::cout << "EXOTIC npv " << npv << " delta " << delta
143
                //           << " gamma " << gamma << std::endl;
144
                // Real xtmp = -5.0;
145
                // std::cout
146
                //     << "********************************************EXERCISE "
147
                //     << expiry << " ******************" << std::endl;
148
                // std::cout << "globalExoticNpv;";
149
                // while (xtmp <= 5.0 + QL_EPSILON) {
150
                //     std::cout << underlyingNpv(expiry, xtmp) << ";";
151
                //     xtmp += 0.1;
152
                // }
153
                // std::cout << std::endl;
154
                // end debug output
155

156
                // play safe, we restrict the maximum maturity so to easily fit
157
                // in the date class restriction
158
                Real maxMaturity =
159
                    swaptionVolatility->dayCounter().yearFraction(
36✔
160
                        expiry, Date::maxDate() - 365);
72✔
161

162
                ext::shared_ptr<MatchHelper> matchHelper_;
36✔
163
                matchHelper_ = ext::make_shared<MatchHelper>(
36✔
164
                    underlyingType(), npv, delta, gamma, *onefactormodel_,
36✔
165
                    standardSwapBase, expiry, maxMaturity, h);
36✔
166

167
                // Optimize
168
                Array initial = initialGuess(expiry);
36✔
169
                QL_REQUIRE(initial.size() == 3,
36✔
170
                           "initial guess must have size 3 (but is "
171
                               << initial.size() << ")");
172

173
                EndCriteria ec(1000, 200, 1E-8, 1E-8, 1E-8); // make these
36✔
174
                                                             // criteria and the
175
                                                             // optimizer itself
176
                                                             // parameters of
177
                                                             // the method ?
178
                Constraint constraint = NoConstraint();
36✔
179
                Problem p(*matchHelper_, constraint, initial);
36✔
180
                LevenbergMarquardt lm;
36✔
181

182
                EndCriteria::Type ret = lm.minimize(p, ec);
36✔
183
                QL_REQUIRE(ret != EndCriteria::None &&
36✔
184
                               ret != EndCriteria::Unknown &&
185
                               ret != EndCriteria::MaxIterations,
186
                           "optimizer returns error (" << ret << ")");
187
                Array solution = p.currentValue();
36✔
188

189
                Real maturity = fabs(solution[1]);
36✔
190

191
                Size years = (Size)std::floor(maturity);
36✔
192
                maturity -= (Real)years;
36✔
193
                maturity *= 12.0;
36✔
194
                Size months = (Size)std::floor(maturity + 0.5);
36✔
195
                if (years == 0 && months == 0)
36✔
196
                    months = 1; // ensure a maturity of at least one months
197
                // maturity -= (Real)months; maturity *= 365.25;
198
                // Size days = (Size)std::floor(maturity);
199

200
                Period matPeriod =
201
                    years * Years + months * Months; //+days*Days;
36✔
202

203
                ext::shared_ptr<SmileSection> sec =
204
                    swaptionVolatility->smileSection(expiry, matPeriod, true);
36✔
205
                Real shift = sec->shift();
36✔
206

207
                // we have to floor the strike of the calibration instrument,
208
                // see warning in the header
209
                solution[2] = std::max(
36✔
210
                    solution[2], 0.00001 - shift); // floor at 0.1bp - shift
36✔
211

212
                // also the calibrated nominal may be zero, so we floor it, too
213
                solution[0] =
36✔
214
                    std::max(solution[0], 0.000001); // float at 0.01bp
36✔
215

216
                Real vol = sec->volatility(solution[2]);
36✔
217

218
                helper = ext::make_shared<SwaptionHelper>(
72✔
219
                    expiry, matPeriod,
220
                    Handle<Quote>(ext::make_shared<SimpleQuote>(
72✔
221
                                      vol)),
222
                    standardSwapBase->iborIndex(),
72✔
223
                    standardSwapBase->fixedLegTenor(),
72✔
224
                    standardSwapBase->dayCounter(),
36✔
225
                    standardSwapBase->iborIndex()->dayCounter(),
72✔
226
                    standardSwapBase->exogenousDiscount()
36✔
227
                        ? standardSwapBase->discountingTermStructure()
36✔
UNCOV
228
                        : standardSwapBase->forwardingTermStructure(),
×
229
                    BlackCalibrationHelper::RelativePriceError, solution[2],
72✔
230
                    fabs(solution[0]), swaptionVolatility->volatilityType(), shift);
108✔
231
                break;
232
            }
36✔
233

234
            default:
×
235
                QL_FAIL("Calibration basket type not known (" << basketType
×
236
                                                              << ")");
237
            }
238

239
            result.push_back(helper);
54✔
240
        }
241

242
        return result;
6✔
243
    }
×
244
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc