-
Notifications
You must be signed in to change notification settings - Fork 497
/
measures_rates.py
2202 lines (1885 loc) · 110 KB
/
measures_rates.py
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
"""
Copyright 2020 Goldman Sachs.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
import datetime
import logging
import re
from collections import OrderedDict
from enum import Enum
from typing import Optional, Union, Dict, List
import pandas as pd
from gs_quant.instrument import IRSwap
from pandas import Series
from gs_quant.api.gs.assets import GsAssetApi
from gs_quant.api.gs.data import QueryType, GsDataApi
from gs_quant.data import DataContext, Dataset
from gs_quant.datetime.gscalendar import GsCalendar
from gs_quant.errors import MqValueError
from gs_quant.markets.securities import AssetIdentifier, Asset
from gs_quant.target.common import Currency as CurrencyEnum, AssetClass, AssetType, PricingLocation, SwapClearingHouse
from gs_quant.timeseries import currency_to_default_ois_asset, convert_asset_for_rates_data_set, RatesConversionType
from gs_quant.timeseries.helper import _to_offset, check_forward_looking, plot_measure
from gs_quant.timeseries.measures import _market_data_timed, _range_from_pricing_date, \
_get_custom_bd, ExtendedSeries, SwaptionTenorType, _extract_series_from_df, GENERIC_DATE, \
_asset_from_spec, ASSET_SPEC, MeasureDependency, _logger
# TODO: Use gs_quant object
class _ClearingHouse(Enum):
LCH = 'LCH'
EUREX = 'EUREX'
JSCC = 'JSCC'
CME = 'CME'
NONE = 'NONE'
class _SwapTenorType(Enum):
FORWARD_TENOR = 'forward_tenor'
SWAP_TENOR = 'swap_tenor'
class EventType(Enum):
MEETING = 'Meeting Forward'
EOY = 'EOY Forward'
SPOT = 'Spot'
class RateType(Enum):
ABSOLUTE = 'absolute'
RELATIVE = 'relative'
CCY_TO_CB = {
'EUR': 'ecb',
'USD': 'frb',
'GBP': 'mpc'
}
CENTRAL_BANK_WATCH_START_DATE = datetime.date(2016, 1, 1)
class TdapiRatesDefaultsProvider:
# flag to indicate that a given property should not be included in asset query
EMPTY_PROPERTY = "null"
def __init__(self, defaults: dict):
self.defaults = defaults
benchmark_mappings = {}
for k, v in defaults.get("CURRENCIES").items():
benchmark_mappings[k] = {e.get("benchmarkType"): e.get('floatingRateOption') for e in v}
self.defaults['MAPPING'] = benchmark_mappings
def is_supported(self, currency: CurrencyEnum):
return currency.value in self.defaults.get("CURRENCIES").keys()
def get_floating_rate_option_for_benchmark(self, currency: CurrencyEnum, benchmark: str):
return self.defaults.get("MAPPING").get(currency.value).get(benchmark)
def get_swaption_parameter(self, currency, field, value=None):
if value == self.EMPTY_PROPERTY:
return None
if value is not None:
return value
if isinstance(currency, str):
currency_name = currency
else:
currency_name = currency.value
for entry in [self.defaults.get("CURRENCIES").get(currency_name)[0], self.defaults.get("COMMON")]:
if field in entry:
value = entry[field][0] if isinstance(entry[field], list) else entry[field]
return value
SWAPTION_DEFAULTS = {
"CURRENCIES": {
"AUD": [{"benchmarkType": "BBR", "floatingRateOption": "AUD-BBR-BBSW", "floatingRateTenor": ["6m", "3m"],
"assetIdForAvailabilityCheck": "MAQHSC1PAF4X5H4B",
"pricingLocation": ["TKO"]}],
"EUR": [
{"benchmarkType": "LIBOR", "floatingRateOption": "EUR-EURIBOR-TELERATE", "floatingRateTenor": ["6m", "3m"],
"assetIdForAvailabilityCheck": "MAZB3PAH8JFVVT80",
"pricingLocation": ["LDN"]},
{"benchmarkType": "EURIBOR", "floatingRateOption": "EUR-EURIBOR-TELERATE",
"floatingRateTenor": ["6m", "3m"],
"assetIdForAvailabilityCheck": "MAZB3PAH8JFVVT80",
"pricingLocation": ["LDN"]}
],
"GBP": [{"benchmarkType": "LIBOR", "floatingRateOption": "GBP-LIBOR-BBA", "floatingRateTenor": ["6m", "3m"],
"assetIdForAvailabilityCheck": "MAX2SBXZRPYR3NTY",
"pricingLocation": ["LDN"]},
{"benchmarkType": "SONIA", "floatingRateOption": "GBP-SONIA-COMPOUND",
"floatingRateTenor": ["1y", "6m", "3m"],
"assetIdForAvailabilityCheck": "MAQC2E5J9X6WGGCJ",
"pricingLocation": ["LDN"]}
],
"JPY": [{"benchmarkType": "LIBOR", "floatingRateOption": "JPY-LIBOR-BBA", "floatingRateTenor": ["6m"],
"assetIdForAvailabilityCheck": "MATT7CA7PRA4B8YB",
"pricingLocation": ["TKO"], }],
"KRW": [{"benchmarkType": "KSDA", "floatingRateOption": "KRW-CD-KSDA-BLOOMBERG", "floatingRateTenor": ["3m"],
"assetIdForAvailabilityCheck": "MAMNSGB00G4ZCWMP",
"pricingLocation": ["TKO"]}],
"NZD": [{"benchmarkType": "BBR", "floatingRateOption": "NZD-BBR-FRA", "floatingRateTenor": ["3m"],
"assetIdForAvailabilityCheck": "MAHGK129ZCWCEG33",
"pricingLocation": ["TKO"], }],
"USD": [{"benchmarkType": "LIBOR", "floatingRateOption": "USD-LIBOR-BBA", "floatingRateTenor": ["3m", "6m"],
"assetIdForAvailabilityCheck": "MAY0X3KRD4AN77E2",
"strikeReference": ["ATM"],
"pricingLocation": ["NYC"]},
{"benchmarkType": "SOFR", "floatingRateOption": "USD-SOFR-COMPOUND",
"floatingRateTenor": ["1y", "6m", "3m"],
"assetIdForAvailabilityCheck": "MANYJ1AWNEX5C7FY",
"strikeReference": ["ATM"],
"pricingLocation": ["NYC"]}
],
},
"COMMON": {
"strikeReference": "ATM",
"clearingHouse": "LCH",
"terminationTenor": "5y",
"expirationTenor": "1y",
"effectiveDate": "0b"
}
}
swaptions_defaults_provider = TdapiRatesDefaultsProvider(SWAPTION_DEFAULTS)
CURRENCY_TO_SWAP_RATE_BENCHMARK = {
'AUD': OrderedDict([('BBR', 'AUD-BBR-BBSW'), ('AONIA', 'AUD-AONIA-OIS-COMPOUND')]),
'BRL': {'CDI': 'BRR-CDI-COMPOUNDED'},
'CAD': OrderedDict([('CDOR', 'CAD-BA-CDOR'), ('CORRA', 'CAD-CORRA-OIS-COMP')]),
'CHF': OrderedDict([('LIBOR', 'CHF-LIBOR-BBA'), ('SARON', 'CHF-SARON-OIS-COMPOUND')]),
'CLP': {'TNA': 'CLP-ICP-CAMARA'},
'CNY': {'REPO': 'CNY-REPO RATE'},
'COP': {'IBR': 'COP-IBR-ON'},
'CZK': {'PRIBOR': 'CZK-PRIBOR-PRBO'},
'DKK': OrderedDict([('CIBOR', 'DKK-CIBOR2-DKNA13'), ('OIS', 'DKK-DKKOIS-OIS-COMPOUND')]),
'EUR': OrderedDict([('EURIBOR', 'EUR-EURIBOR-TELERATE'), ('EONIA', 'EUR-EONIA-OIS-COMPOUND'),
('EUROSTR', 'EUR-EUROSTR-COMPOUND')]),
'GBP': OrderedDict([('LIBOR', 'GBP-LIBOR-BBA'), ('SONIA', 'GBP-SONIA-COMPOUND')]),
'HKD': {'HIBOR': 'HKD-HIBOR-HKAB'},
'HUF': {'BIBOR': 'HUF-BIBOR-BUB'},
'ILS': {'TELBOR': 'ILS-TELBOR-FCI'},
'INR': {'MIBOR': 'INR-MIBOR-OIS-COMPOUND'},
'JPY': OrderedDict([('LIBOR', 'JPY-LIBOR-BBA'), ('TONA', 'JPY-TONA-OIS-COMPOUND')]),
'KRW': {'KSDA': 'KRW-CD-KSDA-BLOOMBERG'},
'MXN': {'TIIE': 'MXN-TIIE-FX'},
'NOK': OrderedDict([('NIBOR', 'NOK-NIBOR-BBA'), ('NOWA', 'NOK-NOWA-OIS-COMPOUND')]),
'NZD': OrderedDict([('BBR', 'NZD-BBR-FRA'), ('NZIONA', 'NZD-NZIONA-OIS-COMPOUND')]),
'PLN': {'WIBOR': 'PLZ-WIBOR-WIBO'},
'RUB': {'MOSPRIME': 'RUB-MOSPRIME-NFEA'},
'SEK': OrderedDict([('STIBOR', 'SEK-STIBOR-SIDE'), ('SIOR', 'SEK-SIOR-OIS-COMPOUND')]),
'SGD': OrderedDict([('SOR', 'SGD-SOR-VWAP'), ('SORA', 'SGD-SORA-COMPOUND')]),
'THB': {'THOR': 'THB-THOR-COMPOUND'},
'USD': OrderedDict(
[('LIBOR', 'USD-LIBOR-BBA'), ('Fed_Funds', 'USD-Federal Funds-H.15-OIS-COMP'), ('SOFR', 'USD-SOFR-COMPOUND')]),
'ZAR': {'JIBAR': 'ZAR-JIBAR-SAFEX'},
}
# TODO Join into single object.
BENCHMARK_TO_DEFAULT_FLOATING_RATE_TENORS = {
'BRR-CDI-COMPOUNDED': '1b',
'AUD-BBR-BBSW': '6m',
'AUD-AONIA-OIS-COMPOUND': '1y',
'CAD-BA-CDOR': '3m',
'CAD-CORRA-OIS-COMP': '3m',
'CHF-LIBOR-BBA': '6m',
'CHF-SARON-OIS-COMPOUND': '1y',
'CLP-ICP-CAMARA': '1b',
'CNY-REPO RATE': '1w',
'COP-IBR-ON': '1b',
'CZK-PRIBOR-PRBO': '6m',
'DKK-CIBOR2-DKNA13': '6m',
'DKK-DKKOIS-OIS-COMPOUND': '1y',
'EUR-EURIBOR-TELERATE': '6m',
'EUR-EUROSTR-COMPOUND': '1y',
'EUR-EONIA-OIS-COMPOUND': '1y',
'GBP-LIBOR-BBA': '6m',
'GBP-SONIA-COMPOUND': '1y',
'HKD-HIBOR-HKAB': '3m',
'HUF-BIBOR-BUB': '6m',
'INR-MIBOR-OIS-COMPOUND': '6m',
'ILS-TELBOR-FCI': '3m',
'JPY-LIBOR-BBA': '6m',
'JPY-TONA-OIS-COMPOUND': '1y',
'KRW-CD-KSDA-BLOOMBERG': '3m',
'MXN-TIIE-FX': '28d',
'NOK-NIBOR-BBA': '6m',
'NOK-NOWA-OIS-COMPOUND': '1y',
'NZD-BBR-FRA': '3m',
'NZD-NZIONA-OIS-COMPOUND': '1y',
'PLZ-WIBOR-WIBO': '6m',
'RUB-MOSPRIME-NFEA': '3m',
'SEK-STIBOR-SIDE': '6m',
'SEK-SIOR-OIS-COMPOUND': '1y',
'SGD-SOR-VWAP': '6m',
'SGD-SORA-COMPOUND': '3m',
'THB-THOR-COMPOUND': '3m',
'USD-LIBOR-BBA': '3m',
'USD-Federal Funds-H.15-OIS-COMP': '1y',
'USD-SOFR-COMPOUND': '1y',
'ZAR-JIBAR-SAFEX': '3m',
}
CURRENCY_TO_PRICING_LOCATION = {
CurrencyEnum.JPY: PricingLocation.TKO,
CurrencyEnum.USD: PricingLocation.NYC,
CurrencyEnum.AUD: PricingLocation.TKO,
CurrencyEnum.NZD: PricingLocation.TKO,
CurrencyEnum.CNY: PricingLocation.HKG,
CurrencyEnum.HKD: PricingLocation.HKG,
CurrencyEnum.INR: PricingLocation.HKG,
CurrencyEnum.KRW: PricingLocation.HKG,
CurrencyEnum.SGD: PricingLocation.HKG,
CurrencyEnum.CAD: PricingLocation.NYC,
CurrencyEnum.EUR: PricingLocation.LDN,
CurrencyEnum.GBP: PricingLocation.LDN,
CurrencyEnum.CHF: PricingLocation.LDN,
CurrencyEnum.DKK: PricingLocation.LDN,
CurrencyEnum.NOK: PricingLocation.LDN,
CurrencyEnum.SEK: PricingLocation.LDN,
CurrencyEnum.BRL: PricingLocation.NYC,
CurrencyEnum.COP: PricingLocation.NYC,
CurrencyEnum.CLP: PricingLocation.NYC,
CurrencyEnum.MXN: PricingLocation.NYC,
}
CURRENCY_TO_DUMMY_SWAP_BBID = {
'CHF': 'MAW25BGQJH9P6DPT',
'EUR': 'MAA9MVX15AJNQCVG',
'GBP': 'MA6QCAP9B7ABS9HA',
'JPY': 'MAEE219J5ZP0ZKRK',
'SEK': 'MAETMVTPNP3199A5',
'USD': 'MAFRSWPAF5QPNTP2',
'DKK': 'MAF131NKWVRESFYA',
'NOK': 'MA25DW5ZGC1BSC8Y',
'HKD': 'MABRNGY8XRFVC36N',
'NZD': 'MAH16NHE1HBN0FBZ',
'AUD': 'MAY8147CRK0ZP53B',
'CNY': 'MA4K1D8HH2R0RQY5',
'CAD': 'MANJ8SS88WJ6N28Q',
'KRW': 'MAP55AXG5SQVS6C5',
'INR': 'MA20JHJXN1PD5HGE',
'SGD': 'MA5CQFHYBPH9E5BS',
'BRL': 'MATPPVN02HJ4M9NS',
'COP': 'MADA0AGFQ65CTMWF',
'CLP': 'MAP8A0SHH9Q86SXC',
'MXN': 'MAAJ9RAHYBAXGYD2'
}
SUPPORTED_INTRADAY_CURRENCY_TO_DUMMY_SWAP_BBID = {
'CHF': 'MACF6R4J5FY4KGBZ',
'EUR': 'MACF6R4J5FY4KGBZ',
'GBP': 'MACF6R4J5FY4KGBZ',
'JPY': 'MACF6R4J5FY4KGBZ',
'SEK': 'MACF6R4J5FY4KGBZ',
'USD': 'MACF6R4J5FY4KGBZ',
'DKK': 'MACF6R4J5FY4KGBZ',
'NOK': 'MACF6R4J5FY4KGBZ',
'NZD': 'MACF6R4J5FY4KGBZ',
'AUD': 'MACF6R4J5FY4KGBZ',
'CAD': 'MACF6R4J5FY4KGBZ'
}
# FXFwd XCCYSwap rates Defaults
CROSS_BBID_TO_DUMMY_OISXCCY_ASSET = {
'EURUSD': 'MA1VJC1E3SZW8E4S',
'GBPUSD': 'MA3JTR4HSC63H4V6',
'AUDUSD': 'MAD4VBRWYXFSY1N4',
'NZDUSD': 'MA1YHQMZVTM3VBWT',
'USDSEK': 'MA2APZREBGDMME83',
'USDNOK': 'MA0K3W6FKH6K1KJE',
'USDDKK': 'MA328HZB86DYSWSJ',
'USDCAD': 'MAT8JNEE2GN5NES6',
'USDCHF': 'MABNGGTNB9A0TKCG',
'USDJPY': 'MAMZ9YG8AF3HQ18C',
}
CURRENCY_TO_CSA_DEFAULT_MAP = {
'USD': 'USD-SOFR',
'EUR': 'EUR-EUROSTR'
}
def _pricing_location_normalized(location: PricingLocation, ccy: CurrencyEnum) -> PricingLocation:
if location == PricingLocation.HKG or location == PricingLocation.TKO:
if ccy in CURRENCY_TO_PRICING_LOCATION.keys() and \
PricingLocation.HKG == CURRENCY_TO_PRICING_LOCATION.get(ccy, PricingLocation.LDN):
return PricingLocation.HKG
else:
return PricingLocation.TKO
else:
return location
def _default_pricing_location(ccy: CurrencyEnum) -> PricingLocation:
if ccy in CURRENCY_TO_PRICING_LOCATION.keys():
return CURRENCY_TO_PRICING_LOCATION.get(ccy, PricingLocation.LDN)
else:
raise MqValueError('No default location set for currency ' + ccy.value + ', please provide one.')
def _cross_to_fxfwd_xcswp_asset(asset_spec: ASSET_SPEC) -> str:
asset = _asset_from_spec(asset_spec)
bbid = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
# for each currency, get a dummy asset for checking availability
result = CROSS_BBID_TO_DUMMY_OISXCCY_ASSET.get(bbid, asset.get_marquee_id())
return result
def _currency_to_tdapi_swap_rate_asset(asset_spec: ASSET_SPEC) -> str:
asset = _asset_from_spec(asset_spec)
bbid = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
# for each currency, get a dummy asset for checking availability
result = CURRENCY_TO_DUMMY_SWAP_BBID.get(bbid, asset.get_marquee_id())
return result
def _currency_to_tdapi_swap_rate_asset_for_intraday(asset_spec: ASSET_SPEC) -> str:
return 'MACF6R4J5FY4KGBZ'
def _currency_to_tdapi_asset_base(asset_spec: ASSET_SPEC, allowed_bbids=None) -> str:
asset = _asset_from_spec(asset_spec)
bbid = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
if bbid is None or (allowed_bbids and bbid not in allowed_bbids):
return asset.get_marquee_id()
try:
result = swaptions_defaults_provider.get_swaption_parameter(bbid, "assetIdForAvailabilityCheck")
except TypeError:
logging.info("No assetIdForAvailabilityCheck for" + bbid)
return asset.get_marquee_id()
return result
def _currency_to_tdapi_midcurve_asset(asset_spec: ASSET_SPEC) -> str:
return _currency_to_tdapi_asset_base(asset_spec, ['GBP', 'EUR', 'USD'])
def _currency_to_tdapi_swaption_rate_asset(asset_spec: ASSET_SPEC) -> str:
return _currency_to_tdapi_asset_base(asset_spec)
def _currency_to_tdapi_basis_swap_rate_asset(asset_spec: ASSET_SPEC) -> str:
asset = _asset_from_spec(asset_spec)
bbid = asset.get_identifier(AssetIdentifier.BLOOMBERG_ID)
# for each currency, get a dummy asset for checking availability
if bbid == 'EUR':
result = 'MAGRG2VT11GQ2RQ9'
elif bbid == 'GBP':
result = 'MAHCYNB3V75JC5Q8'
elif bbid == 'JPY':
result = 'MAXVRBEZCJVH0C4V'
elif bbid == 'USD':
result = 'MAQB1PGEJFCET3GG'
elif bbid == 'CAD':
result = 'MARVD2E65AWEXXBA'
elif bbid == 'AUD':
result = 'MAY8H7HCNZ85FJKM'
elif bbid == 'NZD':
result = 'MAWK15C0P3SM6C7Q'
elif bbid == 'SEK':
result = 'MAS2NJCYHDHP8P0X'
elif bbid == 'NOK':
result = 'MAPXC5YBPZJZXYMZ'
elif bbid == 'DKK':
result = 'MA2164KK5DMYA561'
elif bbid == 'CHF':
result = 'MA7ZHB9T0PF1SB96'
else:
return asset.get_marquee_id()
return result
def _match_floating_tenors(swap_args) -> dict:
payer_index = swap_args['asset_parameters_payer_rate_option']
receiver_index = swap_args['asset_parameters_receiver_rate_option']
if payer_index != receiver_index:
if 'SOFR' in payer_index:
swap_args['asset_parameters_payer_designated_maturity'] = swap_args[
'asset_parameters_receiver_designated_maturity']
if swap_args['asset_parameters_payer_designated_maturity'] == "12m":
swap_args['asset_parameters_payer_designated_maturity'] = "1y"
elif 'SOFR' in receiver_index:
swap_args['asset_parameters_receiver_designated_maturity'] = swap_args[
'asset_parameters_payer_designated_maturity']
if swap_args['asset_parameters_receiver_designated_maturity'] == "12m":
swap_args['asset_parameters_receiver_designated_maturity'] = "1y"
elif 'LIBOR' in payer_index or 'EURIBOR' in payer_index or 'STIBOR' in payer_index:
swap_args['asset_parameters_receiver_designated_maturity'] = swap_args[
'asset_parameters_payer_designated_maturity']
elif 'LIBOR' in receiver_index or 'EURIBOR' in receiver_index or 'STIBOR' in receiver_index:
swap_args['asset_parameters_payer_designated_maturity'] = swap_args[
'asset_parameters_receiver_designated_maturity']
return swap_args
def _get_tdapi_rates_assets(allow_many=False, **kwargs) -> Union[str, list]:
# sanitize input for asset query.
if "pricing_location" in kwargs:
del kwargs["pricing_location"]
assets = GsAssetApi.get_many_assets(**kwargs)
# change order of basis swap legs and check if swap in dataset
if len(assets) == 0 and ('asset_parameters_payer_rate_option' in kwargs): # flip legs
kwargs['asset_parameters_payer_rate_option'], kwargs['asset_parameters_receiver_rate_option'] = \
kwargs['asset_parameters_receiver_rate_option'], kwargs['asset_parameters_payer_rate_option']
kwargs['asset_parameters_payer_designated_maturity'], kwargs[
'asset_parameters_receiver_designated_maturity'] = \
kwargs['asset_parameters_receiver_designated_maturity'], kwargs[
'asset_parameters_payer_designated_maturity']
assets = GsAssetApi.get_many_assets(**kwargs)
if len(assets) > 1:
# term structure measures need multiple assets
if ('asset_parameters_termination_date' not in kwargs) or (
'asset_parameters_effective_date' not in kwargs) or allow_many:
return [asset.id for asset in assets]
else:
raise MqValueError('Specified arguments match multiple assets')
elif len(assets) == 0:
raise MqValueError('Specified arguments did not match any asset in the dataset' + str(kwargs))
else:
return assets[0].id
def _check_forward_tenor(forward_tenor) -> GENERIC_DATE:
if isinstance(forward_tenor, datetime.date):
return forward_tenor
elif forward_tenor in ['Spot', 'spot', 'SPOT']:
return '0b'
elif not (_is_valid_relative_date_tenor(forward_tenor) or
re.fullmatch('(imm[1-4]|frb[1-9]|ecb[1-9])', forward_tenor)):
raise MqValueError('invalid forward tenor ' + forward_tenor)
else:
return forward_tenor
class BenchmarkType(Enum):
LIBOR = 'LIBOR'
EURIBOR = 'EURIBOR'
EUROSTR = 'EUROSTR'
STIBOR = 'STIBOR'
OIS = 'OIS'
CDKSDA = 'CDKSDA'
SOFR = 'SOFR'
SARON = 'SARON'
EONIA = 'EONIA'
SONIA = 'SONIA'
TONA = 'TONA'
Fed_Funds = 'Fed_Funds'
NIBOR = 'NIBOR'
CIBOR = 'CIBOR'
BBR = 'BBR'
BA = 'BA'
KSDA = 'KSDA'
REPO = 'REPO'
SOR = 'SOR'
HIBOR = 'HIBOR'
MIBOR = 'MIBOR'
CDOR = 'CDOR'
CDI = 'CDI'
TNA = 'TNA'
IBR = 'IBR'
TIIE = 'TIIE'
AONIA = 'AONIA'
NZIONA = 'NZIONA'
NOWA = 'NOWA'
CORRA = 'CORRA'
SIOR = 'SIOR'
def _check_benchmark_type(currency, benchmark_type: Union[BenchmarkType, str]) -> BenchmarkType:
if isinstance(benchmark_type, str):
if benchmark_type.upper() in BenchmarkType.__members__:
benchmark_type = BenchmarkType[benchmark_type.upper()]
elif benchmark_type in ['fed_funds', 'Fed_Funds', 'FED_FUNDS']:
benchmark_type = BenchmarkType.Fed_Funds
elif benchmark_type in ['estr', 'ESTR', 'eurostr', 'EuroStr']:
benchmark_type = BenchmarkType.EUROSTR
else:
raise MqValueError('%s is not valid, pick one among ' + ', '.join([x.value for x in BenchmarkType]))
if isinstance(benchmark_type, BenchmarkType) and \
benchmark_type.value not in CURRENCY_TO_SWAP_RATE_BENCHMARK[currency.value].keys():
raise MqValueError('%s is not supported for %s', benchmark_type.value, currency.value)
else:
return benchmark_type
def _check_clearing_house(clearing_house: Union[_ClearingHouse, str]) -> _ClearingHouse:
if isinstance(clearing_house, str) and clearing_house.upper() in _ClearingHouse.__members__:
clearing_house = _ClearingHouse[clearing_house.upper()]
if clearing_house is None:
return _ClearingHouse.LCH
elif isinstance(clearing_house, _ClearingHouse):
return clearing_house
else:
raise MqValueError('invalid clearing house: ' + clearing_house + ' choose one among ' +
', '.join([ch.value for ch in _ClearingHouse]))
def _check_tenor_type(tenor_type: _SwapTenorType) -> _SwapTenorType:
if isinstance(tenor_type, str) and tenor_type.upper() in _SwapTenorType.__members__:
tenor_type = _SwapTenorType[tenor_type.upper()]
if tenor_type is None:
return _SwapTenorType.FORWARD_TENOR
elif isinstance(tenor_type, _SwapTenorType):
return tenor_type
else:
raise MqValueError('invalid tenor_type: ' + tenor_type + ' choose one among ' +
', '.join([ch.value for ch in _SwapTenorType]))
def _check_term_structure_tenor(tenor_type: _SwapTenorType, tenor: str) -> Dict:
if tenor_type == _SwapTenorType.FORWARD_TENOR:
tenor = _check_forward_tenor(tenor)
tenor_to_plot = 'terminationTenor'
tenor_dataset_field = 'asset_parameters_effective_date'
elif not re.fullmatch('(\\d+)([bdwmy])', tenor) or re.fullmatch('(frb[1-9])', tenor):
raise MqValueError('invalid swap tenor ' + tenor)
else:
tenor_to_plot = 'effectiveTenor'
tenor_dataset_field = 'asset_parameters_termination_date'
return dict(tenor=tenor, tenor_to_plot=tenor_to_plot, tenor_dataset_field=tenor_dataset_field)
def _get_benchmark_type(currency: CurrencyEnum, benchmark_type: BenchmarkType = None):
if benchmark_type is None:
if currency == CurrencyEnum.EUR:
benchmark_type = BenchmarkType.EURIBOR
elif currency == CurrencyEnum.SEK:
benchmark_type = BenchmarkType.STIBOR
else:
benchmark_type = BenchmarkType(str(list(CURRENCY_TO_SWAP_RATE_BENCHMARK[currency.value].keys())[0]))
benchmark_type_input = CURRENCY_TO_SWAP_RATE_BENCHMARK[currency.value][benchmark_type.value]
return benchmark_type_input
def _get_swap_leg_defaults(currency: CurrencyEnum, benchmark_type: BenchmarkType = None,
floating_rate_tenor: str = None) -> dict:
pricing_location = CURRENCY_TO_PRICING_LOCATION.get(currency, PricingLocation.LDN)
# default benchmark types
benchmark_type_input = _get_benchmark_type(currency, benchmark_type)
# default floating index
if floating_rate_tenor is None:
floating_rate_tenor = BENCHMARK_TO_DEFAULT_FLOATING_RATE_TENORS[benchmark_type_input]
return dict(currency=currency, benchmark_type=benchmark_type_input,
floating_rate_tenor=floating_rate_tenor, pricing_location=pricing_location)
def _get_swap_csa_terms(curr: str, benchmark_type: str) -> dict:
euribor_index = CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EURIBOR.value]
usd_libor_index = CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.LIBOR.value]
estr_index = CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EUROSTR.value]
if benchmark_type in [euribor_index, usd_libor_index]:
return {}
elif benchmark_type == estr_index:
return dict(csaTerms=curr + '-EuroSTR')
else:
return dict(csaTerms=curr + '-1')
def _get_basis_swap_csa_terms(curr: str, payer_benchmark: str, receiver_benchmark: str) -> dict:
benchmarks = [payer_benchmark, receiver_benchmark]
euribor_index: str = CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EURIBOR.value]
usd_libor_index: str = CURRENCY_TO_SWAP_RATE_BENCHMARK['USD'][BenchmarkType.LIBOR.value]
estr_index: str = CURRENCY_TO_SWAP_RATE_BENCHMARK['EUR'][BenchmarkType.EUROSTR.value]
if (euribor_index in benchmarks) or (usd_libor_index in benchmarks):
return {} # different csaTerms after SOFR and ESTR transitions for a given asset
elif estr_index in benchmarks:
return dict(csaTerms=curr + '-EuroSTR')
else:
return dict(csaTerms=curr + '-1')
def _get_swap_data(asset: Asset, swap_tenor: str, benchmark_type: str = None, floating_rate_tenor: str = None,
forward_tenor: Optional[GENERIC_DATE] = None, clearing_house: _ClearingHouse = None,
source: str = None, real_time: bool = False, location: PricingLocation = None,
query_type: QueryType = QueryType.SWAP_RATE) -> pd.DataFrame:
if real_time and not (query_type == QueryType.SWAP_RATE):
raise NotImplementedError('realtime swap_rate not implemented for anything but rates')
currency = CurrencyEnum(asset.get_identifier(AssetIdentifier.BLOOMBERG_ID))
if currency.value not in CURRENCY_TO_SWAP_RATE_BENCHMARK.keys():
raise NotImplementedError('Data not available for {} swap rates'.format(currency.value))
benchmark_type = _check_benchmark_type(currency, benchmark_type)
clearing_house = _check_clearing_house(clearing_house)
defaults = _get_swap_leg_defaults(currency, benchmark_type, floating_rate_tenor)
if not (re.fullmatch('(\\d+)([bdwmy])', swap_tenor) or re.fullmatch('(frb[1-9]|ecb[1-6])', forward_tenor)):
raise MqValueError('invalid swap tenor ' + swap_tenor)
if not re.fullmatch('(\\d+)([bdwmy])', defaults['floating_rate_tenor']):
raise MqValueError('invalid floating rate tenor ' + defaults['floating_rate_tenor'] + ' for index: ' +
defaults['benchmark_type'])
forward_tenor = _check_forward_tenor(forward_tenor)
fixed_rate = 'ATM'
if location is None:
pricing_location = _default_pricing_location(currency)
else:
pricing_location = PricingLocation(location)
kwargs = dict(asset_class='Rates', type='Swap', asset_parameters_termination_date=swap_tenor,
asset_parameters_floating_rate_option=defaults['benchmark_type'],
asset_parameters_fixed_rate=fixed_rate, asset_parameters_clearing_house=clearing_house.value,
asset_parameters_floating_rate_designated_maturity=defaults['floating_rate_tenor'],
asset_parameters_effective_date=forward_tenor,
asset_parameters_notional_currency=currency.name)
rate_mqid = _get_tdapi_rates_assets(**kwargs)
_logger.debug('where asset= %s, swap_tenor=%s, benchmark_type=%s, floating_rate_tenor=%s, forward_tenor=%s, '
'pricing_location=%s', rate_mqid, swap_tenor, defaults['benchmark_type'],
defaults['floating_rate_tenor'], forward_tenor, pricing_location.value)
pricing_location = _pricing_location_normalized(pricing_location, currency)
where = dict(pricingLocation=pricing_location.value)
q = GsDataApi.build_market_data_query([rate_mqid], query_type, where=where, source=source,
real_time=real_time)
_logger.debug('q %s', q)
df = _market_data_timed(q)
return df
def _get_swap_data_calc(asset: Asset, swap_tenor: str, benchmark_type: str = None, floating_rate_tenor: str = None,
forward_tenor: Optional[GENERIC_DATE] = None, csa: str = None,
real_time: bool = False, location: PricingLocation = None) -> pd.DataFrame:
currency = CurrencyEnum(asset.get_identifier(AssetIdentifier.BLOOMBERG_ID))
benchmark_type = _check_benchmark_type(currency, benchmark_type)
clearing_house = SwapClearingHouse.LCH
if csa in ['EUREX', 'JSCC', 'CME']:
clearing_house = SwapClearingHouse(csa)
defaults = _get_swap_leg_defaults(currency, benchmark_type, floating_rate_tenor)
if not re.fullmatch('(\\d+)([bdwmy])', swap_tenor):
raise MqValueError('invalid swap tenor ' + swap_tenor)
forward_tenor = _check_forward_tenor(forward_tenor)
builder = IRSwap(notional_currency=currency, clearing_house=clearing_house,
floating_rate_designated_maturity=defaults['floating_rate_tenor'],
floating_rate_option=defaults['benchmark_type'],
fixed_rate=0.0, termination_date=swap_tenor)
if forward_tenor:
builder.startdate = forward_tenor
_logger.debug(f'where builder={builder.as_dict()}')
location = location or PricingLocation.NYC
q = GsDataApi.get_mxapi_backtest_data(builder, close_location=location.value, real_time=real_time, csa=csa)
return q
def _get_term_struct_date(tenor: Union[str, datetime.datetime], index: datetime.datetime,
business_day) -> datetime.datetime:
if isinstance(tenor, (datetime.datetime, datetime.date)):
return tenor
try:
year, month, day = tenor.split('-')
return datetime.datetime(int(year), int(month), int(day))
except ValueError:
if tenor == '0b':
return index + business_day - business_day
else:
return index + _to_offset(tenor) + business_day - business_day
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_swap_rate_asset, query_type=QueryType.SWAP_ANNUITY)])
def swap_annuity(asset: Asset, swap_tenor: str, benchmark_type: str = None, floating_rate_tenor: str = None,
forward_tenor: Optional[GENERIC_DATE] = None, clearing_house: _ClearingHouse = None,
location: PricingLocation = None, *,
source: str = None, real_time: bool = False) -> Series:
"""
GS end-of-day Fixed-Floating interest rate swap(IRS) annuity values in years for paying leg across major currencies.
:param asset: asset object loaded from security master
:param swap_tenor: relative date representation of expiration date e.g. 1m
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param forward_tenor: absolute / relative date representation of forward starting point eg: '1y' or 'Spot' for
spot starting swaps, 'imm1' or 'frb1'
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: annuity of swap
"""
df = _get_swap_data(asset=asset, swap_tenor=swap_tenor, benchmark_type=benchmark_type,
floating_rate_tenor=floating_rate_tenor, forward_tenor=forward_tenor,
clearing_house=clearing_house, source=source,
real_time=real_time, query_type=QueryType.SWAP_ANNUITY, location=location)
series = ExtendedSeries(dtype=float) if df.empty else ExtendedSeries(abs(df['swapAnnuity'] * 1e4 / 1e8))
series.dataset_ids = getattr(df, 'dataset_ids', ())
return series
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_swaption_rate_asset,
query_type=QueryType.SWAPTION_PREMIUM)])
def swaption_premium(asset: Asset, expiration_tenor: str = None, termination_tenor: str = None,
relative_strike: str = None, benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *,
source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day premium for swaption.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param relative_strike: strike level relative to at the money e.g. 10 or ATM+10
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type, floating_rate_tenor, "0b", expiration_tenor,
termination_tenor, relative_strike, clearing_house, source=source, real_time=real_time,
start=DataContext.current.start_date, end=DataContext.current.end_date,
query_type=QueryType.SWAPTION_PREMIUM, location=location)
return _extract_series_from_df(df, QueryType.SWAPTION_PREMIUM)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_swaption_rate_asset,
query_type=QueryType.SWAPTION_ANNUITY)])
def swaption_annuity(asset: Asset, expiration_tenor: str = None, termination_tenor: str = None,
relative_strike: float = None, benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *,
source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day annuity for swaption.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param relative_strike: strike level relative to at the money e.g. 10 or ATM+10
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type, floating_rate_tenor, "0b", expiration_tenor,
termination_tenor, relative_strike, clearing_house, source=source, real_time=real_time,
start=DataContext.current.start_date, end=DataContext.current.end_date,
query_type=QueryType.SWAPTION_ANNUITY, location=location)
return _extract_series_from_df(df, QueryType.SWAPTION_ANNUITY)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_midcurve_asset,
query_type=QueryType.MIDCURVE_PREMIUM)])
def midcurve_premium(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str,
relative_strike: float = None, benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *,
source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day premium for midcurve
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param forward_tenor: relative date representation of swap's start date after option expiry e.g. 2y
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param relative_strike: strike level relative to at the money e.g. 10 or ATM+10
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type, floating_rate_tenor, forward_tenor, expiration_tenor,
termination_tenor, relative_strike, clearing_house, source=source, real_time=real_time,
start=DataContext.current.start_date, end=DataContext.current.end_date,
query_type=QueryType.MIDCURVE_PREMIUM, location=location)
return _extract_series_from_df(df, QueryType.MIDCURVE_PREMIUM)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_midcurve_asset,
query_type=QueryType.MIDCURVE_ANNUITY)])
def midcurve_annuity(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str,
relative_strike: float = None, benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None,
*, source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day annuity for midcurve.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param forward_tenor: relative date representation of swap's start date after option expiry e.g. 2y
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param relative_strike: strike level relative to at the money e.g. 10 or ATM+10
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type, floating_rate_tenor, forward_tenor, expiration_tenor,
termination_tenor, relative_strike, clearing_house, source=source, real_time=real_time,
start=DataContext.current.start_date, end=DataContext.current.end_date,
query_type=QueryType.MIDCURVE_ANNUITY, location=location)
return _extract_series_from_df(df, QueryType.MIDCURVE_ANNUITY)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_swaption_rate_asset,
query_type=QueryType.ATM_FWD_RATE)])
def swaption_atm_fwd_rate(asset: Asset, expiration_tenor: str = None, termination_tenor: str = None,
benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None,
*, source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day atm forward rate for swaption vol matrices.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type=benchmark_type, floating_rate_tenor=floating_rate_tenor,
effective_date="0b", expiration_tenor=expiration_tenor,
termination_tenor=termination_tenor, clearing_house=clearing_house, source=source,
real_time=real_time, start=DataContext.current.start_date,
end=DataContext.current.end_date,
query_type=QueryType.ATM_FWD_RATE, location=location)
return _extract_series_from_df(df, QueryType.ATM_FWD_RATE)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_swaption_rate_asset,
query_type=QueryType.SWAPTION_VOL)])
def swaption_vol(asset: Asset, expiration_tenor: str = None, termination_tenor: str = None,
relative_strike: float = None, benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *, source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day implied normal volatility for swaption vol matrices.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param relative_strike: strike level relative to at the money e.g. 10 or ATM+10
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type, floating_rate_tenor, "0b", expiration_tenor,
termination_tenor, relative_strike, clearing_house, source=source, real_time=real_time,
query_type=QueryType.SWAPTION_VOL, start=DataContext.current.start_date,
end=DataContext.current.end_date, location=location)
return _extract_series_from_df(df, QueryType.SWAPTION_VOL)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_midcurve_asset,
query_type=QueryType.MIDCURVE_VOL)])
def midcurve_vol(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str,
relative_strike: float = None, benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *, source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day implied normal volatility for swaption vol matrices.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param forward_tenor: relative date representation of swap's start date after option expiry e.g. 2y
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param relative_strike: strike level relative to at the money e.g. 10 or ATM+10
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type, floating_rate_tenor, forward_tenor, expiration_tenor,
termination_tenor, relative_strike, clearing_house, source=source, real_time=real_time,
query_type=QueryType.MIDCURVE_VOL, start=DataContext.current.start_date,
end=DataContext.current.end_date, location=location)
return _extract_series_from_df(df, QueryType.MIDCURVE_VOL)
@plot_measure((AssetClass.Cash,), (AssetType.Currency,),
[MeasureDependency(id_provider=_currency_to_tdapi_midcurve_asset,
query_type=QueryType.MIDCURVE_ATM_FWD_RATE)])
def midcurve_atm_fwd_rate(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str,
benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *, source: str = None,
real_time: bool = False) -> Series:
"""
GS end-of-day atm forward rate for swaption vol matrices.
:param asset: asset object loaded from security master
:param expiration_tenor: relative date representation of expiration date on the option e.g. 3m
:param forward_tenor: relative date representation of swap's start date after option expiry e.g. 2y
:param termination_tenor: relative date representation of the instrument's expiration date e.g. 1y
:param benchmark_type: benchmark type e.g. LIBOR
:param floating_rate_tenor: floating index rate
:param clearing_house: Example - "LCH", "EUREX", "JSCC", "CME"
:param location: Example - "TKO", "LDN", "NYC"
:param source: name of function caller
:param real_time: whether to retrieve intraday data instead of EOD
:return: swaption implied normal volatility curve
"""
df = _get_swaption_measure(asset, benchmark_type=benchmark_type, floating_rate_tenor=floating_rate_tenor,
effective_date=forward_tenor, expiration_tenor=expiration_tenor,
termination_tenor=termination_tenor, clearing_house=clearing_house, source=source,
real_time=real_time, start=DataContext.current.start_date,
end=DataContext.current.end_date,
query_type=QueryType.MIDCURVE_ATM_FWD_RATE, location=location)
return _extract_series_from_df(df, QueryType.MIDCURVE_ATM_FWD_RATE)