Logo
Fully annotated reference manual - version 1.8.12
Loading...
Searching...
No Matches
hullwhitebucketing.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2017 Quaternion Risk Management Ltd
3 All rights reserved.
4
5 This file is part of ORE, a free-software/open-source library
6 for transparent pricing and risk analysis - http://opensourcerisk.org
7
8 ORE is free software: you can redistribute it and/or modify it
9 under the terms of the Modified BSD License. You should have received a
10 copy of the license along with this program.
11 The license is also available online at <http://opensourcerisk.org>
12
13 This program is distributed on the basis that it will form a useful
14 contribution to risk analytics and model standardisation, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
17*/
18
20#include <ql/math/array.hpp>
21
22#include <algorithm>
23
24using namespace QuantLib;
25
26namespace QuantExt {
27
28Bucketing::Bucketing(const Real lowerBound, const Real upperBound, const Size n) {
29 buckets_.resize(n + 1);
30 Real h = (upperBound - lowerBound) / static_cast<Real>(n);
31 for (Size i = 0; i <= n; ++i)
32 buckets_[i] = lowerBound + static_cast<Real>(i) * h;
34 uniformBuckets_ = true;
35 lowerBound_ = lowerBound;
36 upperBound_ = upperBound;
37 h_ = h;
38}
39
40Size Bucketing::index(const Real x) const {
41 if (uniformBuckets_) {
42 return std::min<Size>(buckets_.size() - 1,
43 std::max(0, static_cast<int>(std::floor((x - lowerBound_) / h_) + 1)));
44 } else {
45 return std::upper_bound(buckets_.begin(), buckets_.end(), x) - buckets_.begin();
46 }
47}
48
50 QL_REQUIRE(!buckets_.empty(), "Bucketing::initBuckets() no buckets given");
51 QL_REQUIRE(std::is_sorted(buckets_.begin(), buckets_.end()), "buckets must be sorted");
52 if (!close_enough(buckets_.back(), QL_MAX_REAL)) {
53 buckets_.insert(buckets_.end(), QL_MAX_REAL);
54 }
55}
56
58 Size N = buckets_.size();
59 p_ = Array(N, 0);
60 A_ = Array(N, 0);
61 Size zeroIdx = index(0.0);
62 p_[zeroIdx] = 1.0;
63 A_[zeroIdx] = 0.0;
64}
65
67 Size N = buckets_.size();
68 for (Size i = 0; i < N; ++i) {
69 if (QuantLib::close_enough(p_[i], 0.0)) {
70 // the probability for a bucket is zero => fill average with midpoint (endpoints)
71 if (i == 0) {
72 A_[i] = buckets_.front();
73 } else if (i == N - 1) {
74 A_[i] = buckets_[N - 2];
75 } else {
76 A_[i] = 0.5 * (buckets_[i - 1] + buckets_[i]);
77 }
78 } else {
79 // otherwise normalize the bucket to represent the conditional aveage for this bucket
80 A_[i] /= p_[i];
81 }
82 }
83}
84
85} // namespace QuantExt
Bucketing(I bucketsBegin, I bucketsEnd)
std::vector< Real > buckets_
Size index(const Real x) const
probability bucketing as in Valuation of a CDO and an nth to Default CDS without Monte Carlo Simulati...
Filter close_enough(const RandomVariable &x, const RandomVariable &y)