File: Bonds.java

package info (click to toggle)
quantlib-swig 1.15-1
  • links: PTS
  • area: main
  • in suites: buster
  • size: 103,484 kB
  • sloc: cpp: 2,029,354; cs: 61,237; java: 45,425; perl: 27,362; python: 22,024; ruby: 989; sh: 741; makefile: 319
file content (545 lines) | stat: -rw-r--r-- 22,296 bytes parent folder | download | duplicates (4)
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

/*
 Copyright (C) 2014 Wondersys 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.
*/

package examples;

import java.util.ArrayList;

import org.quantlib.Actual360;
import org.quantlib.Actual365Fixed;
import org.quantlib.ActualActual;
import org.quantlib.BlackIborCouponPricer;
import org.quantlib.BusinessDayConvention;
import org.quantlib.Calendar;
import org.quantlib.Compounding;
import org.quantlib.ConstantOptionletVolatility;
import org.quantlib.Date;
import org.quantlib.DateGeneration;
import org.quantlib.DayCounter;
import org.quantlib.DepositRateHelper;
import org.quantlib.DiscountingBondEngine;
import org.quantlib.DoubleVector;
import org.quantlib.Euribor6M;
import org.quantlib.FixedRateBond;
import org.quantlib.FixedRateBondHelper;
import org.quantlib.FloatingRateBond;
import org.quantlib.FloatingRateCouponPricer;
import org.quantlib.Frequency;
import org.quantlib.IborCouponPricer;
import org.quantlib.IborIndex;
import org.quantlib.Month;
import org.quantlib.OptionletVolatilityStructureHandle;
import org.quantlib.Period;
import org.quantlib.PiecewiseFlatForward;
import org.quantlib.PiecewiseLinearForward;
import org.quantlib.PricingEngine;
import org.quantlib.QuantLib;
import org.quantlib.QuantLibJNI;
import org.quantlib.QuoteHandle;
import org.quantlib.QuoteVector;
import org.quantlib.RateHelper;
import org.quantlib.RateHelperVector;
import org.quantlib.QuoteHandleVector;
import org.quantlib.RelinkableYieldTermStructureHandle;
import org.quantlib.Schedule;
import org.quantlib.Settings;
import org.quantlib.SimpleQuote;
import org.quantlib.SwapRateHelper;
import org.quantlib.TARGET;
import org.quantlib.Thirty360;
import org.quantlib.TimeUnit;
import org.quantlib.USDLibor;
import org.quantlib.UnitedStates;
import org.quantlib.YieldTermStructure;
import org.quantlib.YieldTermStructureHandle;
import org.quantlib.ZeroCouponBond;

public class Bonds {
    public static void main(String[] args) throws Exception {

        // MARKET DATA
        Calendar cal = new TARGET();
        Date settlementDate = new Date(18, Month.September, 2008);
        // must be a business day
        settlementDate = cal.adjust(settlementDate);

        int fixingDays = 3;
        int settlementdays = 3;

        Date todayDate = cal.advance(settlementDate,
                                     -fixingDays, TimeUnit.Days);

        Settings.instance().setEvaluationDate(todayDate);

        System.out.println("Today: " + todayDate.weekday()
                           + ", " + todayDate);
        System.out.println("Settlement date: " + settlementDate.weekday()
                           + ", " + settlementDate);

        // Building of the bonds discounting yield curve

        // RATE HELPERS

        // RateHelpers are built from the above quotes together with
        // other instrument dependant infos. Quotes are passed in
        // relinkable handles which could be relinked to some other
        // data source later.

        // Common data

        // ZC rates for the short end

        QuoteHandle zc3mRate = new QuoteHandle(new SimpleQuote(0.0096));
        QuoteHandle zc6mRate = new QuoteHandle(new SimpleQuote(0.0145));
        QuoteHandle zc1yRate = new QuoteHandle(new SimpleQuote(0.0194));

        DayCounter zcBondsDayCounter = new Actual365Fixed();

        DepositRateHelper zc3m =
            new DepositRateHelper(zc3mRate, new Period(3, TimeUnit.Months),
                                  fixingDays, cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, zcBondsDayCounter);

        DepositRateHelper zc6m =
            new DepositRateHelper(zc6mRate, new Period(6, TimeUnit.Months),
                                  fixingDays, cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, zcBondsDayCounter);

        DepositRateHelper zc1y =
            new DepositRateHelper(zc1yRate, new Period(1, TimeUnit.Years),
                                  fixingDays, cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, zcBondsDayCounter);

        // setup bonds
        double redemption = 100.0;
        final int numberOfBonds = 5;

        Date issueDates[] = {
            new Date(15, Month.March, 2005),
            new Date(15, Month.June, 2005),
            new Date(30, Month.June, 2006),
            new Date(15, Month.November, 2002),
            new Date(15, Month.May, 1987),
        };

        Date maturities[] = {
            new Date(31, Month.August, 2010),
            new Date(31, Month.August, 2011),
            new Date(31, Month.August, 2013),
            new Date(15, Month.August, 2018),
            new Date(15, Month.May, 2038),
        };

        double couponRates[] = {
            0.02375,
            0.04625,
            0.03125,
            0.04000,
            0.04500
        };

        SimpleQuote marketQuotes[] = {
            new SimpleQuote(100.390625),
            new SimpleQuote(106.21875),
            new SimpleQuote(100.59375),
            new SimpleQuote(101.6875),
            new SimpleQuote(102.140625)
        };

        QuoteHandleVector quoteHandle = new QuoteHandleVector();
        for (int i=0; i<numberOfBonds; i++){
            quoteHandle.add(new QuoteHandle(marketQuotes[i]));
        }

        ArrayList<FixedRateBondHelper> bondHelpers =
            new ArrayList<FixedRateBondHelper>();
        for (int i=0; i<numberOfBonds;i++){
            Schedule schedule =
                new Schedule(issueDates[i],
                             maturities[i],
                             new Period(Frequency.Semiannual),
                             new UnitedStates(UnitedStates.Market.GovernmentBond),
                             BusinessDayConvention.Unadjusted,
                             BusinessDayConvention.Unadjusted,
                             DateGeneration.Rule.Backward,
                             false);
            DoubleVector couponsVector = new DoubleVector();
            couponsVector.add(couponRates[i]);

            DayCounter dayCountConvBond =
                new ActualActual(ActualActual.Convention.Bond);

            FixedRateBondHelper bondHelper =
                new FixedRateBondHelper(quoteHandle.get(i),
                                        settlementdays,
                                        100.0,
                                        schedule,
                                        couponsVector,
                                        dayCountConvBond,
                                        BusinessDayConvention.Unadjusted,
                                        redemption,
                                        issueDates[i]);
            bondHelpers.add(bondHelper);
        }

        // CURVE BUILDING

        // Any DayCounter would be fine
        // ActualActual::ISDA ensures that 30 years is 30.0
        DayCounter termStructureDayCounter =
            new ActualActual(ActualActual.Convention.ISDA);

        // A depo-bond curve
        RateHelperVector bondInstruments = new RateHelperVector();

        // Adding the ZC bonds to the curve for the short end
        bondInstruments.add(zc3m);
        bondInstruments.add(zc6m);
        bondInstruments.add(zc1y);

        // Adding the Fixed rate bonds to the curve for the long end
        for (int i=0; i<numberOfBonds;i++){
            bondInstruments.add(bondHelpers.get(i));
        }

        YieldTermStructure bondDiscountingTermStructure =
            new PiecewiseFlatForward(settlementDate,bondInstruments,
                                     termStructureDayCounter);

        // Building of the Libor forecasting curve

        // SimpleQuote stores a value which can be manually changed;
        // other Quote subclasses could read the value from a database
        // or some kind of data feed

        // deposits
        QuoteHandle d1wQuoteHandle = new QuoteHandle(new SimpleQuote(0.043375));
        QuoteHandle d1mQuoteHandle = new QuoteHandle(new SimpleQuote(0.031875));
        QuoteHandle d3mQuoteHandle = new QuoteHandle(new SimpleQuote(0.0320375));
        QuoteHandle d6mQuoteHandle = new QuoteHandle(new SimpleQuote(0.03385));
        QuoteHandle d9mQuoteHandle = new QuoteHandle(new SimpleQuote(0.0338125));
        QuoteHandle d1yQuoteHandle = new QuoteHandle(new SimpleQuote(0.0335125));
        //swaps
        QuoteHandle s2yQuoteHandle = new QuoteHandle(new SimpleQuote(0.0295));
        QuoteHandle s3yQuoteHandle = new QuoteHandle(new SimpleQuote(0.0323));
        QuoteHandle s5yQuoteHandle = new QuoteHandle(new SimpleQuote(0.0359));
        QuoteHandle s10yQuoteHandle = new QuoteHandle(new SimpleQuote(0.0412));
        QuoteHandle s15yQuoteHandle = new QuoteHandle(new SimpleQuote(0.0433));

        // RATE HELPERS

        // RateHelpers are built from the above quotes together with
        // other instrument dependant infos. Quotes are passed in
        // relinkable handles which could be relinked to some other
        // data source later

        // deposits
        DayCounter depositDayCounter = new Actual360();

        RateHelper d1w =
            new DepositRateHelper(d1wQuoteHandle,
                                  new Period(1, TimeUnit.Weeks),
                                  fixingDays,
                                  cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, depositDayCounter);
        RateHelper d1m =
            new DepositRateHelper(d1mQuoteHandle,
                                  new Period(1, TimeUnit.Months),
                                  fixingDays,
                                  cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, depositDayCounter);
        RateHelper d3m =
            new DepositRateHelper(d3mQuoteHandle,
                                  new Period(3, TimeUnit.Months),
                                  fixingDays,
                                  cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, depositDayCounter);
        RateHelper d6m =
            new DepositRateHelper(d6mQuoteHandle,
                                  new Period(6, TimeUnit.Months),
                                  fixingDays,
                                  cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, depositDayCounter);
        RateHelper d9m =
            new DepositRateHelper(d9mQuoteHandle,
                                  new Period(9, TimeUnit.Months),
                                  fixingDays,
                                  cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, depositDayCounter);
        RateHelper d1y =
            new DepositRateHelper(d1yQuoteHandle,
                                  new Period(1, TimeUnit.Years),
                                  fixingDays,
                                  cal,
                                  BusinessDayConvention.ModifiedFollowing,
                                  true, depositDayCounter);

        // setup swaps
        Frequency swFixedLegFrequency = Frequency.Annual;
        BusinessDayConvention swFixedLegConvention =
            BusinessDayConvention.Unadjusted;
        DayCounter swFixedLegDayCounter =
            new Thirty360(Thirty360.Convention.European);
        IborIndex swFloatingLegIndex = new Euribor6M();

        Period forwardStart  = new Period(1, TimeUnit.Days);
        QuoteHandle spread = new QuoteHandle();
        RateHelper s2y =
            new SwapRateHelper(s2yQuoteHandle,
                               new Period(2, TimeUnit.Years),
                               cal,
                               swFixedLegFrequency,
                               swFixedLegConvention,
                               swFixedLegDayCounter,
                               swFloatingLegIndex,
                               spread, forwardStart);
        RateHelper s3y =
            new SwapRateHelper(s3yQuoteHandle,
                               new Period(3, TimeUnit.Years),
                               cal,
                               swFixedLegFrequency,
                               swFixedLegConvention,
                               swFixedLegDayCounter,
                               swFloatingLegIndex,
                               spread, forwardStart);
        RateHelper s5y =
            new SwapRateHelper(s5yQuoteHandle,
                               new Period(5, TimeUnit.Years),
                               cal,
                               swFixedLegFrequency,
                               swFixedLegConvention,
                               swFixedLegDayCounter,
                               swFloatingLegIndex,
                               spread, forwardStart);
        RateHelper s10y =
            new SwapRateHelper(s10yQuoteHandle,
                               new Period(10, TimeUnit.Years),
                               cal,
                               swFixedLegFrequency,
                               swFixedLegConvention,
                               swFixedLegDayCounter,
                               swFloatingLegIndex,
                               spread, forwardStart);
        RateHelper s15y =
            new SwapRateHelper(s15yQuoteHandle,
                               new Period(15, TimeUnit.Years),
                               cal,
                               swFixedLegFrequency,
                               swFixedLegConvention,
                               swFixedLegDayCounter,
                               swFloatingLegIndex,
                               spread, forwardStart);

        // CURVE BUILDING

        // A depo-swap curve
        RateHelperVector depoSwapInstruments = new RateHelperVector();
        depoSwapInstruments.add(d1w);
        depoSwapInstruments.add(d1m);
        depoSwapInstruments.add(d3m);
        depoSwapInstruments.add(d6m);
        depoSwapInstruments.add(d9m);
        depoSwapInstruments.add(d1y);
        depoSwapInstruments.add(s2y);
        depoSwapInstruments.add(s3y);
        depoSwapInstruments.add(s5y);
        depoSwapInstruments.add(s10y);
        depoSwapInstruments.add(s15y);

        YieldTermStructure depoSwapTermStructure =
            new PiecewiseFlatForward(
                settlementDate, depoSwapInstruments,
                termStructureDayCounter);

        // Term structures that will be used for pricing
        // the one used for discounting cash flows
        RelinkableYieldTermStructureHandle discountingTermStructure = new RelinkableYieldTermStructureHandle();

        RelinkableYieldTermStructureHandle forecastingTermStructure = new RelinkableYieldTermStructureHandle();

        // BONDS TO BE PRICED

        // Common data

        double faceAmount = 100.0;

        // Price engine
        PricingEngine bondEngine =
            new DiscountingBondEngine(discountingTermStructure);

        // Zero coupon bond

        ZeroCouponBond zeroCouponBond =
            new ZeroCouponBond(
                settlementdays,
                new UnitedStates(UnitedStates.Market.GovernmentBond),
                faceAmount,
                new Date(15, Month.August, 2013),
                BusinessDayConvention.Following,
                116.92,
                new Date(15, Month.August, 2003));

        zeroCouponBond.setPricingEngine(bondEngine);

        // Fixed 4.5% US Treasury Note
        Schedule fixedRateBondSchedule =
            new Schedule(
                new Date(15, Month.May, 2007),
                new Date(15, Month.May, 2017),
                new Period(Frequency.Semiannual),
                new UnitedStates(UnitedStates.Market.GovernmentBond),
                BusinessDayConvention.Unadjusted,
                BusinessDayConvention.Unadjusted,
                DateGeneration.Rule.Backward,
                false);

        DoubleVector rateVector = new DoubleVector();
        rateVector.add(0.045);
        FixedRateBond fixedRateBond =
            new FixedRateBond(
                settlementdays,
                faceAmount,
                fixedRateBondSchedule,
                rateVector,
                new ActualActual(ActualActual.Convention.Bond),
                BusinessDayConvention.ModifiedFollowing,
                100.0,
                new Date(15, Month.May, 2007));

        fixedRateBond.setPricingEngine(bondEngine);

        RelinkableYieldTermStructureHandle liborTermStructure =
            new RelinkableYieldTermStructureHandle();

        IborIndex libor3m = new USDLibor(new Period(3, TimeUnit.Months),
                                         liborTermStructure);
        libor3m.addFixing(new Date(17, Month.July, 2008), 0.0278625);

        Schedule floatingBondSchedule =
            new Schedule(
                new Date(21, Month.October, 2005),
                new Date(21, Month.October, 2010),
                new Period(Frequency.Quarterly),
                new UnitedStates(UnitedStates.Market.NYSE),
                BusinessDayConvention.Unadjusted,
                BusinessDayConvention.Unadjusted,
                DateGeneration.Rule.Backward,
                true);

        DoubleVector gearings = new DoubleVector();
        gearings.add(1.0);

        DoubleVector spreads = new DoubleVector();
        spreads.add(0.001);

        DoubleVector caps = new DoubleVector();
        DoubleVector floors = new DoubleVector();

        FloatingRateBond floatingRateBond =
            new FloatingRateBond(
                settlementdays,
                faceAmount,
                floatingBondSchedule,
                libor3m,
                new Actual360(),
                BusinessDayConvention.ModifiedFollowing,
                2,
                gearings,
                spreads,
                caps,
                floors,
                true,
                100.0,
                new Date(21, Month.October, 2005));
        floatingRateBond.setPricingEngine(bondEngine);

        IborCouponPricer pricer = new BlackIborCouponPricer();
        OptionletVolatilityStructureHandle volatility =
            new OptionletVolatilityStructureHandle(
                new ConstantOptionletVolatility(
                    settlementdays,
                    cal,
                    BusinessDayConvention.ModifiedFollowing,
                    0.0,
                    new Actual365Fixed()));

        pricer.setCapletVolatility(volatility);
        QuantLib.setCouponPricer(floatingRateBond.cashflows(), pricer);

        // Yield curve bootstrapping
        discountingTermStructure.linkTo(bondDiscountingTermStructure);
        forecastingTermStructure.linkTo(depoSwapTermStructure);

        // We are using the depo & swap curve to estimate the future
        // Libor rates
        liborTermStructure.linkTo(depoSwapTermStructure);

        // output results to screen
        System.out.printf("\n%18s%10s%10s%10s\n",
                          "", "ZC", "Fixed", "Floating");

        String fmt = "%18s%10.2f%10.2f%10.2f\n";
        System.out.printf(fmt, "Net present value",
                          zeroCouponBond.NPV(),
                          fixedRateBond.NPV(),
                          floatingRateBond.NPV());
        System.out.printf(fmt, "Clean price",
                          zeroCouponBond.cleanPrice(),
                          fixedRateBond.cleanPrice(),
                          floatingRateBond.cleanPrice());
        System.out.printf(fmt, "Dirty price",
                          zeroCouponBond.dirtyPrice(),
                          fixedRateBond.dirtyPrice(),
                          floatingRateBond.dirtyPrice());
        System.out.printf("%18s%8.2f %%%8.2f %%%8.2f %%\n", "Yield",
                          100*zeroCouponBond.yield(new Actual360(),
                                                   Compounding.Compounded,
                                                   Frequency.Annual),
                          100*fixedRateBond.yield(new Actual360(),
                                                  Compounding.Compounded,
                                                  Frequency.Annual),
                          100*floatingRateBond.yield(new Actual360(),
                                                     Compounding.Compounded,
                                                     Frequency.Annual));

        System.out.println("\nSample indirect computations (for the floating rate bond): ");
        System.out.printf("Yield to Clean Price: %.2f\n",
                          floatingRateBond.cleanPrice(
                              floatingRateBond.yield(new Actual360(),
                                                     Compounding.Compounded,
                                                     Frequency.Annual),
                              new Actual360(), Compounding.Compounded,
                              Frequency.Annual, settlementDate));

        System.out.printf("Clean Price to Yield: %.2f %%\n",
                          100*floatingRateBond.yield(
                                floatingRateBond.cleanPrice(),
                                new Actual360(), Compounding.Compounded,
                                Frequency.Annual, settlementDate));

        System.out.println("Done");
    }
}