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
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2009 Ferdinando Ametrano
Copyright (C) 2007 Allen Kuo
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/cashflows/cashflows.hpp>
#include <ql/math/optimization/constraint.hpp>
#include <ql/math/optimization/costfunction.hpp>
#include <ql/math/optimization/simplex.hpp>
#include <ql/pricingengines/bond/bondfunctions.hpp>
#include <ql/termstructures/yield/fittedbonddiscountcurve.hpp>
#include <ql/time/daycounters/simpledaycounter.hpp>
#include <ql/utilities/dataformatters.hpp>
#include <utility>
using std::vector;
namespace QuantLib {
class FittedBondDiscountCurve::FittingMethod::FittingCost
: public CostFunction {
friend class FittedBondDiscountCurve::FittingMethod;
public:
explicit FittingCost(
FittedBondDiscountCurve::FittingMethod* fittingMethod);
Real value(const Array& x) const override;
Array values(const Array& x) const override;
private:
FittedBondDiscountCurve::FittingMethod* fittingMethod_;
};
FittedBondDiscountCurve::FittedBondDiscountCurve(
Natural settlementDays,
const Calendar& calendar,
vector<ext::shared_ptr<BondHelper> > bondHelpers,
const DayCounter& dayCounter,
const FittingMethod& fittingMethod,
Real accuracy,
Size maxEvaluations,
Array guess,
Real simplexLambda,
Size maxStationaryStateIterations)
: YieldTermStructure(settlementDays, calendar, dayCounter), accuracy_(accuracy),
maxEvaluations_(maxEvaluations), simplexLambda_(simplexLambda),
maxStationaryStateIterations_(maxStationaryStateIterations), guessSolution_(std::move(guess)),
bondHelpers_(std::move(bondHelpers)), fittingMethod_(fittingMethod) {
fittingMethod_->curve_ = this;
setup();
}
FittedBondDiscountCurve::FittedBondDiscountCurve(
const Date& referenceDate,
vector<ext::shared_ptr<BondHelper> > bondHelpers,
const DayCounter& dayCounter,
const FittingMethod& fittingMethod,
Real accuracy,
Size maxEvaluations,
Array guess,
Real simplexLambda,
Size maxStationaryStateIterations)
: YieldTermStructure(referenceDate, Calendar(), dayCounter), accuracy_(accuracy),
maxEvaluations_(maxEvaluations), simplexLambda_(simplexLambda),
maxStationaryStateIterations_(maxStationaryStateIterations), guessSolution_(std::move(guess)),
bondHelpers_(std::move(bondHelpers)), fittingMethod_(fittingMethod) {
fittingMethod_->curve_ = this;
setup();
}
FittedBondDiscountCurve::FittedBondDiscountCurve(
Natural settlementDays,
const Calendar& calendar,
const FittingMethod& fittingMethod,
Array parameters,
Date maxDate,
const DayCounter& dayCounter)
: YieldTermStructure(settlementDays, calendar, dayCounter), accuracy_(1e-10),
maxEvaluations_(0), guessSolution_(std::move(parameters)),
maxDate_(maxDate), fittingMethod_(fittingMethod) {
fittingMethod_->curve_ = this;
setup();
}
FittedBondDiscountCurve::FittedBondDiscountCurve(
const Date& referenceDate,
const FittingMethod& fittingMethod,
Array parameters,
Date maxDate,
const DayCounter& dayCounter)
: YieldTermStructure(referenceDate, Calendar(), dayCounter), accuracy_(1e-10),
maxEvaluations_(0), guessSolution_(std::move(parameters)),
maxDate_(maxDate), fittingMethod_(fittingMethod) {
fittingMethod_->curve_ = this;
setup();
}
void FittedBondDiscountCurve::resetGuess(const Array& guess) {
QL_REQUIRE(guess.empty() || guess.size() == fittingMethod_->size(), "guess is of wrong size");
guessSolution_ = guess;
update();
}
void FittedBondDiscountCurve::performCalculations() const {
if (maxEvaluations_!= 0) {
// we need to fit, so we require helpers
QL_REQUIRE(!bondHelpers_.empty(), "no bond helpers given");
}
if (maxEvaluations_ == 0) {
// no fit, but we need either an explicit max date or
// helpers from which to deduce it
QL_REQUIRE(maxDate_ != Date() || !bondHelpers_.empty(),
"no bond helpers or max date given");
}
if (!bondHelpers_.empty()) {
maxDate_ = Date::minDate();
Date refDate = referenceDate();
// double check bond quotes still valid and/or instruments not expired
for (Size i=0; i<bondHelpers_.size(); ++i) {
ext::shared_ptr<Bond> bond = bondHelpers_[i]->bond();
QL_REQUIRE(bondHelpers_[i]->quote()->isValid(),
io::ordinal(i+1) << " bond (maturity: " <<
bond->maturityDate() << ") has an invalid price quote");
Date bondSettlement = bond->settlementDate();
QL_REQUIRE(bondSettlement>=refDate,
io::ordinal(i+1) << " bond settlemente date (" <<
bondSettlement << ") before curve reference date (" <<
refDate << ")");
QL_REQUIRE(BondFunctions::isTradable(*bond, bondSettlement),
io::ordinal(i+1) << " bond non tradable at " <<
bondSettlement << " settlement date (maturity"
" being " << bond->maturityDate() << ")");
maxDate_ = std::max(maxDate_, bondHelpers_[i]->pillarDate());
bondHelpers_[i]->setTermStructure(
const_cast<FittedBondDiscountCurve*>(this));
}
}
fittingMethod_->init();
fittingMethod_->calculate();
}
FittedBondDiscountCurve::FittingMethod::FittingMethod(
bool constrainAtZero,
const Array& weights,
ext::shared_ptr<OptimizationMethod> optimizationMethod,
Array l2,
const Real minCutoffTime,
const Real maxCutoffTime,
Constraint constraint)
: constrainAtZero_(constrainAtZero), weights_(weights), l2_(std::move(l2)),
calculateWeights_(weights.empty()), optimizationMethod_(std::move(optimizationMethod)),
constraint_(std::move(constraint)),
minCutoffTime_(minCutoffTime), maxCutoffTime_(maxCutoffTime) {
if (constraint_.empty())
constraint_ = NoConstraint();
}
void FittedBondDiscountCurve::FittingMethod::init() {
if (curve_->maxEvaluations_ == 0)
return; // we can skip the rest
// yield conventions
DayCounter yieldDC = curve_->dayCounter();
Compounding yieldComp = Compounded;
Frequency yieldFreq = Annual;
Size n = curve_->bondHelpers_.size();
costFunction_ = ext::make_shared<FittingCost>(this);
for (auto& bondHelper : curve_->bondHelpers_) {
bondHelper->setTermStructure(curve_);
}
if (calculateWeights_) {
if (weights_.empty())
weights_ = Array(n);
Real squaredSum = 0.0;
for (Size i=0; i<curve_->bondHelpers_.size(); ++i) {
ext::shared_ptr<Bond> bond = curve_->bondHelpers_[i]->bond();
Real amount = curve_->bondHelpers_[i]->quote()->value();
Bond::Price price(amount, curve_->bondHelpers_[i]->priceType());
Date bondSettlement = bond->settlementDate();
Rate ytm = BondFunctions::yield(*bond, price,
yieldDC, yieldComp, yieldFreq,
bondSettlement);
Time dur = BondFunctions::duration(*bond, ytm,
yieldDC, yieldComp, yieldFreq,
Duration::Modified,
bondSettlement);
weights_[i] = 1.0/dur;
squaredSum += weights_[i]*weights_[i];
}
weights_ /= std::sqrt(squaredSum);
}
QL_REQUIRE(weights_.size() == n,
"Given weights do not cover all boostrapping helpers");
if (!l2_.empty()) {
QL_REQUIRE(l2_.size() == size(),
"Given penalty factors do not cover all parameters");
QL_REQUIRE(!curve_->guessSolution_.empty(), "L2 penalty requires a guess");
}
}
void FittedBondDiscountCurve::FittingMethod::calculate() {
if (curve_->maxEvaluations_ == 0)
{
// Don't calculate, simply use the given parameters to
// provide a fitted curve. This turns the instance into
// an evaluator of the parametric curve, for example
// allowing to use the parameters for a credit spread
// curve calculated with bonds in one currency to be
// coupled to a discount curve in another currency.
QL_REQUIRE(curve_->guessSolution_.size() == size(),
"wrong number of parameters");
solution_ = curve_->guessSolution_;
numberOfIterations_ = 0;
costValue_ = Null<Real>();
errorCode_ = EndCriteria::None;
return;
}
FittingCost& costFunction = *costFunction_;
// start with the guess solution, if it exists
Array x(size(), 0.0);
if (!curve_->guessSolution_.empty()) {
QL_REQUIRE(curve_->guessSolution_.size() == size(), "wrong size for guess");
x = curve_->guessSolution_;
}
// workaround for backwards compatibility
ext::shared_ptr<OptimizationMethod> optimization = optimizationMethod_;
if (!optimization) {
optimization = ext::make_shared<Simplex>(curve_->simplexLambda_);
}
Problem problem(costFunction, constraint_, x);
Real rootEpsilon = curve_->accuracy_;
Real functionEpsilon = curve_->accuracy_;
Real gradientNormEpsilon = curve_->accuracy_;
EndCriteria endCriteria(curve_->maxEvaluations_,
curve_->maxStationaryStateIterations_,
rootEpsilon,
functionEpsilon,
gradientNormEpsilon);
errorCode_ = optimization->minimize(problem,endCriteria);
solution_ = problem.currentValue();
numberOfIterations_ = problem.functionEvaluation();
costValue_ = problem.functionValue();
// save the results as the guess solution, in case of recalculation
curve_->guessSolution_ = solution_;
}
FittedBondDiscountCurve::FittingMethod::FittingCost::FittingCost(
FittedBondDiscountCurve::FittingMethod* fittingMethod)
: fittingMethod_(fittingMethod) {}
Real FittedBondDiscountCurve::FittingMethod::FittingCost::value(
const Array& x) const {
Real squaredError = 0.0;
Array vals = values(x);
for (Real val : vals) {
squaredError += val;
}
return squaredError;
}
Array FittedBondDiscountCurve::FittingMethod::FittingCost::values(const Array &x) const {
Size n = fittingMethod_->curve_->bondHelpers_.size();
Size N = fittingMethod_->l2_.size();
// set solution so that fittingMethod_->curve_ represents the current trial
// the final solution will be set in FittingMethod::calculate() later on
fittingMethod_->solution_ = x;
Array values(n + N);
for (Size i=0; i<n; ++i) {
ext::shared_ptr<BondHelper> helper = fittingMethod_->curve_->bondHelpers_[i];
Real error = helper->impliedQuote() - helper->quote()->value();
Real weightedError = fittingMethod_->weights_[i] * error;
values[i] = weightedError * weightedError;
}
if (N != 0) {
for (Size i = 0; i < N; ++i) {
Real error = x[i] - fittingMethod_->curve_->guessSolution_[i];
values[i + n] = fittingMethod_->l2_[i] * error * error;
}
}
return values;
}
}
|