volvisdata 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,916 @@
1
+ """
2
+ Methods for extracting Implied Vol and producing skew reports
3
+
4
+ """
5
+ from collections import Counter
6
+ import copy
7
+ from decimal import Decimal
8
+ import datetime as dt
9
+ from dateutil.relativedelta import relativedelta
10
+ import numpy as np
11
+ import pandas as pd
12
+ import scipy as sp
13
+ import scipy.interpolate as inter
14
+ import scipy.stats as si
15
+ # pylint: disable=invalid-name, consider-using-f-string
16
+
17
+ class ImpliedVol():
18
+ """
19
+ Implied Volatility Extraction methods
20
+
21
+ """
22
+ @classmethod
23
+ def implied_vol_newton_raphson(cls, opt_params: dict) -> float | str:
24
+ """
25
+ Finds implied volatility using Newton-Raphson method - needs
26
+ knowledge of partial derivative of option pricing formula
27
+ with respect to volatility (vega)
28
+
29
+ Parameters
30
+ ----------
31
+ S : Float
32
+ Stock Price. The default is 100.
33
+ K : Float
34
+ Strike Price. The default is 100.
35
+ T : Float
36
+ Time to Maturity. The default is 0.25 (3 Months).
37
+ r : Float
38
+ Interest Rate. The default is 0.005 (50bps)
39
+ q : Float
40
+ Dividend Yield. The default is 0.
41
+ cm : Float
42
+ # Option price used to solve for vol. The default is 5.
43
+ epsilon : Float
44
+ Degree of precision. The default is 0.0001
45
+ option : Str
46
+ Type of option. 'put' or 'call'. The default is 'call'.
47
+ default : Bool
48
+ Whether the function is being called directly (in which
49
+ case values that are not supplied are set to default
50
+ values) or called from another function where they have
51
+ already been updated.
52
+
53
+ Returns
54
+ -------
55
+ result : Float
56
+ Implied Volatility.
57
+
58
+ """
59
+
60
+ # Manaster and Koehler seed value
61
+ opt_params['vi'] = np.sqrt(
62
+ abs(np.log(opt_params['S'] / opt_params['K'])
63
+ + opt_params['r'] * opt_params['T']) * (2 / opt_params['T']))
64
+
65
+ opt_params['ci'] = cls.black_scholes_merton(
66
+ opt_params=opt_params, sigma=opt_params['vi'])
67
+
68
+ opt_params['vegai'] = cls.black_scholes_merton_vega(
69
+ opt_params=opt_params, sigma=opt_params['vi'])
70
+
71
+ opt_params['mindiff'] = abs(opt_params['cm'] - opt_params['ci'])
72
+
73
+ while (abs(opt_params['cm'] - opt_params['ci'])
74
+ >= opt_params['epsilon']
75
+ and abs(opt_params['cm'] - opt_params['ci'])
76
+ <= opt_params['mindiff']):
77
+
78
+ opt_params['vi'] = (
79
+ opt_params['vi']
80
+ - (opt_params['ci'] - opt_params['cm']) / opt_params['vegai'])
81
+
82
+ opt_params['ci'] = cls.black_scholes_merton(
83
+ opt_params=opt_params, sigma=opt_params['vi'])
84
+
85
+ opt_params['vegai'] = cls.black_scholes_merton_vega(
86
+ opt_params=opt_params, sigma=opt_params['vi'])
87
+
88
+ opt_params['mindiff'] = abs(opt_params['cm'] - opt_params['ci'])
89
+
90
+ if abs(opt_params['cm'] - opt_params['ci']) < opt_params['epsilon']:
91
+ result = opt_params['vi']
92
+ else:
93
+ result = 'NA'
94
+
95
+ return result
96
+
97
+
98
+ @classmethod
99
+ def implied_vol_bisection(cls, opt_params: dict) -> float | str:
100
+ """
101
+ Finds implied volatility using bisection method.
102
+
103
+ Parameters
104
+ ----------
105
+ S : Float
106
+ Stock Price. The default is 100.
107
+ K : Float
108
+ Strike Price. The default is 100.
109
+ T : Float
110
+ Time to Maturity. The default is 0.25 (3 Months).
111
+ r : Float
112
+ Interest Rate. The default is 0.005 (50bps)
113
+ q : Float
114
+ Dividend Yield. The default is 0.
115
+ cm : Float
116
+ # Option price used to solve for vol. The default is 5.
117
+ epsilon : Float
118
+ Degree of precision. The default is 0.0001
119
+ option : Str
120
+ Type of option. 'put' or 'call'. The default is 'call'.
121
+ default : Bool
122
+ Whether the function is being called directly (in which
123
+ case values that are not supplied are set to default
124
+ values) or called from another function where they have
125
+ already been updated.
126
+
127
+ Returns
128
+ -------
129
+ result : Float
130
+ Implied Volatility.
131
+
132
+ """
133
+
134
+ opt_params['vLow'] = 0.005
135
+ opt_params['vHigh'] = 4
136
+ opt_params['cLow'] = cls.black_scholes_merton(
137
+ opt_params=opt_params, sigma=opt_params['vLow'])
138
+
139
+ opt_params['cHigh'] = cls.black_scholes_merton(
140
+ opt_params=opt_params, sigma=opt_params['vHigh'])
141
+
142
+ counter = 0
143
+
144
+ opt_params['vi'] = (
145
+ opt_params['vLow']
146
+ + (opt_params['cm'] - opt_params['cLow'])
147
+ * (opt_params['vHigh'] - opt_params['vLow'])
148
+ / (opt_params['cHigh'] - opt_params['cLow']))
149
+
150
+ while abs(opt_params['cm'] - cls.black_scholes_merton(
151
+ opt_params=opt_params,
152
+ sigma=opt_params['vi'])) > opt_params['epsilon']:
153
+
154
+ counter = counter + 1
155
+ if counter == 100:
156
+ result = 'NA'
157
+
158
+ if cls.black_scholes_merton(
159
+ opt_params=opt_params,
160
+ sigma=opt_params['vi']) < opt_params['cm']:
161
+ opt_params['vLow'] = opt_params['vi']
162
+
163
+ else:
164
+ opt_params['vHigh'] = opt_params['vi']
165
+
166
+ opt_params['cLow'] = cls.black_scholes_merton(
167
+ opt_params=opt_params, sigma=opt_params['vLow'])
168
+
169
+ opt_params['cHigh'] = cls.black_scholes_merton(
170
+ opt_params=opt_params, sigma=opt_params['vHigh'])
171
+
172
+ opt_params['vi'] = (
173
+ opt_params['vLow']
174
+ + (opt_params['cm'] - opt_params['cLow'])
175
+ * (opt_params['vHigh'] - opt_params['vLow'])
176
+ / (opt_params['cHigh'] - opt_params['cLow']))
177
+
178
+ result = opt_params['vi']
179
+
180
+ return result
181
+
182
+
183
+ @classmethod
184
+ def implied_vol_naive(cls, opt_params: dict) -> float:
185
+ """
186
+ Finds implied volatility using simple naive iteration,
187
+ increasing precision each time the difference changes sign.
188
+
189
+ Parameters
190
+ ----------
191
+ S : Float
192
+ Stock Price. The default is 100.
193
+ K : Float
194
+ Strike Price. The default is 100.
195
+ T : Float
196
+ Time to Maturity. The default is 0.25 (3 Months).
197
+ r : Float
198
+ Interest Rate. The default is 0.005 (50bps)
199
+ q : Float
200
+ Dividend Yield. The default is 0.
201
+ cm : Float
202
+ # Option price used to solve for vol. The default is 5.
203
+ epsilon : Float
204
+ Degree of precision. The default is 0.0001
205
+ option : Str
206
+ Type of option. 'put' or 'call'. The default is 'call'.
207
+
208
+ Returns
209
+ -------
210
+ result : Float
211
+ Implied Volatility.
212
+
213
+ """
214
+
215
+ # Seed vol
216
+ opt_params['vi'] = 0.2
217
+
218
+ # Calculate starting option price using this vol
219
+ opt_params['ci'] = cls.black_scholes_merton(
220
+ opt_params=opt_params, sigma=opt_params['vi'])
221
+
222
+ # Initial price difference
223
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
224
+
225
+ if opt_params['price_diff'] > 0:
226
+ opt_params['flag'] = 1
227
+
228
+ else:
229
+ opt_params['flag'] = -1
230
+
231
+ # Starting vol shift size
232
+ opt_params['shift'] = 0.01
233
+
234
+ opt_params['price_diff_start'] = opt_params['price_diff']
235
+
236
+ while abs(opt_params['price_diff']) > opt_params['epsilon']:
237
+
238
+ # If the price difference changes sign after the vol shift,
239
+ # reduce the decimal by one and reverse the sign
240
+ if (np.sign(opt_params['price_diff'])
241
+ != np.sign(opt_params['price_diff_start'])):
242
+ opt_params['shift'] = opt_params['shift'] * -0.1
243
+
244
+ # Calculate new vol
245
+ opt_params['vi'] += (opt_params['shift'] * opt_params['flag'])
246
+
247
+ # Set initial price difference
248
+ opt_params['price_diff_start'] = opt_params['price_diff']
249
+
250
+ # Calculate the option price with new vol
251
+ opt_params['ci'] = cls.black_scholes_merton(
252
+ opt_params=opt_params, sigma=opt_params['vi'])
253
+
254
+ # Price difference after shifting vol
255
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
256
+
257
+ # If values are diverging reverse the shift sign
258
+ if (abs(opt_params['price_diff'])
259
+ > abs(opt_params['price_diff_start'])):
260
+ opt_params['shift'] = -opt_params['shift']
261
+
262
+ result = opt_params['vi']
263
+
264
+ return result
265
+
266
+
267
+ @classmethod
268
+ def implied_vol_naive_verbose(cls, opt_params: dict) -> float:
269
+ """
270
+ Finds implied volatility using simple naive iteration,
271
+ increasing precision each time the difference changes sign.
272
+
273
+ Parameters
274
+ ----------
275
+ S : Float
276
+ Stock Price. The default is 100.
277
+ K : Float
278
+ Strike Price. The default is 100.
279
+ T : Float
280
+ Time to Maturity. The default is 0.25 (3 Months).
281
+ r : Float
282
+ Interest Rate. The default is 0.005 (50bps)
283
+ q : Float
284
+ Dividend Yield. The default is 0.
285
+ cm : Float
286
+ # Option price used to solve for vol. The default is 5.
287
+ epsilon : Float
288
+ Degree of precision. The default is 0.0001
289
+ option : Str
290
+ Type of option. 'put' or 'call'. The default is 'call'.
291
+
292
+ Returns
293
+ -------
294
+ result : Float
295
+ Implied Volatility.
296
+
297
+ """
298
+
299
+ opt_params['vi'] = 0.2
300
+ opt_params['ci'] = cls.black_scholes_merton(
301
+ opt_params=opt_params, sigma=opt_params['vi'])
302
+
303
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
304
+ if opt_params['price_diff'] > 0:
305
+ opt_params['flag'] = 1
306
+ else:
307
+ opt_params['flag'] = -1
308
+ while abs(opt_params['price_diff']) > opt_params['epsilon']:
309
+ while opt_params['price_diff'] * opt_params['flag'] > 0:
310
+ opt_params['ci'] = cls.black_scholes_merton(
311
+ opt_params=opt_params, sigma=opt_params['vi'])
312
+
313
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
314
+ opt_params['vi'] += (0.01 * opt_params['flag'])
315
+
316
+ while opt_params['price_diff'] * opt_params['flag'] < 0:
317
+ opt_params['ci'] = cls.black_scholes_merton(
318
+ opt_params=opt_params, sigma=opt_params['vi'])
319
+
320
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
321
+ opt_params['vi'] -= (0.001 * opt_params['flag'])
322
+
323
+ while opt_params['price_diff'] * opt_params['flag'] > 0:
324
+ opt_params['ci'] = cls.black_scholes_merton(
325
+ opt_params=opt_params, sigma=opt_params['vi'])
326
+
327
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
328
+ opt_params['vi'] += (0.0001 * opt_params['flag'])
329
+
330
+ while opt_params['price_diff'] * opt_params['flag'] < 0:
331
+ opt_params['ci'] = cls.black_scholes_merton(
332
+ opt_params=opt_params, sigma=opt_params['vi'])
333
+
334
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
335
+ opt_params['vi'] -= (0.00001 * opt_params['flag'])
336
+
337
+ while opt_params['price_diff'] * opt_params['flag'] > 0:
338
+ opt_params['ci'] = cls.black_scholes_merton(
339
+ opt_params=opt_params, sigma=opt_params['vi'])
340
+
341
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
342
+ opt_params['vi'] += (0.000001 * opt_params['flag'])
343
+
344
+ while opt_params['price_diff'] * opt_params['flag'] < 0:
345
+ opt_params['ci'] = cls.black_scholes_merton(
346
+ opt_params=opt_params, sigma=opt_params['vi'])
347
+
348
+ opt_params['price_diff'] = opt_params['cm'] - opt_params['ci']
349
+ opt_params['vi'] -= (0.0000001 * opt_params['flag'])
350
+
351
+ result = opt_params['vi']
352
+
353
+ return result
354
+
355
+
356
+ @staticmethod
357
+ def black_scholes_merton(
358
+ opt_params: dict,
359
+ sigma: float) -> float:
360
+ """
361
+ Black-Scholes-Merton Option price
362
+
363
+ Parameters
364
+ ----------
365
+ S : Float
366
+ Stock Price. The default is 100.
367
+ K : Float
368
+ Strike Price. The default is 100.
369
+ T : Float
370
+ Time to Maturity. The default is 0.25 (3 Months).
371
+ r : Float
372
+ Interest Rate. The default is 0.005 (50bps)
373
+ q : Float
374
+ Dividend Yield. The default is 0.
375
+ sigma : Float
376
+ Implied Volatility. The default is 0.2 (20%).
377
+ option : Str
378
+ Type of option. 'put' or 'call'. The default is 'call'.
379
+
380
+ Returns
381
+ -------
382
+ opt_price : Float
383
+ Option Price.
384
+
385
+ """
386
+
387
+ opt_params['b'] = opt_params['r'] - opt_params['q']
388
+ opt_params['carry'] = np.exp(
389
+ (opt_params['b'] - opt_params['r']) * opt_params['T'])
390
+ opt_params['d1'] = (
391
+ (np.log(opt_params['S'] / opt_params['K'])
392
+ + (opt_params['b'] + (0.5 * sigma ** 2)) * opt_params['T'])
393
+ / (sigma * np.sqrt(opt_params['T'])))
394
+ opt_params['d2'] = (
395
+ (np.log(opt_params['S'] / opt_params['K'])
396
+ + (opt_params['b'] - (0.5 * sigma ** 2)) * opt_params['T'])
397
+ / (sigma * np.sqrt(opt_params['T'])))
398
+
399
+ # Cumulative normal distribution function
400
+ opt_params['Nd1'] = si.norm.cdf(opt_params['d1'], 0.0, 1.0)
401
+ opt_params['minusNd1'] = si.norm.cdf(-opt_params['d1'], 0.0, 1.0)
402
+ opt_params['Nd2'] = si.norm.cdf(opt_params['d2'], 0.0, 1.0)
403
+ opt_params['minusNd2'] = si.norm.cdf(-opt_params['d2'], 0.0, 1.0)
404
+
405
+ if opt_params['option'] == "call":
406
+ opt_price = (
407
+ (opt_params['S'] * opt_params['carry'] * opt_params['Nd1'])
408
+ - (opt_params['K']
409
+ * np.exp(-opt_params['r'] * opt_params['T'])
410
+ * opt_params['Nd2']))
411
+
412
+ elif opt_params['option'] == 'put':
413
+ opt_price = (
414
+ (opt_params['K']
415
+ * np.exp(-opt_params['r'] * opt_params['T'])
416
+ * opt_params['minusNd2'])
417
+ - (opt_params['S']
418
+ * opt_params['carry']
419
+ * opt_params['minusNd1']))
420
+
421
+ else:
422
+ print("Please supply a value for option - 'put' or 'call'")
423
+
424
+ return opt_price
425
+
426
+
427
+ @staticmethod
428
+ def black_scholes_merton_vega(
429
+ opt_params: dict,
430
+ sigma: float) -> float:
431
+ """
432
+ Black-Scholes-Merton Option Vega
433
+
434
+ Parameters
435
+ ----------
436
+ S : Float
437
+ Stock Price. The default is 100.
438
+ K : Float
439
+ Strike Price. The default is 100.
440
+ T : Float
441
+ Time to Maturity. The default is 0.25 (3 Months).
442
+ r : Float
443
+ Interest Rate. The default is 0.005 (50bps)
444
+ q : Float
445
+ Dividend Yield. The default is 0.
446
+ sigma : Float
447
+ Implied Volatility. The default is 0.2 (20%).
448
+
449
+ Returns
450
+ -------
451
+ opt_vega : Float
452
+ Option Vega.
453
+
454
+ """
455
+
456
+ opt_params['b'] = opt_params['r'] - opt_params['q']
457
+ opt_params['carry'] = np.exp(
458
+ (opt_params['b'] - opt_params['r']) * opt_params['T'])
459
+ opt_params['d1'] = (
460
+ (np.log(opt_params['S'] / opt_params['K'])
461
+ + (opt_params['b'] + (0.5 * sigma ** 2)) * opt_params['T'])
462
+ / (sigma * np.sqrt(opt_params['T'])))
463
+ opt_params['nd1'] = (
464
+ 1 / np.sqrt(2 * np.pi)) * (np.exp(-opt_params['d1'] ** 2 * 0.5))
465
+
466
+ opt_vega = (opt_params['S']
467
+ * opt_params['carry']
468
+ * opt_params['nd1']
469
+ * np.sqrt(opt_params['T']))
470
+
471
+ return opt_vega
472
+
473
+
474
+ class VolMethods():
475
+ """
476
+ Methods for extracting Implied Vol and producing skew reports
477
+
478
+ """
479
+ @classmethod
480
+ def smooth(
481
+ cls,
482
+ params: dict,
483
+ tables: dict) -> tuple[dict, dict]:
484
+ """
485
+ Create a column of smoothed implied vols
486
+
487
+ Parameters
488
+ ----------
489
+ order : Int
490
+ Polynomial order used in numpy polyfit function. The
491
+ default is 3.
492
+ voltype : Str
493
+ Whether to use 'bid', 'mid', 'ask' or 'last' price. The
494
+ default is 'last'.
495
+ smoothopt : Int
496
+ Minimum number of options to fit curve to. The default
497
+ is 6.
498
+
499
+ Returns
500
+ -------
501
+ DataFrame
502
+ DataFrame of Option prices.
503
+
504
+ """
505
+
506
+ # Create a dictionary of the number of options for each
507
+ # maturity
508
+ mat_dict = dict(Counter(tables['imp_vol_data']['Days']))
509
+
510
+ # Create a sorted list of the different number of days to
511
+ # maturity
512
+ maturities = sorted(list(set(tables['imp_vol_data']['Days'])))
513
+
514
+ # Create a sorted list of the different number of strikes
515
+ strikes_full = sorted(list(set((tables['imp_vol_data'][
516
+ 'Strike'].astype(float)))))
517
+
518
+ # create copy of implied vol data
519
+ tables['imp_vol_data_smoothed'] = copy.deepcopy(tables['imp_vol_data'])
520
+
521
+ for ttm, count in mat_dict.items():
522
+
523
+ # if there are less than smoothopt (default is 6) options
524
+ # for a given maturity
525
+ if count < params['smoothopt']:
526
+
527
+ # remove that maturity from the maturities list
528
+ maturities.remove(ttm)
529
+
530
+ # and remove that maturity from the implied vol
531
+ # DataFrame
532
+ tables['imp_vol_data_smoothed'] = tables[
533
+ 'imp_vol_data_smoothed'][
534
+ tables['imp_vol_data_smoothed']['Days'] != ttm]
535
+
536
+ # Create empty DataFrame with the full range of strikes as
537
+ # index
538
+ tables['smooth_surf'] = pd.DataFrame(index=strikes_full)
539
+
540
+ # going through the maturity list (in reverse so the columns
541
+ # created are in increasing order)
542
+ for maturity in reversed(maturities):
543
+
544
+ # Extract the strikes for this maturity
545
+ strikes = tables['imp_vol_data'][tables['imp_vol_data'][
546
+ 'Days']==maturity]['Strike']
547
+
548
+ # And the vols (specifying the voltype)
549
+ vols = tables['imp_vol_data'][tables['imp_vol_data'][
550
+ 'Days']==maturity][str(
551
+ params['vols_dict'][str(params['voltype'])])]
552
+
553
+ # Fit a polynomial to this data
554
+ curve_fit = np.polyfit(strikes, vols, params['order'])
555
+ p = np.poly1d(curve_fit)
556
+
557
+ # Create empty list to store smoothed implied vols
558
+ iv_new = []
559
+
560
+ # For each strike
561
+ for strike in strikes_full:
562
+
563
+ # Add the smoothed value to the iv_new list
564
+ iv_new.append(p(strike))
565
+
566
+ # Append this list as a new column in the smooth_surf
567
+ # DataFrame
568
+ tables['smooth_surf'].insert(0, str(maturity), iv_new)
569
+
570
+ # Apply the _vol_map function to add smoothed vol column to
571
+ # DataFrame
572
+ tables['imp_vol_data_smoothed'] = (
573
+ tables['imp_vol_data_smoothed'].apply(
574
+ lambda x: cls._vol_map(x, tables), axis=1))
575
+
576
+ return params, tables
577
+
578
+
579
+ @staticmethod
580
+ def _vol_map(
581
+ row: pd.Series,
582
+ tables: dict) -> pd.Series:
583
+ """
584
+ Map value calculated in smooth surface DataFrame to
585
+ 'Smoothed Vol' column.
586
+
587
+ Parameters
588
+ ----------
589
+ row : Array
590
+ Each row in the DataFrame.
591
+
592
+ Returns
593
+ -------
594
+ row : Array
595
+ Each row in the DataFrame.
596
+
597
+ """
598
+ row['Smoothed Vol'] = (
599
+ tables['smooth_surf'].loc[row['Strike'], str(row['Days'])])
600
+
601
+ return row
602
+
603
+
604
+ @classmethod
605
+ def map_vols(
606
+ cls,
607
+ params: dict,
608
+ tables: dict) -> tuple[inter._rbf.Rbf, inter._rbf.Rbf]:
609
+ """
610
+ Create vol surface mapping function
611
+
612
+ Parameters
613
+ ----------
614
+ tables : Dict
615
+ Dictionary containing the market data tables.
616
+
617
+ Returns
618
+ -------
619
+ vol_surface : scipy.interpolate.rbf.Rbf
620
+ Vol surface interpolation function.
621
+
622
+ """
623
+ params, tables = cls.smooth(params=params, tables=tables)
624
+ data = tables['imp_vol_data_smoothed']
625
+ t_vols_smooth = data['Smoothed Vol'] * 100
626
+ t_vols = data['Imp Vol - Last'] * 100
627
+ t_strikes = data['Strike']
628
+ t_ttm = data['TTM'] * 365
629
+ vol_surface = sp.interpolate.Rbf(
630
+ t_strikes,
631
+ t_ttm,
632
+ t_vols,
633
+ function=params['rbffunc'],
634
+ smooth=5,
635
+ epsilon=5)
636
+
637
+ vol_surface_smoothed = sp.interpolate.Rbf(
638
+ t_strikes,
639
+ t_ttm,
640
+ t_vols_smooth,
641
+ function=params['rbffunc'],
642
+ smooth=5,
643
+ epsilon=5)
644
+
645
+ return vol_surface, vol_surface_smoothed
646
+
647
+
648
+ @staticmethod
649
+ def get_vol(
650
+ maturity: str,
651
+ strike: int,
652
+ params: dict,
653
+ surface_models: dict) -> float:
654
+ """
655
+ Return implied vol for a given maturity and strike
656
+
657
+ Parameters
658
+ ----------
659
+ maturity : Str
660
+ The date for the option maturity, expressed as 'YYYY-MM-DD'.
661
+ strike : Int
662
+ The strike expressed as a percent, where ATM = 100.
663
+
664
+ Returns
665
+ -------
666
+ imp_vol : Float
667
+ The implied volatility.
668
+
669
+ """
670
+ strike_level = params['spot'] * strike / 100
671
+ maturity_date = dt.datetime.strptime(maturity, '%Y-%m-%d')
672
+ start_date = dt.datetime.strptime(params['start_date'], '%Y-%m-%d')
673
+ ttm = (maturity_date - start_date).days
674
+ if params['smoothing']:
675
+ imp_vol = surface_models[
676
+ 'vol_surface_smoothed'](strike_level, ttm)
677
+ else:
678
+ imp_vol = surface_models['vol_surface'](strike_level, ttm)
679
+
680
+ return np.round(imp_vol, 2)
681
+
682
+
683
+ @classmethod
684
+ def create_vol_dict(
685
+ cls,
686
+ params: dict,
687
+ surface_models: dict) -> dict:
688
+ """
689
+ Create dictionary of implied vols by tenor and strike to use in skew
690
+ report
691
+
692
+ Parameters
693
+ ----------
694
+ params : Dict
695
+ Dictionary of key parameters.
696
+ surface_models : Dict
697
+ Dictionary of vol surfaces.
698
+
699
+ Returns
700
+ -------
701
+ vol_dict : Dict
702
+ Dictionary of implied vols.
703
+
704
+ """
705
+ vol_dict = {}
706
+ start_date = dt.datetime.strptime(params['start_date'], '%Y-%m-%d')
707
+ for month in range(1, params['skew_months']+1):
708
+ for strike in [80, 90, 100, 110, 120]:
709
+ maturity = dt.datetime.strftime(
710
+ start_date + relativedelta(months=month), '%Y-%m-%d')
711
+ vol_dict[(month, strike)] = cls.get_vol(
712
+ maturity=maturity, strike=strike, params=params,
713
+ surface_models=surface_models)
714
+
715
+ return vol_dict
716
+
717
+
718
+ @classmethod
719
+ def print_skew_report(
720
+ cls,
721
+ vol_dict: dict,
722
+ params: dict) -> None:
723
+ """
724
+ Print a report showing implied vols for 80%, 90% and ATM strikes and
725
+ selected tenor length
726
+
727
+ Parameters
728
+ ----------
729
+ vol_dict : Dict
730
+ Dictionary of implied vols.
731
+ params : Dict
732
+ Dictionary of key parameters.
733
+
734
+ Returns
735
+ -------
736
+ Prints the report to the console.
737
+
738
+ """
739
+ # Set decimal format
740
+ dp2 = Decimal(10) ** -2 # (equivalent to Decimal '0.01')
741
+
742
+ if params['skew_direction'] == 'full':
743
+ cls._full_skew(vol_dict=vol_dict, params=params, dp2=dp2)
744
+ else:
745
+ cls._header(params=params)
746
+
747
+ if params['skew_direction'] == 'up':
748
+ cls._upside_skew(vol_dict=vol_dict, params=params, dp2=dp2)
749
+
750
+ else:
751
+ cls._downside_skew(vol_dict=vol_dict, params=params, dp2=dp2)
752
+
753
+
754
+ @staticmethod
755
+ def _header(params: dict) -> None:
756
+
757
+ print('='*78)
758
+ print(': {:^74} :'.format('Skew Summary'))
759
+ print('-'*78)
760
+
761
+ # Contract traded on left and period covered on right
762
+ print(': Underlying Ticker : {:<19}{} : {} :'.format(
763
+ params['ticker_label'],
764
+ 'Close of Business Date',
765
+ params['start_date']))
766
+ print('-'*78)
767
+
768
+ # Strike and skew headers
769
+ print(': {:^12} :{:^34} : {:^23} :'.format(
770
+ 'Maturity',
771
+ 'Strike',
772
+ 'Skew'))
773
+ print('-'*78)
774
+
775
+ if params['skew_direction'] == 'up':
776
+
777
+ print(': {:>15}{:>7} : {:>7} : {:>7} : {:>10}'\
778
+ ' : {:>10} :'.format(
779
+ ': ',
780
+ 'ATM',
781
+ '110%',
782
+ '120%',
783
+ '+10% Skew',
784
+ '+20% Skew'))
785
+
786
+ if params['skew_direction'] == 'down':
787
+ print(': {:>15}{:>7} : {:>7} : {:>7} : {:>10}'\
788
+ ' : {:>10} :'.format(
789
+ ': ',
790
+ '80%',
791
+ '90%',
792
+ 'ATM',
793
+ '-10% Skew',
794
+ '-20% Skew'))
795
+
796
+
797
+ @staticmethod
798
+ def _downside_skew(
799
+ vol_dict: dict,
800
+ params: dict,
801
+ dp2: Decimal) -> None:
802
+
803
+ # Monthly skew summary for selected number of months
804
+ for month in range(1, params['skew_months'] + 1):
805
+ if month < 10:
806
+ month_label = ' '+str(month)
807
+ else:
808
+ month_label = str(month)
809
+ print(': {} Month Vol : {:>7} : {:>7} : {:>7} : {:>7}'\
810
+ ' : {:>7} :'.format(
811
+ month_label,
812
+ Decimal(vol_dict[(month, 80)]).quantize(dp2),
813
+ Decimal(vol_dict[(month, 90)]).quantize(dp2),
814
+ Decimal(vol_dict[(month, 100)]).quantize(dp2),
815
+ Decimal((vol_dict[(month, 90)]
816
+ - vol_dict[(month, 100)]) / 10).quantize(dp2),
817
+ Decimal((vol_dict[(month, 80)]
818
+ - vol_dict[(month, 100)]) / 20).quantize(dp2)))
819
+
820
+ print('-'*78)
821
+ print('='*78)
822
+
823
+
824
+ @staticmethod
825
+ def _upside_skew(
826
+ vol_dict: dict,
827
+ params: dict,
828
+ dp2: Decimal) -> None:
829
+
830
+ # Monthly skew summary for selected number of months
831
+ for month in range(1, params['skew_months'] + 1):
832
+ if month < 10:
833
+ month_label = ' '+str(month)
834
+ else:
835
+ month_label = str(month)
836
+ print(': {} Month Vol : {:>7} : {:>7} : {:>7} : {:>7}'\
837
+ ' : {:>7} :'.format(
838
+ month_label,
839
+ Decimal(vol_dict[(month, 100)]).quantize(dp2),
840
+ Decimal(vol_dict[(month, 110)]).quantize(dp2),
841
+ Decimal(vol_dict[(month, 120)]).quantize(dp2),
842
+ Decimal((vol_dict[(month, 110)]
843
+ - vol_dict[(month, 100)]) / 10).quantize(dp2),
844
+ Decimal((vol_dict[(month, 120)]
845
+ - vol_dict[(month, 100)]) / 20).quantize(dp2)))
846
+
847
+ print('-'*78)
848
+ print('='*78)
849
+
850
+
851
+ @staticmethod
852
+ def _full_skew(
853
+ vol_dict: dict,
854
+ params: dict,
855
+ dp2: Decimal) -> None:
856
+
857
+ print('='*115)
858
+ print(': {:^111} :'.format('Skew Summary'))
859
+ print('-'*115)
860
+
861
+ # Contract traded on left and period covered on right
862
+ print(': Underlying Ticker : {:<56}{} : {} :'.format(
863
+ params['ticker_label'],
864
+ 'Close of Business Date',
865
+ params['start_date']))
866
+ print('-'*115)
867
+
868
+ # Strike and skew headers
869
+ print(': {:^13} : {:^47} : {:^45} :'.format(
870
+ 'Maturity',
871
+ 'Strike',
872
+ 'Skew'))
873
+ print('-'*115)
874
+
875
+ # Header rows
876
+ print(': {:>16}{:>6} : {:>6} : {:>6} : {:>6} : {:>6} : {:>9}'\
877
+ ' : {:>9} : {:>9} : {:>9} :'.format(
878
+ ': ',
879
+ '80%',
880
+ '90%',
881
+ 'ATM',
882
+ '110%',
883
+ '120%',
884
+ '-20% Skew',
885
+ '-10% Skew',
886
+ '+10% Skew',
887
+ '+20% Skew'))
888
+
889
+ # Set decimal format
890
+ dp2 = Decimal(10) ** -2 # (equivalent to Decimal '0.01')
891
+
892
+ # Monthly skew summary for selected number of months
893
+ for month in range(1, params['skew_months'] + 1):
894
+ if month < 10:
895
+ month_label = ' '+str(month)
896
+ else:
897
+ month_label = str(month)
898
+ print(': {} Month Vol : {:>6} : {:>6} : {:>6} : {:>6} : '\
899
+ '{:>6} : {:>7} : {:>7} : {:>7} : {:>7} :'.format(
900
+ month_label,
901
+ Decimal(vol_dict[(month, 80)]).quantize(dp2),
902
+ Decimal(vol_dict[(month, 90)]).quantize(dp2),
903
+ Decimal(vol_dict[(month, 100)]).quantize(dp2),
904
+ Decimal(vol_dict[(month, 110)]).quantize(dp2),
905
+ Decimal(vol_dict[(month, 120)]).quantize(dp2),
906
+ Decimal((vol_dict[(month, 80)]
907
+ - vol_dict[(month, 100)]) / 20).quantize(dp2),
908
+ Decimal((vol_dict[(month, 90)]
909
+ - vol_dict[(month, 100)]) / 10).quantize(dp2),
910
+ Decimal((vol_dict[(month, 110)]
911
+ - vol_dict[(month, 100)]) / 10).quantize(dp2),
912
+ Decimal((vol_dict[(month, 120)]
913
+ - vol_dict[(month, 100)]) / 20).quantize(dp2)))
914
+
915
+ print('-'*115)
916
+ print('='*115)