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

lballabio / QuantLib / 27603489947

16 Jun 2026 08:07AM UTC coverage: 74.828% (-0.006%) from 74.834%
27603489947

Pull #2629

github

web-flow
Merge a100f20fd into 9eac92aff
Pull Request #2629: Replace Boost macros that might not work with AAD types

59233 of 79159 relevant lines covered (74.83%)

8636679.49 hits per line

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

84.21
/ql/termstructures/volatility/abcdcalibration.cpp
1
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2

3
/*
4
 Copyright (C) 2006, 2015 Ferdinando Ametrano
5
 Copyright (C) 2006 Cristina Duminuco
6
 Copyright (C) 2005, 2006 Klaus Spanderen
7
 Copyright (C) 2007 Giorgio Facchinetti
8
 Copyright (C) 2015 Paolo Mazzocchi
9

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

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

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

24
#include <ql/math/distributions/normaldistribution.hpp>
25
#include <ql/math/interpolations/abcdinterpolation.hpp>
26
#include <ql/math/optimization/constraint.hpp>
27
#include <ql/math/optimization/levenbergmarquardt.hpp>
28
#include <ql/math/optimization/method.hpp>
29
#include <ql/pricingengines/blackformula.hpp>
30
#include <ql/termstructures/volatility/abcd.hpp>
31
#include <ql/termstructures/volatility/abcdcalibration.hpp>
32
#include <utility>
33

34
namespace QuantLib {
35

36
    // to constrained <- from unconstrained
37
    Array AbcdCalibration::AbcdParametersTransformation::direct(const Array& x) const {
19✔
38
        y_[1] = x[1];
19✔
39
        y_[2] = std::exp(x[2]);
19✔
40
        y_[3] = std::exp(x[3]);
19✔
41
        y_[0] = std::exp(x[0]) - y_[3];
19✔
42
        return y_;
19✔
43
    }
44

45
    // to unconstrained <- from constrained
46
    Array AbcdCalibration::AbcdParametersTransformation::inverse(const Array& x) const {
1✔
47
        y_[1] = x[1];
1✔
48
        y_[2] = std::log(x[2]);
1✔
49
        y_[3] = std::log(x[3]);
1✔
50
        y_[0] = std::log(x[0] + x[3]);
1✔
51
        return y_;
1✔
52
    }
53

54
    // to constrained <- from unconstrained
55

56
    AbcdCalibration::AbcdCalibration(const std::vector<Real>& t,
1✔
57
                                     const std::vector<Real>& blackVols,
58
                                     Real a,
59
                                     Real b,
60
                                     Real c,
61
                                     Real d,
62
                                     bool aIsFixed,
63
                                     bool bIsFixed,
64
                                     bool cIsFixed,
65
                                     bool dIsFixed,
66
                                     bool vegaWeighted,
67
                                     ext::shared_ptr<EndCriteria> endCriteria,
68
                                     ext::shared_ptr<OptimizationMethod> optMethod)
1✔
69
    : aIsFixed_(aIsFixed), bIsFixed_(bIsFixed), cIsFixed_(cIsFixed), dIsFixed_(dIsFixed), a_(a),
1✔
70
      b_(b), c_(c), d_(d), abcdEndCriteria_(EndCriteria::None),
1✔
71
      endCriteria_(std::move(endCriteria)), optMethod_(std::move(optMethod)),
1✔
72
      weights_(blackVols.size(), 1.0 / blackVols.size()), vegaWeighted_(vegaWeighted), times_(t),
1✔
73
      blackVols_(blackVols) {
1✔
74

75
        AbcdMathFunction::validate(a, b, c, d);
1✔
76

77
        QL_REQUIRE(blackVols.size()==t.size(),
1✔
78
                       "mismatch between number of times (" << t.size() <<
79
                       ") and blackVols (" << blackVols.size() << ")");
80

81
        // if no optimization method or endCriteria is provided, we provide one
82
        if (!optMethod_) {
1✔
83
            Real epsfcn = 1.0e-8;
84
            Real xtol = 1.0e-8;
85
            Real gtol = 1.0e-8;
86
            bool useCostFunctionsJacobian = false;
87
            optMethod_ = ext::shared_ptr<OptimizationMethod>(new
2✔
88
                LevenbergMarquardt(epsfcn, xtol, gtol, useCostFunctionsJacobian));
2✔
89
        }
90
        if (!endCriteria_) {
1✔
91
            Size maxIterations = 10000;
1✔
92
            Size maxStationaryStateIterations = 1000;
1✔
93
            Real rootEpsilon = 1.0e-8;
1✔
94
            Real functionEpsilon = 0.3e-4;     // Why 0.3e-4 ?
1✔
95
            Real gradientNormEpsilon = 0.3e-4; // Why 0.3e-4 ?
1✔
96
            endCriteria_ = ext::make_shared<EndCriteria>(maxIterations, maxStationaryStateIterations,
2✔
97
                            rootEpsilon, functionEpsilon, gradientNormEpsilon);
1✔
98
        }
99
    }
1✔
100

101
    void AbcdCalibration::compute() {
1✔
102
        if (vegaWeighted_) {
1✔
103
            Real weightsSum = 0.0;
104
            for (Size i=0; i<times_.size() ; i++) {
×
105
                Real stdDev = std::sqrt(blackVols_[i]* blackVols_[i]* times_[i]);
×
106
                // when strike==forward, the blackFormulaStdDevDerivative becomes
107
                weights_[i] = CumulativeNormalDistribution().derivative(.5*stdDev);
×
108
                weightsSum += weights_[i];
×
109
            }
110
            // weight normalization
111
            for (Size i=0; i<times_.size() ; i++) {
×
112
                weights_[i] /= weightsSum;
×
113
            }
114
        }
115

116
        // there is nothing to optimize
117
        if (aIsFixed_ && bIsFixed_ && cIsFixed_ && dIsFixed_) {
1✔
118
            abcdEndCriteria_ = EndCriteria::None;
×
119
            //error_ = interpolationError();
120
            //maxError_ = interpolationMaxError();
121
            return;
×
122
        } else {
123

124
            AbcdError costFunction(this);
125
            transformation_ = ext::shared_ptr<ParametersTransformation>(new
2✔
126
                AbcdParametersTransformation);
2✔
127

128
            Array guess(4);
129
            guess[0] = a_;
1✔
130
            guess[1] = b_;
1✔
131
            guess[2] = c_;
1✔
132
            guess[3] = d_;
1✔
133

134
            std::vector<bool> parameterAreFixed(4);
×
135
            parameterAreFixed[0] = aIsFixed_;
1✔
136
            parameterAreFixed[1] = bIsFixed_;
1✔
137
            parameterAreFixed[2] = cIsFixed_;
1✔
138
            parameterAreFixed[3] = dIsFixed_;
1✔
139

140
            Array inversedTransformatedGuess(transformation_->inverse(guess));
1✔
141

142
            ProjectedCostFunction projectedAbcdCostFunction(costFunction,
143
                            inversedTransformatedGuess, parameterAreFixed);
1✔
144

145
            Array projectedGuess
146
                (projectedAbcdCostFunction.project(inversedTransformatedGuess));
1✔
147

148
            NoConstraint constraint;
1✔
149
            Problem problem(projectedAbcdCostFunction, constraint, projectedGuess);
1✔
150
            abcdEndCriteria_ = optMethod_->minimize(problem, *endCriteria_);
1✔
151
            Array projectedResult(problem.currentValue());
1✔
152
            Array transfResult(projectedAbcdCostFunction.include(projectedResult));
1✔
153

154
            Array result = transformation_->direct(transfResult);
1✔
155
            AbcdMathFunction::validate(a_, b_, c_, d_);
1✔
156
            a_ = result[0];
1✔
157
            b_ = result[1];
1✔
158
            c_ = result[2];
1✔
159
            d_ = result[3];
1✔
160

161
        }
162
    }
163

164
    Real AbcdCalibration::value(Real x) const {
189✔
165
        return abcdBlackVolatility(x,a_,b_,c_,d_);
189✔
166
    }
167

168
    std::vector<Real> AbcdCalibration::k(const std::vector<Real>& t,
1✔
169
                                         const std::vector<Real>& blackVols) const {
170
        QL_REQUIRE(blackVols.size()==t.size(),
1✔
171
               "mismatch between number of times (" << t.size() <<
172
               ") and blackVols (" << blackVols.size() << ")");
173
        std::vector<Real> k(t.size());
1✔
174
        for (Size i=0; i<t.size() ; i++) {
10✔
175
            k[i]=blackVols[i]/value(t[i]);
9✔
176
        }
177
        return k;
1✔
178
    }
179

180
    Real AbcdCalibration::error() const {
3✔
181
        Size n = times_.size();
182
        Real error, squaredError = 0.0;
183
        for (Size i=0; i<times_.size() ; i++) {
30✔
184
            error = (value(times_[i]) - blackVols_[i]);
27✔
185
            squaredError += error * error * weights_[i];
27✔
186
        }
187
        return std::sqrt(n*squaredError/(n-1));
3✔
188
    }
189

190
    Real AbcdCalibration::maxError() const {
×
191
        Real error, maxError = QL_MIN_REAL;
×
192
        for (Size i=0; i<times_.size() ; i++) {
×
193
            error = std::fabs(value(times_[i]) - blackVols_[i]);
×
194
            maxError = std::max(maxError, error);
×
195
        }
196
        return maxError;
×
197
    }
198

199
    // calculate weighted differences
200
    Array AbcdCalibration::errors() const {
17✔
201
        Array results(times_.size());
17✔
202
        for (Size i=0; i<times_.size() ; i++) {
170✔
203
            results[i] = (value(times_[i]) - blackVols_[i])* std::sqrt(weights_[i]);
153✔
204
        }
205
        return results;
17✔
206
    }
207

208
    EndCriteria::Type AbcdCalibration::endCriteria() const{
1✔
209
        return abcdEndCriteria_;
1✔
210
    }
211

212
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc