File: termstructures.cpp

package info (click to toggle)
quantlib 1.39-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 41,264 kB
  • sloc: cpp: 396,561; makefile: 6,539; python: 272; sh: 154; lisp: 86
file content (621 lines) | stat: -rw-r--r-- 26,613 bytes parent folder | download | duplicates (2)
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2003 RiskMap 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/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 "toplevelfixture.hpp"
#include "utilities.hpp"
#include <ql/termstructures/yield/compositezeroyieldstructure.hpp>
#include <ql/termstructures/yield/ratehelpers.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/termstructures/yield/piecewiseyieldcurve.hpp>
#include <ql/termstructures/yield/impliedtermstructure.hpp>
#include <ql/termstructures/yield/forwardspreadedtermstructure.hpp>
#include <ql/termstructures/yield/piecewiseforwardspreadedtermstructure.hpp>
#include <ql/termstructures/yield/zerospreadedtermstructure.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/time/daycounters/thirty360.hpp>
#include <ql/math/comparison.hpp>
#include <ql/math/interpolation.hpp>
#include <ql/math/interpolations/forwardflatinterpolation.hpp>
#include <ql/indexes/iborindex.hpp>
#include <ql/currency.hpp>
#include <ql/utilities/dataformatters.hpp>

using namespace QuantLib;
using namespace boost::unit_test_framework;

BOOST_FIXTURE_TEST_SUITE(QuantLibTests, TopLevelFixture)

BOOST_AUTO_TEST_SUITE(TermStructureTests)

struct Datum {
    Integer n;
    TimeUnit units;
    Rate rate;
};

struct CommonVars {
    // common data
    Calendar calendar;
    Natural settlementDays;
    ext::shared_ptr<YieldTermStructure> termStructure;
    ext::shared_ptr<YieldTermStructure> dummyTermStructure;

    // setup
    CommonVars() {
        calendar = TARGET();
        settlementDays = 2;
        Date today = calendar.adjust(Date::todaysDate());
        Settings::instance().evaluationDate() = today;
        Date settlement = calendar.advance(today,settlementDays,Days);
        Datum depositData[] = {
            { 1, Months, 4.581 },
            { 2, Months, 4.573 },
            { 3, Months, 4.557 },
            { 6, Months, 4.496 },
            { 9, Months, 4.490 }
        };
        Datum swapData[] = {
            {  1, Years, 4.54 },
            {  5, Years, 4.99 },
            { 10, Years, 5.47 },
            { 20, Years, 5.89 },
            { 30, Years, 5.96 }
        };
        Size deposits = std::size(depositData),
            swaps = std::size(swapData);

        std::vector<ext::shared_ptr<RateHelper> > instruments(deposits+swaps);
        for (Size i=0; i<deposits; i++) {
            instruments[i] = ext::shared_ptr<RateHelper>(new
                    DepositRateHelper(depositData[i].rate/100,
                                      depositData[i].n*depositData[i].units,
                                      settlementDays, calendar,
                                      ModifiedFollowing, true,
                                      Actual360()));
        }
        ext::shared_ptr<IborIndex> index(new IborIndex("dummy",
                                                       6*Months,
                                                       settlementDays,
                                                       Currency(),
                                                       calendar,
                                                       ModifiedFollowing,
                                                       false,
                                                       Actual360()));
        for (Size i=0; i<swaps; ++i) {
            instruments[i+deposits] = ext::shared_ptr<RateHelper>(new
                    SwapRateHelper(swapData[i].rate/100,
                                   swapData[i].n*swapData[i].units,
                                   calendar,
                                   Annual, Unadjusted, Thirty360(Thirty360::BondBasis),
                                   index));
        }
        termStructure = ext::shared_ptr<YieldTermStructure>(new
                PiecewiseYieldCurve<Discount,LogLinear>(settlement,
                                                        instruments, Actual360()));
        dummyTermStructure = ext::shared_ptr<YieldTermStructure>(new
                PiecewiseYieldCurve<Discount,LogLinear>(settlement,
                                                        instruments, Actual360()));
    }
};

Real sub(Real x, Real y) { return x - y; }


BOOST_AUTO_TEST_CASE(testReferenceChange) {

    BOOST_TEST_MESSAGE("Testing term structure against evaluation date change...");

    CommonVars vars;

    ext::shared_ptr<SimpleQuote> flatRate (new SimpleQuote);
    Handle<Quote> flatRateHandle(flatRate);
    vars.termStructure = ext::shared_ptr<YieldTermStructure>(
                          new FlatForward(vars.settlementDays, NullCalendar(),
                                          flatRateHandle, Actual360()));
    Date today = Settings::instance().evaluationDate();
    flatRate->setValue(.03);
    Integer days[] = { 10, 30, 60, 120, 360, 720 };
    Size i;

    std::vector<DiscountFactor> expected(std::size(days));
    for (i=0; i<std::size(days); i++)
        expected[i] = vars.termStructure->discount(today+days[i]);

    Settings::instance().evaluationDate() = today+30;
    std::vector<DiscountFactor> calculated(std::size(days));
    for (i=0; i<std::size(days); i++)
        calculated[i] = vars.termStructure->discount(today+30+days[i]);

    for (i=0; i<std::size(days); i++) {
        if (!close(expected[i],calculated[i]))
            BOOST_ERROR("\n  Discount at " << days[i] << " days:\n"
                        << std::setprecision(12)
                        << "    before date change: " << expected[i] << "\n"
                        << "    after date change:  " << calculated[i]);
    }
}

BOOST_AUTO_TEST_CASE(testImplied) {

    BOOST_TEST_MESSAGE("Testing consistency of implied term structure...");

    CommonVars vars;

    Real tolerance = 1.0e-10;
    Date today = Settings::instance().evaluationDate();
    Date newToday = today + 3*Years;
    Date newSettlement = vars.calendar.advance(newToday,
                                               vars.settlementDays,Days);
    Date testDate = newSettlement + 5*Years;
    ext::shared_ptr<YieldTermStructure> implied(
        new ImpliedTermStructure(Handle<YieldTermStructure>(vars.termStructure),
                                 newSettlement));
    DiscountFactor baseDiscount = vars.termStructure->discount(newSettlement);
    DiscountFactor discount = vars.termStructure->discount(testDate);
    DiscountFactor impliedDiscount = implied->discount(testDate);
    if (std::fabs(discount - baseDiscount*impliedDiscount) > tolerance)
        BOOST_ERROR(
            "unable to reproduce discount from implied curve\n"
            << std::fixed << std::setprecision(10)
            << "    calculated: " << baseDiscount*impliedDiscount << "\n"
            << "    expected:   " << discount);
}

BOOST_AUTO_TEST_CASE(testImpliedObs) {

    BOOST_TEST_MESSAGE("Testing observability of implied term structure...");

    CommonVars vars;

    Date today = Settings::instance().evaluationDate();
    Date newToday = today + 3*Years;
    Date newSettlement = vars.calendar.advance(newToday,
                                               vars.settlementDays,Days);
    RelinkableHandle<YieldTermStructure> h;
    ext::shared_ptr<YieldTermStructure> implied(
                                  new ImpliedTermStructure(h, newSettlement));
    Flag flag;
    flag.registerWith(implied);
    h.linkTo(vars.termStructure);
    if (!flag.isUp())
        BOOST_ERROR("Observer was not notified of term structure change");
}

BOOST_AUTO_TEST_CASE(testFSpreaded) {

    BOOST_TEST_MESSAGE("Testing consistency of forward-spreaded term structure...");

    CommonVars vars;

    Real tolerance = 1.0e-10;
    ext::shared_ptr<Quote> me(new SimpleQuote(0.01));
    Handle<Quote> mh(me);
    ext::shared_ptr<YieldTermStructure> spreaded(
        new ForwardSpreadedTermStructure(
            Handle<YieldTermStructure>(vars.termStructure),mh));
    Date testDate = vars.termStructure->referenceDate() + 5*Years;
    DayCounter tsdc  = vars.termStructure->dayCounter();
    DayCounter sprdc = spreaded->dayCounter();
    Rate forward = vars.termStructure->forwardRate(testDate, testDate, tsdc,
                                                   Continuous, NoFrequency);
    Rate spreadedForward = spreaded->forwardRate(testDate, testDate, sprdc,
                                                 Continuous, NoFrequency);
    if (std::fabs(forward - (spreadedForward-me->value())) > tolerance)
        BOOST_ERROR(
            "unable to reproduce forward from spreaded curve\n"
            << std::setprecision(10)
            << "    calculated: "
            << io::rate(spreadedForward-me->value()) << "\n"
            << "    expected:   " << io::rate(forward));
}

BOOST_AUTO_TEST_CASE(testFSpreadedObs) {

    BOOST_TEST_MESSAGE("Testing observability of forward-spreaded "
                       "term structure...");

    CommonVars vars;

    ext::shared_ptr<SimpleQuote> me(new SimpleQuote(0.01));
    Handle<Quote> mh(me);
    RelinkableHandle<YieldTermStructure> h; //(vars.dummyTermStructure);
    ext::shared_ptr<YieldTermStructure> spreaded(
        new ForwardSpreadedTermStructure(h,mh));
    Flag flag;
    flag.registerWith(spreaded);
    h.linkTo(vars.termStructure);
    if (!flag.isUp())
        BOOST_ERROR("Observer was not notified of term structure change");
    flag.lower();
    me->setValue(0.005);
    if (!flag.isUp())
        BOOST_ERROR("Observer was not notified of spread change");
}

BOOST_AUTO_TEST_CASE(testZSpreaded) {

    BOOST_TEST_MESSAGE("Testing consistency of zero-spreaded term structure...");

    CommonVars vars;

    Real tolerance = 1.0e-10;
    ext::shared_ptr<Quote> me(new SimpleQuote(0.01));
    Handle<Quote> mh(me);
    ext::shared_ptr<YieldTermStructure> spreaded(
        new ZeroSpreadedTermStructure(
            Handle<YieldTermStructure>(vars.termStructure),mh));
    Date testDate = vars.termStructure->referenceDate() + 5*Years;
    DayCounter rfdc  = vars.termStructure->dayCounter();
    Rate zero = vars.termStructure->zeroRate(testDate, rfdc,
                                             Continuous, NoFrequency);
    Rate spreadedZero = spreaded->zeroRate(testDate, rfdc,
                                           Continuous, NoFrequency);
    if (std::fabs(zero - (spreadedZero-me->value())) > tolerance)
        BOOST_ERROR(
            "unable to reproduce zero yield from spreaded curve\n"
            << std::setprecision(10)
            << "    calculated: " << io::rate(spreadedZero-me->value()) << "\n"
            << "    expected:   " << io::rate(zero));
}

BOOST_AUTO_TEST_CASE(testZSpreadedObs) {

    BOOST_TEST_MESSAGE("Testing observability of zero-spreaded term structure...");

    CommonVars vars;

    ext::shared_ptr<SimpleQuote> me(new SimpleQuote(0.01));
    Handle<Quote> mh(me);
    RelinkableHandle<YieldTermStructure> h(vars.dummyTermStructure);

    ext::shared_ptr<YieldTermStructure> spreaded(
        new ZeroSpreadedTermStructure(h,mh));
    Flag flag;
    flag.registerWith(spreaded);
    h.linkTo(vars.termStructure);
    if (!flag.isUp())
        BOOST_ERROR("Observer was not notified of term structure change");
    flag.lower();
    me->setValue(0.005);
    if (!flag.isUp())
        BOOST_ERROR("Observer was not notified of spread change");
}

BOOST_AUTO_TEST_CASE(testCreateWithNullUnderlying) {
    BOOST_TEST_MESSAGE(
        "Testing that a zero-spreaded curve can be created with "
        "a null underlying curve...");

    CommonVars vars;

    Handle<Quote> spread(ext::shared_ptr<Quote>(new SimpleQuote(0.01)));
    RelinkableHandle<YieldTermStructure> underlying;
    // this shouldn't throw
    ext::shared_ptr<YieldTermStructure> spreaded(
        new ZeroSpreadedTermStructure(underlying,spread));
    // if we do this, the curve can work.
    underlying.linkTo(vars.termStructure);
    // check that we can use it
    spreaded->referenceDate();
}

BOOST_AUTO_TEST_CASE(testLinearInterpolationSpreadedForwardRate) {

    BOOST_TEST_MESSAGE("Testing linear interpolation of forward rates between two dates...");

    CommonVars vars;

    // Define the forward rate spreads
    auto calendar = vars.calendar;
    auto dc = vars.termStructure->dayCounter();
    Date today = Settings::instance().evaluationDate();
    Date settlement = calendar.advance(today, vars.settlementDays, Days);
    ext::shared_ptr<SimpleQuote> spread1 = ext::make_shared<SimpleQuote>(0.02);
    ext::shared_ptr<SimpleQuote> spread2 = ext::make_shared<SimpleQuote>(0.03);
    std::vector<Handle<Quote>> spreads = { Handle<Quote>(spread1), Handle<Quote>(spread2) };

    // Define the dates where spreads are specified
    std::vector<Date> spreadDates = { vars.calendar.advance(today, 100, Days),
                                      vars.calendar.advance(today, 150, Days) };

    Date interpolationDate = vars.calendar.advance(today, 120, Days);

    // Create the forward spreaded term structure
    ext::shared_ptr<YieldTermStructure> spreadedTermStructure =
        ext::make_shared<InterpolatedPiecewiseForwardSpreadedTermStructure<Linear>>(
                        Handle<YieldTermStructure>(vars.termStructure),
                        spreads, spreadDates);

    // Reference dates
    Date d0 = vars.calendar.advance(today, 100, Days);
    Date d1 = vars.calendar.advance(today, 150, Days);
    Date d2 = vars.calendar.advance(today, 120, Days);

    // Compute expected interpolated forward rate
    Real time0 = dc.yearFraction(settlement, d0);
    Real time1 = dc.yearFraction(settlement, d1);
    Real time2 = dc.yearFraction(settlement, d2);

    Real m = (0.03 - 0.02) / (time1 - time0);

    Time t = dc.yearFraction(settlement, interpolationDate);
    Rate expectedForwardRate = vars.termStructure->forwardRate(t, t, Continuous, NoFrequency, true) + (m * (time2 - time0) + 0.02);
    Rate interpolatedForwardRate = spreadedTermStructure->forwardRate(t, t, Continuous, NoFrequency, true);

    Real tolerance = 1e-9;

    if (std::fabs(interpolatedForwardRate - expectedForwardRate) > tolerance)
        BOOST_ERROR(
            "unable to reproduce interpolated forward rate\n"
            << std::setprecision(10)
            << "    calculated: " << io::rate(interpolatedForwardRate) << "\n"
            << "    expected: "   << io::rate(expectedForwardRate));
}

BOOST_AUTO_TEST_CASE(testForwardFlatInterpolationSpreadedForwardRate) {

    BOOST_TEST_MESSAGE("Testing forward flat interpolation of forward rates between two dates...");

    CommonVars vars;

    auto dc = vars.termStructure->dayCounter();
    Date today = Settings::instance().evaluationDate();

    // Define the forward rate spreads
    ext::shared_ptr<SimpleQuote> spread1 = ext::make_shared<SimpleQuote>(0.02);
    ext::shared_ptr<SimpleQuote> spread2 = ext::make_shared<SimpleQuote>(0.03);
    std::vector<Handle<Quote>> spreads = { Handle<Quote>(spread1), Handle<Quote>(spread2) };

    // Define the spread dates
    std::vector<Date> spreadDates = { vars.calendar.advance(today, 75, Days),
                                      vars.calendar.advance(today, 260, Days) };

    Date interpolationDate = vars.calendar.advance(today, 100, Days);

    // Create the forward spreaded term structure using ForwardFlat interpolation
    ext::shared_ptr<YieldTermStructure> spreadedTermStructure =
        ext::make_shared<InterpolatedPiecewiseForwardSpreadedTermStructure<ForwardFlat>>(
                        Handle<YieldTermStructure>(vars.termStructure),
                        spreads, spreadDates);

    Time t = dc.yearFraction(today, interpolationDate);
    Rate expectedForwardRate = vars.termStructure->forwardRate(t, t, Continuous, NoFrequency, true) +
                               spread1->value();

    Rate interpolatedForwardRate = spreadedTermStructure->forwardRate(t, t, Continuous, NoFrequency, true);

    Real tolerance = 1e-9;

    if (std::fabs(interpolatedForwardRate - expectedForwardRate) > tolerance)
        BOOST_ERROR(
            "unable to reproduce interpolated forward rate\n"
            << std::setprecision(10)
            << "    calculated: " << io::rate(interpolatedForwardRate) << "\n"
            << "    expected: "   << io::rate(expectedForwardRate));
}


BOOST_AUTO_TEST_CASE(testBackwardFlatInterpolationSpreadedForwardRate) {

    BOOST_TEST_MESSAGE("Testing backward flat interpolation of forward rates between two dates...");

    CommonVars vars;

    auto dc = vars.termStructure->dayCounter();
    Date today = Settings::instance().evaluationDate();

    // Define the forward rate spreads
    ext::shared_ptr<SimpleQuote> spread1 = ext::make_shared<SimpleQuote>(0.02);
    ext::shared_ptr<SimpleQuote> spread2 = ext::make_shared<SimpleQuote>(0.03);
    ext::shared_ptr<SimpleQuote> spread3 = ext::make_shared<SimpleQuote>(0.04);
    std::vector<Handle<Quote>> spreads = {
        Handle<Quote>(spread1), Handle<Quote>(spread2), Handle<Quote>(spread3)
    };

    // Define the spread dates
    std::vector<Date> spreadDates = { vars.calendar.advance(today, 100, Days),
                                      vars.calendar.advance(today, 200, Days),
                                      vars.calendar.advance(today, 300, Days) };

    Date interpolationDate = vars.calendar.advance(today, 110, Days);

    ext::shared_ptr<YieldTermStructure> spreadedTermStructure =
        ext::make_shared<InterpolatedPiecewiseForwardSpreadedTermStructure<BackwardFlat>>(
                        Handle<YieldTermStructure>(vars.termStructure),
                        spreads, spreadDates);

    Time t = dc.yearFraction(today, interpolationDate);
    Rate expectedForwardRate = vars.termStructure->forwardRate(t, t, Continuous, NoFrequency, true) +
                               spread2->value();

    Rate interpolatedForwardRate = spreadedTermStructure->forwardRate(t, t, Continuous, NoFrequency, true);

    Real tolerance = 1e-9;

    if (std::fabs(interpolatedForwardRate - expectedForwardRate) > tolerance)
        BOOST_ERROR(
            "unable to reproduce interpolated forward rate\n"
            << std::setprecision(10)
            << "    calculated: " << io::rate(interpolatedForwardRate) << "\n"
            << "    expected: "   << io::rate(expectedForwardRate));
}


BOOST_AUTO_TEST_CASE(testBackwardFlatInterpolationZeroRate) {

    BOOST_TEST_MESSAGE("Testing backward flat interpolation of zero rates between two dates...");

    CommonVars vars;
    auto dc = vars.termStructure->dayCounter();
    Date today = Settings::instance().evaluationDate();
    Date referenceDate = vars.termStructure->referenceDate();

    // Define the zero rate spreads
    ext::shared_ptr<SimpleQuote> spread1 = ext::make_shared<SimpleQuote>(0.02);
    ext::shared_ptr<SimpleQuote> spread2 = ext::make_shared<SimpleQuote>(0.03);
    ext::shared_ptr<SimpleQuote> spread3 = ext::make_shared<SimpleQuote>(0.04);
    std::vector<Handle<Quote>> spreads = {
        Handle<Quote>(spread1), Handle<Quote>(spread2), Handle<Quote>(spread3)
    };

    // Define the spread dates
    std::vector<Date> spreadDates = { vars.calendar.advance(today, 100, Days),
                                      vars.calendar.advance(today, 200, Days),
                                      vars.calendar.advance(today, 300, Days) };
    std::vector<Time> times(spreadDates.size());
    std::vector<Real> spreadValues(spreadDates.size());
    for (Size i = 0; i < spreadDates.size(); i++) {
            times[i] = dc.yearFraction(referenceDate, spreadDates[i]);
            spreadValues[i] = spreads[i]->value();
    }

    Date interpolationDate = vars.calendar.advance(today, 110, Days);

    ext::shared_ptr<YieldTermStructure> spreadedTermStructure =
        ext::make_shared<InterpolatedPiecewiseForwardSpreadedTermStructure<BackwardFlat>>(
                        Handle<YieldTermStructure>(vars.termStructure),
                        spreads, spreadDates);

    BackwardFlatInterpolation bckFlatInterpolation(times.begin(), times.end(), 
                                                  spreadValues.begin()); 

    Time t = dc.yearFraction(today, interpolationDate);
    Rate nonSpreadedRate = vars.termStructure->zeroRate(t, Continuous, NoFrequency, true);
    Rate spreadPrimitive = bckFlatInterpolation.primitive(t, true) / t;
    Rate expectedZeroRate = nonSpreadedRate + spreadPrimitive;

    Rate interpolatedZeroRate = spreadedTermStructure->zeroRate(t, Continuous, NoFrequency, true);

    Real tolerance = 1e-9;

    if (std::fabs(interpolatedZeroRate - expectedZeroRate) > tolerance)
        BOOST_ERROR(
            "unable to reproduce interpolated zero rate\n"
            << std::setprecision(10)
            << "    calculated: " << io::rate(interpolatedZeroRate) << "\n"
            << "    expected: "   << io::rate(expectedZeroRate));
}


BOOST_AUTO_TEST_CASE(testLinkToNullUnderlying) {
    BOOST_TEST_MESSAGE(
        "Testing that an underlying curve can be relinked to "
        "a null underlying curve...");

    CommonVars vars;

    Handle<Quote> spread(ext::shared_ptr<Quote>(new SimpleQuote(0.01)));
    RelinkableHandle<YieldTermStructure> underlying(vars.termStructure);
    ext::shared_ptr<YieldTermStructure> spreaded(
        new ZeroSpreadedTermStructure(underlying,spread));
    // check that we can use it
    spreaded->referenceDate();
    // if we do this, the curve can't work anymore. But it shouldn't
    // throw as long as we don't try to use it.
    underlying.reset();
}

BOOST_AUTO_TEST_CASE(testCompositeZeroYieldStructures) {
    BOOST_TEST_MESSAGE(
        "Testing composite zero yield structures...");

    Settings::instance().evaluationDate() = Date(10, Nov, 2017);

    // First curve
    std::vector<Date> dates = {Date(10, Nov, 2017), Date(13, Nov, 2017), Date(12, Feb, 2018),
                               Date(10, May, 2018), Date(10, Aug, 2018), Date(12, Nov, 2018),
                               Date(21, Dec, 2018), Date(15, Jan, 2020), Date(31, Mar, 2021),
                               Date(28, Feb, 2023), Date(21, Dec, 2026), Date(31, Jan, 2030),
                               Date(28, Feb, 2031), Date(31, Mar, 2036), Date(28, Feb, 2041),
                               Date(28, Feb, 2048), Date(31, Dec, 2141)};

    std::vector<Rate> rates = {0.0655823213132524, 0.0655823213132524, 0.0699455024156877,
                               0.0799107139233497, 0.0813931951022577, 0.0841615820666691,
                               0.0501297919004145, 0.0823483583439658, 0.0860720030924466,
                               0.0922887604375688, 0.10588902278996,   0.117021968693922,
                               0.109824660896137,  0.109231572878364,  0.119218123236241,
                               0.128647300167664,  0.0506086995288751};

    ext::shared_ptr<YieldTermStructure> termStructure1 = ext::shared_ptr<YieldTermStructure>(
        new ForwardCurve(dates, rates, Actual365Fixed(), NullCalendar()));

    // Second curve
    dates = {Date(10, Nov, 2017), Date(13, Nov, 2017), Date(11, Dec, 2017), Date(12, Feb, 2018),
             Date(10, May, 2018), Date(31, Jan, 2022), Date(7, Dec, 2023),  Date(31, Jan, 2025),
             Date(31, Mar, 2028), Date(7, Dec, 2033),  Date(1, Feb, 2038),  Date(2, Apr, 2046),
             Date(2, Jan, 2051),  Date(31, Dec, 2141)};

    rates = {0.056656806197189,  0.056656806197189,  0.0419541633454473, 0.0286681050019797,
             0.0148840226959593, 0.0246680238374363, 0.0255349067810599, 0.0298907184711927,
             0.0263943927922053, 0.0291924526539802, 0.0270049276163556, 0.028775807327614,
             0.0293567711641792, 0.010518655099659};

    ext::shared_ptr<YieldTermStructure> termStructure2 = ext::shared_ptr<YieldTermStructure>(
        new ForwardCurve(dates, rates, Actual365Fixed(), NullCalendar()));

    typedef Real(*binary_f)(Real, Real);

    ext::shared_ptr<YieldTermStructure> compoundCurve = ext::shared_ptr<YieldTermStructure>(
        new CompositeZeroYieldStructure<binary_f>(Handle<YieldTermStructure>(termStructure1), Handle<YieldTermStructure>(termStructure2), sub));

    // Expected values
    dates = {Date(10, Nov, 2017), Date(15, Dec, 2017), Date(15, Jun, 2018), Date(15, Sep, 2029),
             Date(15, Sep, 2038), Date(15, Mar, 2046), Date(15, Dec, 2141)};

    rates = {0.00892551511527986, 0.0278755322562788, 0.0512001768603456, 0.0729941474263546,
             0.0778333309498459,  0.0828451659139004, 0.0503573807521742};

    Real tolerance = 1.0e-10;
    for (Size i = 0; i < dates.size(); ++i) {
        Rate actual = compoundCurve->zeroRate(dates[i], Actual365Fixed(), Continuous).rate();
        Rate expected = rates[i];

        if (std::fabs(actual - expected) > tolerance)
            BOOST_ERROR(
                "unable to reproduce zero yield rate from composite input curve\n"
                << std::fixed << std::setprecision(10)
                << "    calculated: " << actual << "\n"
                << "    expected:   " << expected);
    }
}

BOOST_AUTO_TEST_CASE(testNullTimeToReference) {
    BOOST_TEST_MESSAGE("Testing zero-rate calculation for null time-to-reference...");

    Rate rate = 0.02;
    auto dayCount = Thirty360(Thirty360::BondBasis);
    auto curve = FlatForward(Date(30, August, 2023), rate, dayCount);

    // the time between August 30th and 31st is null for the 30/360 day count convention
    Rate expected = rate;
    Rate calculated = curve.zeroRate(Date(31, August, 2023), dayCount, Continuous);
    Real tolerance = 1.0e-10;

    if (std::fabs(calculated - expected) > tolerance)
        BOOST_ERROR("unable to reproduce zero yield rate from curve\n"
                    << std::fixed << std::setprecision(10)
                    << "    calculated: " << calculated << "\n"
                    << "    expected:   " << expected);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()