File: shortratemodels.cpp

package info (click to toggle)
quantlib 0.3.13-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 11,964 kB
  • ctags: 11,071
  • sloc: cpp: 69,443; ansic: 21,483; sh: 8,860; makefile: 1,824; lisp: 86
file content (237 lines) | stat: -rw-r--r-- 8,319 bytes parent folder | download
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
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2005 StatPro Italia srl

 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/reference/license.html>.

 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 "shortratemodels.hpp"
#include "utilities.hpp"
#include <ql/ShortRateModels/OneFactorModels/hullwhite.hpp>
#include <ql/ShortRateModels/CalibrationHelpers/swaptionhelper.hpp>
#include <ql/PricingEngines/Swaption/all.hpp>
#include <ql/Indexes/euribor.hpp>
#include <ql/Indexes/indexmanager.hpp>
#include <ql/DayCounters/all.hpp>
#include <ql/Optimization/simplex.hpp>
#include <ql/TermStructures/discountcurve.hpp>

using namespace QuantLib;
using namespace boost::unit_test_framework;

QL_BEGIN_TEST_LOCALS(ShortRateModelTest)

struct CalibrationData {
    Integer start;
    Integer length;
    Volatility volatility;
};

void teardown() {
    Settings::instance().evaluationDate() = Date();
    IndexManager::instance().clearHistories();
}

QL_END_TEST_LOCALS(ShortRateModelTest)


void ShortRateModelTest::testCachedHullWhite() {
    #if !defined(QL_PATCH_BORLAND)

    BOOST_MESSAGE("Testing Hull-White calibration against cached values...");

    QL_TEST_BEGIN

    Date today(15, February, 2002);
    Date settlement(19, February, 2002);
    Settings::instance().evaluationDate() = today;

    Handle<YieldTermStructure> termStructure;
    termStructure.linkTo(flatRate(settlement,0.04875825,
                                  Actual365Fixed()));

    boost::shared_ptr<HullWhite> model(new HullWhite(termStructure));

    CalibrationData data[] = {{ 1, 5, 0.1148 },
                              { 2, 4, 0.1108 },
                              { 3, 3, 0.1070 },
                              { 4, 2, 0.1021 },
                              { 5, 1, 0.1000 }};

    boost::shared_ptr<Xibor> index(new Euribor6M(termStructure));

    std::vector<boost::shared_ptr<CalibrationHelper> > swaptions;
    for (Size i=0; i<LENGTH(data); i++) {
        boost::shared_ptr<Quote> vol(new SimpleQuote(data[i].volatility));
        boost::shared_ptr<CalibrationHelper> helper(
                             new SwaptionHelper(Period(data[i].start, Years),
                                                Period(data[i].length, Years),
                                                Handle<Quote>(vol),
                                                index,
                                                Annual, Thirty360(),
                                                Actual360(), termStructure));
        helper->setPricingEngine(boost::shared_ptr<PricingEngine>(
                                        new JamshidianSwaptionEngine(model)));
        swaptions.push_back(helper);
    }

    Real lambda = 0.5;
    Simplex simplex(lambda, 1e-9);
    simplex.setEndCriteria(EndCriteria(10000, 1e-7));
    model->calibrate(swaptions, simplex);

    #if defined(QL_USE_INDEXED_COUPON)
    Real cachedA = 0.0484921, cachedSigma = 0.00591608;
    #else
    Real cachedA = 0.0458489, cachedSigma = 0.00582708;
    #endif
    Real tolerance = 1.0e-6;

    if (std::fabs(model->params()[0]-cachedA) > tolerance
        || std::fabs(model->params()[1]-cachedSigma) > tolerance) {
        BOOST_ERROR("Failed to reproduce cached calibration results:\n"
                    << "calculated: a = " << model->params()[0] << ", "
                    << "sigma = " << model->params()[1] << "\n"
                    << "expected:   a = " << cachedA << ", "
                    << "sigma = " << cachedSigma);
    }

    QL_TEST_TEARDOWN
    #endif
}


void ShortRateModelTest::testSwaps() {
    #if !defined(QL_PATCH_BORLAND)

    BOOST_MESSAGE("Testing Hull-White swap pricing against known values...");

    QL_TEST_BEGIN

    Date today = Settings::instance().evaluationDate();
    Calendar calendar = TARGET();
    today = calendar.adjust(today);
    Settings::instance().evaluationDate() = today;

    Date settlement = calendar.advance(today,2,Days);

    Date dates[] = {
        settlement,
        calendar.advance(settlement,1,Weeks),
        calendar.advance(settlement,1,Months),
        calendar.advance(settlement,3,Months),
        calendar.advance(settlement,6,Months),
        calendar.advance(settlement,9,Months),
        calendar.advance(settlement,1,Years),
        calendar.advance(settlement,2,Years),
        calendar.advance(settlement,3,Years),
        calendar.advance(settlement,5,Years),
        calendar.advance(settlement,10,Years),
        calendar.advance(settlement,15,Years)
    };
    DiscountFactor discounts[] = {
        1.0,
        0.999258,
        0.996704,
        0.990809,
        0.981798,
        0.972570,
        0.963430,
        0.929532,
        0.889267,
        0.803693,
        0.596903,
        0.433022
    };

    Handle<YieldTermStructure> termStructure;
    termStructure.linkTo(boost::shared_ptr<YieldTermStructure>(
       new DiscountCurve(
           std::vector<Date>(dates,dates+LENGTH(dates)),
           std::vector<DiscountFactor>(discounts,discounts+LENGTH(discounts)),
           Actual365Fixed())));

    boost::shared_ptr<HullWhite> model(new HullWhite(termStructure));

    Integer start[] = { -3, 0, 3 };
    Integer length[] = { 2, 5, 10 };
    Rate rates[] = { 0.02, 0.04, 0.06 };
    boost::shared_ptr<Xibor> euribor(new Euribor6M(termStructure));

    boost::shared_ptr<PricingEngine> engine(
                                        new TreeVanillaSwapEngine(model,120));

    #if defined(QL_USE_INDEXED_COUPON)
    Real tolerance = 3.0e-3;
    #else
    Real tolerance = 1.0e-8;
    #endif

    for (Size i=0; i<LENGTH(start); i++) {

        Date startDate = calendar.advance(settlement,start[i],Months);
        if (startDate < today) {
            Date fixingDate = calendar.advance(startDate,-2,Days);
            TimeSeries<Real> pastFixings;
            pastFixings[fixingDate] = 0.03;
            IndexManager::instance().setHistory(euribor->name(),
                                                pastFixings);
        }

        for (Size j=0; j<LENGTH(length); j++) {

            Date maturity = calendar.advance(startDate,length[i],Years);
            Schedule fixedSchedule(calendar,startDate,maturity,
                                   Annual,Unadjusted);
            Schedule floatSchedule(calendar,startDate,maturity,
                                   Semiannual,Following);

            for (Size k=0; k<LENGTH(rates); k++) {

                VanillaSwap swap(true, 1000000.0,
                                 fixedSchedule, rates[k], Thirty360(),
                                 floatSchedule, euribor, 2, 0.0,
                                 Actual360(), termStructure);
                Real expected = swap.NPV();
                swap.setPricingEngine(engine);
                Real calculated = swap.NPV();

                Real error = std::fabs((expected-calculated)/expected);
                if (error > tolerance) {
                    BOOST_ERROR("Failed to reproduce swap NPV:"
                                << QL_FIXED << std::setprecision(9)
                                << "\n    calculated: " << calculated
                                << "\n    expected:   " << expected
                                << QL_SCIENTIFIC
                                << "\n    rel. error: " << error);
                }
            }
        }
    }

    QL_TEST_TEARDOWN
    #endif
}


test_suite* ShortRateModelTest::suite() {
    test_suite* suite = BOOST_TEST_SUITE("Short-rate model tests");
    #if !defined(QL_PATCH_BORLAND)
    suite->add(BOOST_TEST_CASE(&ShortRateModelTest::testCachedHullWhite));
    suite->add(BOOST_TEST_CASE(&ShortRateModelTest::testSwaps));
    #endif
    return suite;
}