forked from lballabio/QuantLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsabrswaptionvolatilitycube.hpp
More file actions
1436 lines (1273 loc) · 66.1 KB
/
Copy pathsabrswaptionvolatilitycube.hpp
File metadata and controls
1436 lines (1273 loc) · 66.1 KB
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006, 2007 Giorgio Facchinetti
Copyright (C) 2014, 2015 Peter Caspers
Copyright (C) 2023 Ignacio Anguita
Copyright (C) 2026 Aaditya Panikath
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
<https://www.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 sabrswaptionvolatilitycube.hpp
\brief Swaption volatility cube, fit-early-interpolate-later approach
The provided types are
SabrSwaptionVolatilityCube using the classic Hagan 2002 Sabr formula
NoArbSabrSwaptionVolatilityCube using the No Arbitrage Sabr model (Doust)
*/
#ifndef quantlib_sabr_swaption_volatility_cube_hpp
#define quantlib_sabr_swaption_volatility_cube_hpp
#include <ql/math/interpolations/backwardflatlinearinterpolation.hpp>
#include <ql/math/interpolations/bilinearinterpolation.hpp>
#include <ql/math/interpolations/flatextrapolation2d.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/math/interpolations/sabrinterpolation.hpp>
#include <ql/math/matrix.hpp>
#include <ql/math/solvers1d/brent.hpp>
#include <ql/quote.hpp>
#include <ql/termstructures/volatility/sabrsmilesection.hpp>
#include <ql/termstructures/volatility/swaption/swaptionvolcube.hpp>
#include <string>
#include <tuple>
#include <utility>
#ifndef SWAPTIONVOLCUBE_VEGAWEIGHTED_TOL
#define SWAPTIONVOLCUBE_VEGAWEIGHTED_TOL 15.0e-4
#endif
#ifndef SWAPTIONVOLCUBE_TOL
#define SWAPTIONVOLCUBE_TOL 100.0e-4
#endif
namespace QuantLib {
class Interpolation2D;
class EndCriteria;
class OptimizationMethod;
//! Traits class for XABR model customization points
/*! This traits class provides default implementations for model
operations used by XabrSwaptionVolatilityCube. The defaults
assume a 4-parameter SABR-like model with the standard
SABRInterpolation constructor signature.
Custom models can specialize this template to override:
- \c nParams: number of model parameters (default: 4)
- \c createInterpolation: factory for smile interpolation
- \c extractGamma: extract gamma parameter (default: 0)
- \c createSmileSection: factory for smile sections
\note The primary template works for any model whose Interpolation
type accepts the same constructor signature as SABRInterpolation
(4 params, shift, volatilityType). Models with different
constructors (e.g., NoArbSabr, ZABR) should specialize this
traits class.
*/
template <class Model>
struct XabrModelTraits {
static constexpr Size nParams = 4;
template <class I1, class I2>
static ext::shared_ptr<typename Model::Interpolation> createInterpolation(
const I1& xBegin, const I1& xEnd, const I2& yBegin,
Time t, const Real& forward,
const std::vector<Real>& params,
const std::vector<bool>& paramIsFixed,
bool vegaWeighted,
const ext::shared_ptr<EndCriteria>& endCriteria,
const ext::shared_ptr<OptimizationMethod>& optMethod,
Real errorAccept, bool useMaxError, Size maxGuesses,
Real shift, VolatilityType volatilityType) {
return ext::make_shared<typename Model::Interpolation>(
xBegin, xEnd, yBegin, t, forward,
params[0], params[1], params[2], params[3],
paramIsFixed[0], paramIsFixed[1], paramIsFixed[2], paramIsFixed[3],
vegaWeighted, endCriteria, optMethod,
errorAccept, useMaxError, maxGuesses, shift, volatilityType);
}
static Real extractGamma(
const ext::shared_ptr<typename Model::Interpolation>& /* interp */) {
return 0.0;
}
static ext::shared_ptr<typename Model::SmileSection> createSmileSection(
Time optionTime, Real forward,
const std::vector<Real>& params,
Real shift, VolatilityType volatilityType) {
return ext::make_shared<typename Model::SmileSection>(
optionTime, forward, params, shift, volatilityType);
}
};
//! XABR Swaption Volatility Cube
/*! This class implements the XABR Swaption Volatility Cube
which is a generic for different SABR, ZABR and
different smile models that can be used to instantiate concrete cubes.
Model customization is handled through XabrModelTraits<Model>.
The Model type must define at minimum:
- \c Interpolation: the interpolation type
- \c SmileSection: the smile section type
\see XabrModelTraits for customization points
*/
template<class Model>
class XabrSwaptionVolatilityCube : public SwaptionVolatilityCube {
using Traits = XabrModelTraits<Model>;
class Cube { // NOLINT(cppcoreguidelines-special-member-functions)
public:
Cube() = default;
Cube(const std::vector<Date>& optionDates,
const std::vector<Period>& swapTenors,
const std::vector<Time>& optionTimes,
const std::vector<Time>& swapLengths,
Size nLayers,
bool extrapolation = true,
bool backwardFlat = false);
Cube& operator=(const Cube& o);
Cube(const Cube&);
virtual ~Cube() = default;
void setElement(Size IndexOfLayer,
Size IndexOfRow,
Size IndexOfColumn,
Real x);
void setPoints(const std::vector<Matrix>& x);
void setPoint(const Date& optionDate,
const Period& swapTenor,
Time optionTime,
Time swapLength,
const std::vector<Real>& point);
void setLayer(Size i,
const Matrix& x);
void expandLayers(Size i,
bool expandOptionTimes,
Size j,
bool expandSwapLengths);
const std::vector<Date>& optionDates() const {
return optionDates_;
}
const std::vector<Period>& swapTenors() const {
return swapTenors_;
}
const std::vector<Time>& optionTimes() const;
const std::vector<Time>& swapLengths() const;
const std::vector<Matrix>& points() const;
std::vector<Real> operator()(Time optionTime, Time swapLengths) const;
void updateInterpolators()const;
Matrix browse() const;
private:
std::vector<Time> optionTimes_, swapLengths_;
std::vector<Date> optionDates_;
std::vector<Period> swapTenors_;
Size nLayers_;
std::vector<Matrix> points_;
mutable std::vector<Matrix> transposedPoints_;
bool extrapolation_;
bool backwardFlat_;
mutable std::vector< ext::shared_ptr<Interpolation2D> > interpolators_;
};
public:
using SwaptionVolatilityStructure::smileSection;
XabrSwaptionVolatilityCube(
const Handle<SwaptionVolatilityStructure>& atmVolStructure,
const std::vector<Period>& optionTenors,
const std::vector<Period>& swapTenors,
const std::vector<Spread>& strikeSpreads,
const std::vector<std::vector<Handle<Quote> > >& volSpreads,
const ext::shared_ptr<SwapIndex>& swapIndexBase,
const ext::shared_ptr<SwapIndex>& shortSwapIndexBase,
bool vegaWeightedSmileFit,
std::vector<std::vector<Handle<Quote> > > parametersGuess,
std::vector<bool> isParameterFixed,
bool isAtmCalibrated,
ext::shared_ptr<EndCriteria> endCriteria = ext::shared_ptr<EndCriteria>(),
Real maxErrorTolerance = Null<Real>(),
ext::shared_ptr<OptimizationMethod> optMethod = ext::shared_ptr<OptimizationMethod>(),
Real errorAccept = Null<Real>(),
bool useMaxError = false,
Size maxGuesses = 50,
bool backwardFlat = false,
Real cutoffStrike = 0.0001,
bool singlePassCalibration = false);
//! \name LazyObject interface
//@{
void performCalculations() const override;
//@}
//! \name SwaptionVolatilityCube interface
//@{
ext::shared_ptr<SmileSection> smileSectionImpl(Time optionTime,
Time swapLength) const override;
//@}
//! \name Other inspectors
//@{
const Matrix& marketVolCube(Size i) const {
return marketVolCube_.points()[i];
}
Matrix sparseSabrParameters()const;
Matrix denseSabrParameters() const;
Matrix marketVolCube() const;
Matrix volCubeAtmCalibrated() const;
//@}
void sabrCalibrationSection(const Cube& marketVolCube,
Cube& parametersCube,
const Period& swapTenor) const;
void recalibration(Real beta,
const Period& swapTenor);
void recalibration(const std::vector<Real> &beta,
const Period& swapTenor);
void recalibration(const std::vector<Period> &swapLengths,
const std::vector<Real> &beta,
const Period& swapTenor);
void updateAfterRecalibration();
protected:
void registerWithParametersGuess();
void setParameterGuess() const;
ext::shared_ptr<SmileSection> smileSection(
Time optionTime,
Time swapLength,
const Cube& sabrParametersCube) const;
Cube sabrCalibration(const Cube &marketVolCube) const;
Real calibratedAtmAlpha(Time optionTime,
Rate forward,
Volatility atmVol,
std::vector<Real> parameters,
Real shift) const;
std::pair<Real, Real> smileErrors(
Time optionTime,
Rate forward,
const std::vector<Real>& parameters,
Real shift,
const std::vector<Real>& strikes,
const std::vector<Real>& volatilities,
const std::vector<Real>& weights) const;
void fillVolatilityCube(bool marketSpreads = false) const;
void createSparseSmiles() const;
std::vector<Real> spreadVolInterpolation(
const Date& atmOptionDate,
const Period& atmSwapTenor,
bool marketSpreads) const;
private:
Size requiredNumberOfStrikes() const override { return 1; }
mutable Cube marketVolCube_;
mutable Cube volCubeAtmCalibrated_;
mutable Cube sparseParameters_;
mutable Cube denseParameters_;
mutable std::vector< std::vector<ext::shared_ptr<SmileSection> > >
sparseSmiles_;
std::vector<std::vector<Handle<Quote> > > parametersGuessQuotes_;
mutable Cube parametersGuess_;
std::vector<bool> isParameterFixed_;
bool isAtmCalibrated_;
bool singlePassCalibration_;
const ext::shared_ptr<EndCriteria> endCriteria_;
Real maxErrorTolerance_;
const ext::shared_ptr<OptimizationMethod> optMethod_;
Real errorAccept_;
const bool useMaxError_;
const Size maxGuesses_;
const bool backwardFlat_;
const Real cutoffStrike_;
VolatilityType volatilityType_;
class PrivateObserver : public Observer {
public:
explicit PrivateObserver(XabrSwaptionVolatilityCube<Model> *v)
: v_(v) {}
void update() override {
v_->setParameterGuess();
v_->update();
}
private:
XabrSwaptionVolatilityCube<Model> *v_;
};
ext::shared_ptr<PrivateObserver> privateObserver_;
};
//=======================================================================//
// XabrSwaptionVolatilityCube //
//=======================================================================//
template <class Model>
XabrSwaptionVolatilityCube<Model>::XabrSwaptionVolatilityCube(
const Handle<SwaptionVolatilityStructure>& atmVolStructure,
const std::vector<Period>& optionTenors,
const std::vector<Period>& swapTenors,
const std::vector<Spread>& strikeSpreads,
const std::vector<std::vector<Handle<Quote> > >& volSpreads,
const ext::shared_ptr<SwapIndex>& swapIndexBase,
const ext::shared_ptr<SwapIndex>& shortSwapIndexBase,
bool vegaWeightedSmileFit,
std::vector<std::vector<Handle<Quote> > > parametersGuess,
std::vector<bool> isParameterFixed,
bool isAtmCalibrated,
ext::shared_ptr<EndCriteria> endCriteria,
Real maxErrorTolerance,
ext::shared_ptr<OptimizationMethod> optMethod,
const Real errorAccept,
const bool useMaxError,
const Size maxGuesses,
const bool backwardFlat,
const Real cutoffStrike,
const bool singlePassCalibration)
: SwaptionVolatilityCube(atmVolStructure,
optionTenors,
swapTenors,
strikeSpreads,
volSpreads,
swapIndexBase,
shortSwapIndexBase,
vegaWeightedSmileFit),
parametersGuessQuotes_(std::move(parametersGuess)),
isParameterFixed_(std::move(isParameterFixed)), isAtmCalibrated_(isAtmCalibrated),
singlePassCalibration_(singlePassCalibration),
endCriteria_(std::move(endCriteria)), optMethod_(std::move(optMethod)),
useMaxError_(useMaxError), maxGuesses_(maxGuesses), backwardFlat_(backwardFlat),
cutoffStrike_(cutoffStrike), volatilityType_(atmVolStructure->volatilityType()) {
if (maxErrorTolerance != Null<Rate>()) {
maxErrorTolerance_ = maxErrorTolerance;
} else{
maxErrorTolerance_ = SWAPTIONVOLCUBE_TOL;
if (vegaWeightedSmileFit_) maxErrorTolerance_ = SWAPTIONVOLCUBE_VEGAWEIGHTED_TOL;
}
if (errorAccept != Null<Rate>()) {
errorAccept_ = errorAccept;
} else{
errorAccept_ = maxErrorTolerance_ / 5.0;
}
privateObserver_ = ext::make_shared<PrivateObserver>(this);
registerWithParametersGuess();
setParameterGuess();
}
template<class Model> void XabrSwaptionVolatilityCube<Model>::registerWithParametersGuess()
{
for (Size i=0; i<Traits::nParams; i++)
for (Size j=0; j<nOptionTenors_; j++)
for (Size k=0; k<nSwapTenors_; k++)
privateObserver_->registerWith(parametersGuessQuotes_[j*nSwapTenors_+k][i]);
}
template<class Model> void XabrSwaptionVolatilityCube<Model>::setParameterGuess() const {
//! set parametersGuess_ by parametersGuessQuotes_
parametersGuess_ = Cube(optionDates_, swapTenors_,
optionTimes_, swapLengths_, Traits::nParams,
true, backwardFlat_);
Size i;
for (i=0; i<Traits::nParams; i++)
for (Size j=0; j<nOptionTenors_ ; j++)
for (Size k=0; k<nSwapTenors_; k++) {
parametersGuess_.setElement(i, j, k,
parametersGuessQuotes_[j*nSwapTenors_+k][i]->value());
}
parametersGuess_.updateInterpolators();
}
template<class Model> void XabrSwaptionVolatilityCube<Model>::performCalculations() const {
SwaptionVolatilityCube::performCalculations();
//! set marketVolCube_ by volSpreads_ quotes
marketVolCube_ = Cube(optionDates_, swapTenors_,
optionTimes_, swapLengths_, nStrikes_);
Rate atmForward;
Volatility atmVol, vol;
for (Size j=0; j<nOptionTenors_; ++j) {
for (Size k=0; k<nSwapTenors_; ++k) {
atmForward = atmStrike(optionDates_[j], swapTenors_[k]);
atmVol = atmVol_->volatility(optionDates_[j], swapTenors_[k],
atmForward);
for (Size i=0; i<nStrikes_; ++i) {
vol = atmVol + volSpreads_[j*nSwapTenors_+k][i]->value();
marketVolCube_.setElement(i, j, k, vol);
}
}
}
marketVolCube_.updateInterpolators();
volCubeAtmCalibrated_= marketVolCube_;
if (singlePassCalibration_) {
fillVolatilityCube(true);
denseParameters_ = sabrCalibration(volCubeAtmCalibrated_);
denseParameters_.updateInterpolators();
sparseParameters_ = denseParameters_;
} else {
sparseParameters_ = sabrCalibration(marketVolCube_);
sparseParameters_.updateInterpolators();
if (isAtmCalibrated_) {
fillVolatilityCube();
denseParameters_ = sabrCalibration(volCubeAtmCalibrated_);
denseParameters_.updateInterpolators();
}
}
}
template<class Model> void XabrSwaptionVolatilityCube<Model>::updateAfterRecalibration() {
volCubeAtmCalibrated_ = marketVolCube_;
if (singlePassCalibration_) {
fillVolatilityCube(true);
denseParameters_ = sabrCalibration(volCubeAtmCalibrated_);
denseParameters_.updateInterpolators();
sparseParameters_ = denseParameters_;
} else if (isAtmCalibrated_) {
fillVolatilityCube();
denseParameters_ = sabrCalibration(volCubeAtmCalibrated_);
denseParameters_.updateInterpolators();
}
notifyObservers();
}
template <class Model>
Real XabrSwaptionVolatilityCube<Model>::calibratedAtmAlpha(
Time optionTime,
Rate forward,
Volatility atmVol,
std::vector<Real> parameters,
Real shift) const {
const auto atmError = [&](Real alpha) {
parameters[0] = alpha;
return Traits::createSmileSection(optionTime, forward, parameters,
shift, volatilityType_)
->volatility(forward) -
atmVol;
};
Brent solver;
solver.setLowerBound(QL_EPSILON);
const Real guess = parameters[0];
const Real step = std::max(0.1 * guess, 1.0e-6);
return solver.solve(atmError, 1.0e-12, guess, step);
}
template <class Model>
std::pair<Real, Real> XabrSwaptionVolatilityCube<Model>::smileErrors(
Time optionTime,
Rate forward,
const std::vector<Real>& parameters,
Real shift,
const std::vector<Real>& strikes,
const std::vector<Real>& volatilities,
const std::vector<Real>& weights) const {
const auto smile = Traits::createSmileSection(
optionTime, forward, parameters, shift, volatilityType_);
Real squaredError = 0.0;
Real maxError = QL_MIN_REAL;
for (Size i = 0; i < strikes.size(); ++i) {
const Real error = smile->volatility(strikes[i]) - volatilities[i];
squaredError += error * error * weights[i];
maxError = std::max(maxError, std::fabs(error));
}
const Size n = strikes.size();
return { std::sqrt(n * squaredError / (n == 1 ? 1 : n - 1)), maxError };
}
template <class Model>
typename XabrSwaptionVolatilityCube<Model>::Cube
XabrSwaptionVolatilityCube<Model>::sabrCalibration(const Cube &marketVolCube) const {
const std::vector<Time>& optionTimes = marketVolCube.optionTimes();
const std::vector<Time>& swapLengths = marketVolCube.swapLengths();
const std::vector<Date>& optionDates = marketVolCube.optionDates();
const std::vector<Period>& swapTenors = marketVolCube.swapTenors();
Matrix alphas(optionTimes.size(), swapLengths.size(),0.);
Matrix betas(alphas);
Matrix nus(alphas);
Matrix rhos(alphas);
Matrix gammas(alphas); // Zero-initialized; populated and used only for 5+ param models (ZABR).
Matrix forwards(alphas);
Matrix errors(alphas);
Matrix maxErrors(alphas);
Matrix endCriteria(alphas);
const std::vector<Matrix>& tmpMarketVolCube = marketVolCube.points();
std::vector<Real> strikes(strikeSpreads_.size());
std::vector<Real> volatilities(strikeSpreads_.size());
for (Size j=0; j<optionTimes.size(); j++) {
for (Size k=0; k<swapLengths.size(); k++) {
Rate atmForward = atmStrike(optionDates[j], swapTenors[k]);
Real shiftTmp = atmVol_->shift(optionTimes[j], swapLengths[k]);
strikes.clear();
volatilities.clear();
for (Size i=0; i<nStrikes_; i++){
Real strike = atmForward+strikeSpreads_[i];
if(strike + shiftTmp >=cutoffStrike_) {
strikes.push_back(strike);
volatilities.push_back(tmpMarketVolCube[i][j][k]);
}
}
const std::vector<Real>& guess =
parametersGuess_(optionTimes[j], swapLengths[k]);
const ext::shared_ptr<typename Model::Interpolation> sabrInterpolation =
Traits::createInterpolation(strikes.begin(), strikes.end(),
volatilities.begin(),
optionTimes[j], atmForward,
guess,
isParameterFixed_,
vegaWeightedSmileFit_,
endCriteria_,
optMethod_,
errorAccept_,
useMaxError_,
maxGuesses_,
shiftTmp,
volatilityType_);
sabrInterpolation->update();
Real rmsError = sabrInterpolation->rmsError();
Real maxError = sabrInterpolation->maxError();
const Real calibrationRmsError = rmsError;
const Real calibrationMaxError = maxError;
alphas [j][k] = sabrInterpolation->alpha();
betas [j][k] = sabrInterpolation->beta();
nus [j][k] = sabrInterpolation->nu();
rhos [j][k] = sabrInterpolation->rho();
if constexpr (Traits::nParams >= 5)
gammas[j][k] = Traits::extractGamma(sabrInterpolation);
if (singlePassCalibration_ && isAtmCalibrated_) {
std::vector<Real> parameters = { alphas[j][k], betas[j][k],
nus[j][k], rhos[j][k] };
if constexpr (Traits::nParams >= 5)
parameters.push_back(gammas[j][k]);
const Volatility atmVol = atmVol_->volatility(
optionDates[j], swapTenors[k], atmForward, true);
alphas[j][k] = calibratedAtmAlpha(
optionTimes[j], atmForward, atmVol, parameters, shiftTmp);
parameters[0] = alphas[j][k];
std::tie(rmsError, maxError) = smileErrors(
optionTimes[j], atmForward, parameters, shiftTmp, strikes,
volatilities, sabrInterpolation->interpolationWeights());
}
forwards [j][k] = atmForward;
errors [j][k] = rmsError;
maxErrors [j][k] = maxError;
endCriteria[j][k] = sabrInterpolation->endCriteria();
// Build gamma diagnostic string only for models that have gamma (ZABR).
// if constexpr guarantees dead-branch elimination for 4-param models.
std::string gammaInfo;
if constexpr (Traits::nParams >= 5)
gammaInfo = "\n gamma = " + std::to_string(gammas[j][k]);
QL_ENSURE(endCriteria[j][k] != Integer(EndCriteria::MaxIterations),
"global swaptions calibration failed: "
"MaxIterations reached: " << "\n" <<
"option maturity = " << optionDates[j] << ", \n" <<
"swap tenor = " << swapTenors[k] << ", \n" <<
"rms error = " << io::rate(calibrationRmsError) << ", \n" <<
"max error = " << io::rate(calibrationMaxError) << ", \n" <<
" alpha = " << alphas[j][k] << "\n" <<
" beta = " << betas[j][k] << "\n" <<
" nu = " << nus[j][k] << "\n" <<
" rho = " << rhos[j][k] << gammaInfo << "\n"
);
QL_ENSURE((useMaxError_ ? calibrationMaxError : calibrationRmsError) <
maxErrorTolerance_,
"global swaptions calibration failed: "
"error tolerance exceeded: "
<< "\n"
<< "using " << (useMaxError_ ? "maxError" : "rmsError")
<< " tolerance " << maxErrorTolerance_ << ", \n"
<< "option maturity = " << optionDates[j] << ", \n"
<< "swap tenor = " << swapTenors[k] << ", \n"
<< "rms error = " << io::rate(calibrationRmsError) << ", \n"
<< "max error = " << io::rate(calibrationMaxError) << ", \n"
<< " alpha = " << alphas[j][k] << "\n"
<< " beta = " << betas[j][k] << "\n"
<< " nu = " << nus[j][k] << "\n"
<< " rho = " << rhos[j][k] << gammaInfo << "\n");
}
}
// Cube has Traits::nParams parameter layers + 4 metadata layers
// (forwards, errors, maxErrors, endCriteria)
Cube sabrParametersCube(optionDates, swapTenors,
optionTimes, swapLengths, Traits::nParams + 4,
true, backwardFlat_);
sabrParametersCube.setLayer(0, alphas);
sabrParametersCube.setLayer(1, betas);
sabrParametersCube.setLayer(2, nus);
sabrParametersCube.setLayer(3, rhos);
// For models with 5+ params (e.g., ZABR), store gamma in layer 4
if constexpr (Traits::nParams >= 5)
sabrParametersCube.setLayer(4, gammas);
// Metadata layers start at Traits::nParams
sabrParametersCube.setLayer(Traits::nParams, forwards);
sabrParametersCube.setLayer(Traits::nParams + 1, errors);
sabrParametersCube.setLayer(Traits::nParams + 2, maxErrors);
sabrParametersCube.setLayer(Traits::nParams + 3, endCriteria);
return sabrParametersCube;
}
template<class Model> void XabrSwaptionVolatilityCube<Model>::sabrCalibrationSection(
const Cube& marketVolCube,
Cube& parametersCube,
const Period& swapTenor) const {
const std::vector<Time>& optionTimes = marketVolCube.optionTimes();
const std::vector<Time>& swapLengths = marketVolCube.swapLengths();
const std::vector<Date>& optionDates = marketVolCube.optionDates();
const std::vector<Period>& swapTenors = marketVolCube.swapTenors();
Size k = std::find(swapTenors.begin(), swapTenors.end(),
swapTenor) - swapTenors.begin();
QL_REQUIRE(k != swapTenors.size(), "swap tenor not found");
std::vector<Real> calibrationResult(Traits::nParams + 4, 0.);
const std::vector<Matrix>& tmpMarketVolCube = marketVolCube.points();
std::vector<Real> strikes(strikeSpreads_.size());
std::vector<Real> volatilities(strikeSpreads_.size());
for (Size j=0; j<optionTimes.size(); j++) {
Rate atmForward = atmStrike(optionDates[j], swapTenors[k]);
Real shiftTmp = atmVol_->shift(optionTimes[j], swapLengths[k]);
strikes.clear();
volatilities.clear();
for (Size i=0; i<nStrikes_; i++){
Real strike = atmForward+strikeSpreads_[i];
if(strike+shiftTmp>=cutoffStrike_) {
strikes.push_back(strike);
volatilities.push_back(tmpMarketVolCube[i][j][k]);
}
}
const std::vector<Real>& guess =
parametersGuess_(optionTimes[j], swapLengths[k]);
const ext::shared_ptr<typename Model::Interpolation> sabrInterpolation =
Traits::createInterpolation(strikes.begin(), strikes.end(),
volatilities.begin(),
optionTimes[j], atmForward,
guess,
isParameterFixed_,
vegaWeightedSmileFit_,
endCriteria_,
optMethod_,
errorAccept_,
useMaxError_,
maxGuesses_,
shiftTmp,
volatilityType_);
sabrInterpolation->update();
Real interpolationError = sabrInterpolation->rmsError();
Real maxError = sabrInterpolation->maxError();
const Real calibrationError = interpolationError;
const Real calibrationMaxError = maxError;
calibrationResult[0]=sabrInterpolation->alpha();
calibrationResult[1]=sabrInterpolation->beta();
calibrationResult[2]=sabrInterpolation->nu();
calibrationResult[3]=sabrInterpolation->rho();
if constexpr (Traits::nParams >= 5)
calibrationResult[4] = Traits::extractGamma(sabrInterpolation);
if (singlePassCalibration_ && isAtmCalibrated_) {
std::vector<Real> parameters(
calibrationResult.begin(),
calibrationResult.begin() + Traits::nParams);
const Volatility atmVol = atmVol_->volatility(
optionDates[j], swapTenors[k], atmForward, true);
calibrationResult[0] = calibratedAtmAlpha(
optionTimes[j], atmForward, atmVol, parameters, shiftTmp);
parameters[0] = calibrationResult[0];
std::tie(interpolationError, maxError) = smileErrors(
optionTimes[j], atmForward, parameters, shiftTmp, strikes,
volatilities, sabrInterpolation->interpolationWeights());
}
// Metadata stored after model parameters
calibrationResult[Traits::nParams]=atmForward;
calibrationResult[Traits::nParams + 1]=interpolationError;
calibrationResult[Traits::nParams + 2]=maxError;
calibrationResult[Traits::nParams + 3]=sabrInterpolation->endCriteria();
// Build gamma diagnostic string only for models that have gamma (ZABR).
// if constexpr guarantees dead-branch elimination for 4-param models.
std::string gammaInfo;
if constexpr (Traits::nParams >= 5)
gammaInfo = ", gamma " + std::to_string(calibrationResult[4]);
QL_ENSURE(calibrationResult[Traits::nParams + 3] != Integer(EndCriteria::MaxIterations),
"section calibration failed: "
"option tenor " << optionDates[j] <<
", swap tenor " << swapTenors[k] <<
": max iteration (" <<
endCriteria_->maxIterations() << ")" <<
", alpha " << calibrationResult[0] <<
", beta " << calibrationResult[1] <<
", nu " << calibrationResult[2] <<
", rho " << calibrationResult[3] <<
gammaInfo <<
", max error " << calibrationMaxError <<
", error " << calibrationError
);
QL_ENSURE((useMaxError_ ? calibrationMaxError : calibrationError) <
maxErrorTolerance_,
"section calibration failed: "
"option tenor " << optionDates[j] <<
", swap tenor " << swapTenors[k] <<
(useMaxError_ ? ": max error " : ": error ") <<
(useMaxError_ ? calibrationMaxError : calibrationError) <<
", alpha " << calibrationResult[0] <<
", beta " << calibrationResult[1] <<
", nu " << calibrationResult[2] <<
", rho " << calibrationResult[3] <<
gammaInfo <<
(useMaxError_ ? ", error " : ", max error ") <<
(useMaxError_ ? calibrationError : calibrationMaxError)
);
parametersCube.setPoint(optionDates[j], swapTenors[k],
optionTimes[j], swapLengths[k],
calibrationResult);
parametersCube.updateInterpolators();
}
}
template<class Model>
void XabrSwaptionVolatilityCube<Model>::fillVolatilityCube(bool marketSpreads) const {
const ext::shared_ptr<SwaptionVolatilityDiscrete> atmVolStructure =
ext::dynamic_pointer_cast<SwaptionVolatilityDiscrete>(*atmVol_);
std::vector<Time> atmOptionTimes(atmVolStructure->optionTimes());
std::vector<Time> optionTimes(volCubeAtmCalibrated_.optionTimes());
atmOptionTimes.insert(atmOptionTimes.end(),
optionTimes.begin(), optionTimes.end());
std::sort(atmOptionTimes.begin(),atmOptionTimes.end());
auto new_end = std::unique(atmOptionTimes.begin(), atmOptionTimes.end());
atmOptionTimes.erase(new_end, atmOptionTimes.end());
std::vector<Time> atmSwapLengths(atmVolStructure->swapLengths());
std::vector<Time> swapLengths(volCubeAtmCalibrated_.swapLengths());
atmSwapLengths.insert(atmSwapLengths.end(),
swapLengths.begin(), swapLengths.end());
std::sort(atmSwapLengths.begin(),atmSwapLengths.end());
new_end = std::unique(atmSwapLengths.begin(), atmSwapLengths.end());
atmSwapLengths.erase(new_end, atmSwapLengths.end());
std::vector<Date> atmOptionDates = atmVolStructure->optionDates();
std::vector<Date> optionDates(volCubeAtmCalibrated_.optionDates());
atmOptionDates.insert(atmOptionDates.end(),
optionDates.begin(), optionDates.end());
std::sort(atmOptionDates.begin(),atmOptionDates.end());
auto new_end_1 = std::unique(atmOptionDates.begin(), atmOptionDates.end());
atmOptionDates.erase(new_end_1, atmOptionDates.end());
std::vector<Period> atmSwapTenors = atmVolStructure->swapTenors();
std::vector<Period> swapTenors(volCubeAtmCalibrated_.swapTenors());
atmSwapTenors.insert(atmSwapTenors.end(),
swapTenors.begin(), swapTenors.end());
std::sort(atmSwapTenors.begin(),atmSwapTenors.end());
auto new_end_2 = std::unique(atmSwapTenors.begin(), atmSwapTenors.end());
atmSwapTenors.erase(new_end_2, atmSwapTenors.end());
if (!marketSpreads)
createSparseSmiles();
for (Size j=0; j<atmOptionTimes.size(); j++) {
for (Size k=0; k<atmSwapLengths.size(); k++) {
bool expandOptionTimes =
!(std::binary_search(optionTimes.begin(),
optionTimes.end(),
atmOptionTimes[j]));
bool expandSwapLengths =
!(std::binary_search(swapLengths.begin(),
swapLengths.end(),
atmSwapLengths[k]));
if(expandOptionTimes || expandSwapLengths){
Rate atmForward = atmStrike(atmOptionDates[j],
atmSwapTenors[k]);
Volatility atmVol = atmVol_->volatility(
atmOptionDates[j], atmSwapTenors[k], atmForward);
std::vector<Real> spreadVols = spreadVolInterpolation(
atmOptionDates[j], atmSwapTenors[k], marketSpreads);
std::vector<Real> volAtmCalibrated;
volAtmCalibrated.reserve(nStrikes_);
for (Size i=0; i<nStrikes_; i++)
volAtmCalibrated.push_back(atmVol + spreadVols[i]);
volCubeAtmCalibrated_.setPoint(
atmOptionDates[j], atmSwapTenors[k],
atmOptionTimes[j], atmSwapLengths[k],
volAtmCalibrated);
}
}
}
volCubeAtmCalibrated_.updateInterpolators();
}
template<class Model> void XabrSwaptionVolatilityCube<Model>::createSparseSmiles() const {
std::vector<Time> optionTimes(sparseParameters_.optionTimes());
std::vector<Time> swapLengths(sparseParameters_.swapLengths());
sparseSmiles_.clear();
for (Real& optionTime : optionTimes) {
std::vector<ext::shared_ptr<SmileSection> > tmp;
Size n = swapLengths.size();
tmp.reserve(n);
for (Size k=0; k<n; ++k) {
tmp.push_back(smileSection(optionTime, swapLengths[k], sparseParameters_));
}
sparseSmiles_.push_back(tmp);
}
}
template<class Model>
std::vector<Real> XabrSwaptionVolatilityCube<Model>::spreadVolInterpolation(
const Date& atmOptionDate,
const Period& atmSwapTenor,
bool marketSpreads) const {
Time atmOptionTime = timeFromReference(atmOptionDate);
Time atmTimeLength = swapLength(atmSwapTenor);
std::vector<Real> result;
const Cube& sourceCube = marketSpreads ? marketVolCube_ : sparseParameters_;
const std::vector<Time>& optionTimes(sourceCube.optionTimes());
const std::vector<Time>& swapLengths(sourceCube.swapLengths());
const std::vector<Date>& optionDates =
sourceCube.optionDates();
const std::vector<Period>& swapTenors = sourceCube.swapTenors();
std::vector<Real>::const_iterator optionTimesPreviousNode,
swapLengthsPreviousNode;
optionTimesPreviousNode = std::lower_bound(optionTimes.begin(),
optionTimes.end(),
atmOptionTime);
Size optionTimesPreviousIndex =
optionTimesPreviousNode - optionTimes.begin();
if (optionTimesPreviousIndex >0)
optionTimesPreviousIndex --;
swapLengthsPreviousNode = std::lower_bound(swapLengths.begin(),
swapLengths.end(),
atmTimeLength);
Size swapLengthsPreviousIndex = swapLengthsPreviousNode - swapLengths.begin();
if (swapLengthsPreviousIndex >0)
swapLengthsPreviousIndex --;
std::vector< std::vector<ext::shared_ptr<SmileSection> > > smiles;
if (marketSpreads) {
QL_REQUIRE(optionTimesPreviousIndex+1 < optionTimes.size(),
"cannot interpolate market spreads at option time " <<
atmOptionTime);
QL_REQUIRE(swapLengthsPreviousIndex+1 < swapLengths.size(),
"cannot interpolate market spreads at swap length " <<
atmTimeLength);
} else {
std::vector<ext::shared_ptr<SmileSection> > smilesOnPreviousExpiry;
std::vector<ext::shared_ptr<SmileSection> > smilesOnNextExpiry;
QL_REQUIRE(optionTimesPreviousIndex+1 < sparseSmiles_.size(),
"optionTimesPreviousIndex+1 >= sparseSmiles_.size()");
QL_REQUIRE(swapLengthsPreviousIndex+1 < sparseSmiles_[0].size(),
"swapLengthsPreviousIndex+1 >= sparseSmiles_[0].size()");
smilesOnPreviousExpiry.push_back(
sparseSmiles_[optionTimesPreviousIndex][swapLengthsPreviousIndex]);
smilesOnPreviousExpiry.push_back(
sparseSmiles_[optionTimesPreviousIndex][swapLengthsPreviousIndex+1]);
smilesOnNextExpiry.push_back(
sparseSmiles_[optionTimesPreviousIndex+1][swapLengthsPreviousIndex]);
smilesOnNextExpiry.push_back(
sparseSmiles_[optionTimesPreviousIndex+1][swapLengthsPreviousIndex+1]);
smiles.push_back(smilesOnPreviousExpiry);
smiles.push_back(smilesOnNextExpiry);
}
std::vector<Real> optionsNodes(2);
optionsNodes[0] = optionTimes[optionTimesPreviousIndex];
optionsNodes[1] = optionTimes[optionTimesPreviousIndex+1];
std::vector<Date> optionsDateNodes(2);
optionsDateNodes[0] = optionDates[optionTimesPreviousIndex];
optionsDateNodes[1] = optionDates[optionTimesPreviousIndex+1];
std::vector<Real> swapLengthsNodes(2);
swapLengthsNodes[0] = swapLengths[swapLengthsPreviousIndex];
swapLengthsNodes[1] = swapLengths[swapLengthsPreviousIndex+1];
std::vector<Period> swapTenorNodes(2);
swapTenorNodes[0] = swapTenors[swapLengthsPreviousIndex];
swapTenorNodes[1] = swapTenors[swapLengthsPreviousIndex+1];
Rate atmForward = atmStrike(atmOptionDate, atmSwapTenor);
Real shift = atmVol_->shift(atmOptionTime, atmTimeLength);
Matrix atmForwards(2, 2, 0.0);
Matrix atmShifts(2,2,0.0);
Matrix atmVols(2, 2, 0.0);
for (Size i=0; i<2; i++) {
for (Size j=0; j<2; j++) {
atmForwards[i][j] = atmStrike(optionsDateNodes[i],
swapTenorNodes[j]);
atmShifts[i][j] = atmVol_->shift(optionsNodes[i], swapLengthsNodes[j]);
if (!marketSpreads) {
// atmVols[i][j] = smiles[i][j]->volatility(atmForwards[i][j]);
atmVols[i][j] = atmVol_->volatility(
optionsDateNodes[i], swapTenorNodes[j], atmForwards[i][j]);
/* With the old implementation the interpolated spreads on ATM
volatilities were null even if the spreads on ATM volatilities to be
interpolated were non-zero. The new implementation removes
this behaviour, but introduces a small ERROR in the cube:
even if no spreads are applied on any cube ATM volatility corresponding
to quoted smile sections (that is ATM volatilities in sparse cube), the
cube ATM volatilities corresponding to not quoted smile sections (that
is ATM volatilities in dense cube) are no more exactly the quoted values,
but that ones PLUS the linear interpolation of the fit errors on the ATM
volatilities in sparse cube whose spreads are used in the calculation.
A similar imprecision is introduced to the volatilities in dense cube
whith moneyness near to 1.
(See below how spreadVols are calculated).
The extent of this error depends on the quality of the fit: in case of
good fits it is negligibile.
*/
}
}
}
for (Size k=0; k<nStrikes_; k++){
const Real strike = std::max(atmForward + strikeSpreads_[k],cutoffStrike_-shift);
const Real moneyness = (atmForward+shift)/(strike+shift);
Matrix strikes(2,2,0.);
Matrix spreadVols(2,2,0.);
for (Size i=0; i<2; i++){
for (Size j=0; j<2; j++){
if (volatilityType_ == VolatilityType::Normal)
strikes[i][j] = atmForwards[i][j] + strike - atmForward;
else
strikes[i][j] =
(atmForwards[i][j]+atmShifts[i][j])/moneyness - atmShifts[i][j];
if (marketSpreads) {
const Size section =
(optionTimesPreviousIndex+i)*nSwapTenors_ +
swapLengthsPreviousIndex+j;
if (nStrikes_ == 1) {
spreadVols[i][j] = volSpreads_[section][0]->value();
} else {
std::vector<Real> quotedSpreads(nStrikes_);
for (Size n = 0; n < nStrikes_; ++n)
quotedSpreads[n] = volSpreads_[section][n]->value();
LinearInterpolation strikeInterpolation(
strikeSpreads_.begin(), strikeSpreads_.end(),
quotedSpreads.begin());
strikeInterpolation.enableExtrapolation();
spreadVols[i][j] = strikeInterpolation(
strikes[i][j] - atmForwards[i][j]);
}
} else {
spreadVols[i][j] =
smiles[i][j]->volatility(strikes[i][j]) - atmVols[i][j];
}
}
}
Cube localInterpolator(optionsDateNodes, swapTenorNodes,
optionsNodes, swapLengthsNodes, 1);