/usr/include/ql/termstructures/iterativebootstrap.hpp is in libquantlib0-dev 1.9.1-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008, 2011, 2015 Ferdinando Ametrano
Copyright (C) 2007 Chris Kenyon
Copyright (C) 2007 StatPro Italia srl
Copyright (C) 2015 Paolo Mazzocchi
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.
*/
/*! \file iterativebootstrap.hpp
\brief universal piecewise-term-structure boostrapper.
*/
#ifndef quantlib_iterative_bootstrap_hpp
#define quantlib_iterative_bootstrap_hpp
#include <ql/termstructures/bootstraphelper.hpp>
#include <ql/termstructures/bootstraperror.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/math/solvers1d/finitedifferencenewtonsafe.hpp>
#include <ql/math/solvers1d/brent.hpp>
#include <ql/utilities/dataformatters.hpp>
namespace QuantLib {
//! Universal piecewise-term-structure boostrapper.
template <class Curve>
class IterativeBootstrap {
typedef typename Curve::traits_type Traits;
typedef typename Curve::interpolator_type Interpolator;
public:
IterativeBootstrap();
void setup(Curve* ts);
void calculate() const;
private:
void initialize() const;
Curve* ts_;
Size n_;
Brent firstSolver_;
FiniteDifferenceNewtonSafe solver_;
mutable bool initialized_, validCurve_, loopRequired_;
mutable Size firstAliveHelper_, alive_;
mutable std::vector<Real> previousData_;
mutable std::vector<boost::shared_ptr<BootstrapError<Curve> > > errors_;
};
// template definitions
template <class Curve>
IterativeBootstrap<Curve>::IterativeBootstrap()
: ts_(0), initialized_(false), validCurve_(false),
loopRequired_(Interpolator::global) {}
template <class Curve>
void IterativeBootstrap<Curve>::setup(Curve* ts) {
ts_ = ts;
n_ = ts_->instruments_.size();
QL_REQUIRE(n_ > 0, "no bootstrap helpers given")
for (Size j=0; j<n_; ++j)
ts_->registerWith(ts_->instruments_[j]);
// do not initialize yet: instruments could be invalid here
// but valid later when bootstrapping is actually required
}
template <class Curve>
void IterativeBootstrap<Curve>::initialize() const {
// ensure helpers are sorted
std::sort(ts_->instruments_.begin(), ts_->instruments_.end(),
detail::BootstrapHelperSorter());
// skip expired helpers
Date firstDate = Traits::initialDate(ts_);
QL_REQUIRE(ts_->instruments_[n_-1]->pillarDate()>firstDate,
"all instruments expired");
firstAliveHelper_ = 0;
while (ts_->instruments_[firstAliveHelper_]->pillarDate() <= firstDate)
++firstAliveHelper_;
alive_ = n_-firstAliveHelper_;
QL_REQUIRE(alive_>=Interpolator::requiredPoints-1,
"not enough alive instruments: " << alive_ <<
" provided, " << Interpolator::requiredPoints-1 <<
" required");
// calculate dates and times, create errors_
std::vector<Date>& dates = ts_->dates_;
std::vector<Time>& times = ts_->times_;
dates.resize(alive_+1);
times.resize(alive_+1);
errors_.resize(alive_+1);
dates[0] = firstDate;
times[0] = ts_->timeFromReference(dates[0]);
Date latestRelevantDate, maxDate = firstDate;
// pillar counter: i
// helper counter: j
for (Size i=1, j=firstAliveHelper_; j<n_; ++i, ++j) {
const boost::shared_ptr<typename Traits::helper>& helper =
ts_->instruments_[j];
dates[i] = helper->pillarDate();
times[i] = ts_->timeFromReference(dates[i]);
// check for duplicated pillars
QL_REQUIRE(dates[i-1]!=dates[i],
"more than one instrument with pillar " << dates[i]);
latestRelevantDate = helper->latestRelevantDate();
// check that the helper is really extending the curve, i.e. that
// pillar-sorted helpers are also sorted by latestRelevantDate
QL_REQUIRE(latestRelevantDate > maxDate,
io::ordinal(j+1) << " instrument (pillar: " <<
dates[i] << ") has latestRelevantDate (" <<
latestRelevantDate << ") before or equal to "
"previous instrument's latestRelevantDate (" <<
maxDate << ")");
maxDate = latestRelevantDate;
// when a pillar date is different from the last relevant date the
// convergence loop is required even if the Interpolator is local
if (dates[i] != latestRelevantDate)
loopRequired_ = true;
errors_[i] = boost::shared_ptr<BootstrapError<Curve> >(new
BootstrapError<Curve>(ts_, helper, i));
}
ts_->maxDate_ = maxDate;
// set initial guess only if the current curve cannot be used as guess
if (!validCurve_ || ts_->data_.size()!=alive_+1) {
// ts_->data_[0] is the only relevant item,
// but reasonable numbers might be needed for the whole data vector
// because, e.g., of interpolation's early checks
ts_->data_ = std::vector<Real>(alive_+1, Traits::initialValue(ts_));
previousData_.resize(alive_+1);
}
initialized_ = true;
}
template <class Curve>
void IterativeBootstrap<Curve>::calculate() const {
// we might have to call initialize even if the curve is initialized
// and not moving, just because helpers might be date relative and change
// with evaluation date change.
// anyway it makes little sense to use date relative helpers with a
// non-moving curve if the evaluation date changes
if (!initialized_ || ts_->moving_)
initialize();
// setup helpers
for (Size j=firstAliveHelper_; j<n_; ++j) {
const boost::shared_ptr<typename Traits::helper>& helper =
ts_->instruments_[j];
// check for valid quote
QL_REQUIRE(helper->quote()->isValid(),
io::ordinal(j + 1) << " instrument (maturity: " <<
helper->maturityDate() << ", pillar: " <<
helper->pillarDate() << ") has an invalid quote");
// don't try this at home!
// This call creates helpers, and removes "const".
// There is a significant interaction with observability.
helper->setTermStructure(const_cast<Curve*>(ts_));
}
const std::vector<Time>& times = ts_->times_;
const std::vector<Real>& data = ts_->data_;
Real accuracy = ts_->accuracy_;
Size maxIterations = Traits::maxIterations()-1;
// there might be a valid curve state to use as guess
bool validData = validCurve_;
for (Size iteration=0; ; ++iteration) {
previousData_ = ts_->data_;
for (Size i=1; i<=alive_; ++i) { // pillar loop
// bracket root and calculate guess
Real min = Traits::minValueAfter(i, ts_, validData,
firstAliveHelper_);
Real max = Traits::maxValueAfter(i, ts_, validData,
firstAliveHelper_);
Real guess = Traits::guess(i, ts_, validData,
firstAliveHelper_);
// adjust guess if needed
if (guess>=max)
guess = max - (max-min)/5.0;
else if (guess<=min)
guess = min + (max-min)/5.0;
// extend interpolation if needed
if (!validData) {
try { // extend interpolation a point at a time
// including the pillar to be boostrapped
ts_->interpolation_ = ts_->interpolator_.interpolate(
times.begin(), times.begin()+i+1, data.begin());
} catch (...) {
if (!Interpolator::global)
throw; // no chance to fix it in a later iteration
// otherwise use Linear while the target
// interpolation is not usable yet
ts_->interpolation_ = Linear().interpolate(
times.begin(), times.begin()+i+1, data.begin());
}
ts_->interpolation_.update();
}
try {
if (validData)
solver_.solve(*errors_[i], accuracy, guess, min, max);
else
firstSolver_.solve(*errors_[i], accuracy,guess,min,max);
} catch (std::exception &e) {
// the previous curve state could have been a bad guess
// let's restart without using it
if (validCurve_) {
validCurve_ = validData = false;
continue;
}
QL_FAIL(io::ordinal(iteration+1) << " iteration: failed "
"at " << io::ordinal(i) << " alive instrument, "
"pillar " << errors_[i]->helper()->pillarDate() <<
", maturity " << errors_[i]->helper()->maturityDate() <<
", reference date " << ts_->dates_[0] <<
": " << e.what());
}
}
if (!loopRequired_)
break;
// exit condition
Real change = std::fabs(data[1]-previousData_[1]);
for (Size i=2; i<=alive_; ++i)
change = std::max(change, std::fabs(data[i]-previousData_[i]));
if (change<=accuracy) // convergence reached
break;
QL_REQUIRE(iteration<maxIterations,
"convergence not reached after " << iteration <<
" iterations; last improvement " << change <<
", required accuracy " << accuracy);
validData = true;
}
validCurve_ = true;
}
}
#endif
|