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.
volvisdata/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.0.1"
@@ -0,0 +1,515 @@
1
+ """
2
+ Methods for graphing volatility data
3
+
4
+ """
5
+ import copy
6
+ import os
7
+ import warnings
8
+ import numpy as np
9
+ import scipy as sp
10
+ from scipy.interpolate import griddata
11
+ from volvisdata.vol_methods import VolMethods
12
+ # pylint: disable=invalid-name, consider-using-f-string
13
+
14
+ class GraphData():
15
+ """
16
+ Methods for graphing volatility data
17
+
18
+ """
19
+ @classmethod
20
+ def line_graph(
21
+ cls,
22
+ params: dict,
23
+ tables: dict) -> dict:
24
+ """
25
+ Returns data for plotting a linegraph of each option maturity plotted by strike
26
+ and implied vol
27
+
28
+ Parameters
29
+ ----------
30
+ voltype : Str
31
+ Whether to use 'bid', 'mid', 'ask' or 'last' price. The
32
+ default is 'last'.
33
+
34
+ Returns
35
+ -------
36
+ data_dict : Dict
37
+ Dictionary of linegraph data
38
+
39
+ """
40
+ # Create a sorted list of the different number of option
41
+ # expiries
42
+ dates = sorted(list(set(tables['imp_vol_data']['Expiry'])))
43
+
44
+ # Create a sorted list of the different number of option time
45
+ # to maturity
46
+ tenors = sorted(list(set(tables['imp_vol_data']['TTM'])))
47
+
48
+ # Combine these in a dictionary
49
+ tenor_date_dict = dict(zip(dates, tenors))
50
+
51
+ opt_dict = {}
52
+ opt_dict['tenors'] = []
53
+ # For each expiry date
54
+ for exp_date, tenor in tenor_date_dict.items():
55
+ # Create a dictionary of strikes, vols & label
56
+ data = {}
57
+ data['strikes'] = np.array(tables['imp_vol_data'][
58
+ tables['imp_vol_data']['TTM']==tenor]['Strike'])
59
+ data['vols'] = np.array(tables['imp_vol_data'][
60
+ tables['imp_vol_data']['TTM']==tenor][str(
61
+ params['vols_dict'][str(params['voltype'])])] * 100)
62
+ data['label'] = str(exp_date)+' Expiry'
63
+
64
+ # Append this to the array of tenors
65
+ opt_dict['tenors'].append(data)
66
+
67
+ opt_dict = cls._create_opt_labels(
68
+ params=params,
69
+ opt_dict=opt_dict,
70
+ output='line'
71
+ )
72
+
73
+ data_dict = {
74
+ 'params': params,
75
+ 'tables': tables,
76
+ 'opt_dict': opt_dict
77
+ }
78
+
79
+ return data_dict
80
+
81
+
82
+ @classmethod
83
+ def scatter_3d(
84
+ cls,
85
+ params: dict,
86
+ tables: dict) -> dict:
87
+ """
88
+ Returns data for plotting a 3D scatter plot of each option implied vol against strike and maturity
89
+
90
+ Parameters
91
+ ----------
92
+ voltype : Str
93
+ Whether to use 'bid', 'mid', 'ask' or 'last' price. The
94
+ default is 'last'.
95
+ azim : Float
96
+ L-R view angle for 3D graphs. The default is -50.
97
+ elev : Float
98
+ Elevation view angle for 3D graphs. The default is 20.
99
+
100
+ Returns
101
+ -------
102
+ data_dict : Dict
103
+ Dictionary of 3D Scatter plot data.
104
+
105
+ """
106
+ # Create dictionary to store option data
107
+ opt_dict = {}
108
+
109
+ # Create figure and axis objects and format
110
+ opt_dict = cls._create_opt_labels(
111
+ params=params,
112
+ opt_dict=opt_dict,
113
+ output='mpl'
114
+ )
115
+
116
+ # Create copy of data
117
+ tables['data_3D'] = copy.deepcopy(tables['imp_vol_data'])
118
+
119
+ # Filter out any zero prices
120
+ tables['data_3D'] = tables['data_3D'][tables['data_3D'][str(
121
+ params['prices_dict'][str(params['voltype'])])] != 0]
122
+
123
+ # Specify the 3 axis values
124
+ opt_dict['strikes'] = np.array(tables['data_3D']['Strike'])
125
+ opt_dict['ttms'] = np.array(tables['data_3D']['TTM'] * 365)
126
+ opt_dict['vols'] = np.array(tables['data_3D'][str(params['vols_dict'][str(
127
+ params['voltype'])])] * 100)
128
+
129
+ data_dict = {
130
+ 'params': params,
131
+ 'tables': tables,
132
+ 'opt_dict': opt_dict
133
+ }
134
+
135
+ return data_dict
136
+
137
+
138
+ @classmethod
139
+ def surface_3d(
140
+ cls,
141
+ params: dict,
142
+ tables: dict) -> dict:
143
+ """
144
+ Returns data for plotting a 3D surface plot of the implied vol surface against strike and maturity
145
+
146
+ Parameters
147
+ ----------
148
+ surfacetype : Str
149
+ The type of 3D surface to display from 'trisurf', 'mesh',
150
+ 'spline', 'interactive_mesh' and 'interactive_spline'.
151
+ The default is 'mesh'.
152
+ smoothing : Bool
153
+ Whether to apply polynomial smoothing. The default is False.
154
+ scatter : Bool
155
+ Whether to plot scatter points on 3D mesh grid. The default
156
+ is False.
157
+ voltype : Str
158
+ Whether to use 'bid', 'mid', 'ask' or 'last' price. The
159
+ default is 'last'.
160
+ order : Int
161
+ Polynomial order used in numpy polyfit function. The
162
+ default is 3.
163
+ spacegrain : Int
164
+ Number of points in each axis linspace argument for 3D
165
+ graphs. The default
166
+ is 100.
167
+ azim : Float
168
+ L-R view angle for 3D graphs. The default is -50.
169
+ elev : Float
170
+ Elevation view angle for 3D graphs. The default is 20.
171
+ rbffunc : Str
172
+ Radial basis function used in interpolation chosen from
173
+ 'multiquadric', 'inverse', 'gaussian', 'linear', 'cubic',
174
+ 'quintic', 'thin_plate'. The default is 'thin_plate'
175
+ colorscale : Str
176
+ Colors used in plotly interactive graph. The default is
177
+ 'BlueRed'
178
+ opacity : Float
179
+ opacity of 3D interactive graph
180
+ surf : Bool
181
+ Plot surface in interactive graph
182
+ notebook : Bool
183
+ Whether interactive graph is run in Jupyter notebook or IDE.
184
+ The default is False.
185
+ save_image : Bool
186
+ Whether to save a copy of the image as a png file. The default is
187
+ False
188
+ image_folder : Str
189
+ Location to save any images. The default is 'images'
190
+ image_dpi : Int
191
+ Resolution to save images. The default is 50.
192
+
193
+ Returns
194
+ -------
195
+ data_dict : Dict
196
+ Dictionary of 3D surface plot data.
197
+
198
+ """
199
+
200
+ # Suppress mpl user warning about data containing nan values
201
+ warnings.filterwarnings(
202
+ "ignore", category=UserWarning, message='Z contains NaN values. '\
203
+ 'This may result in rendering artifacts.')
204
+
205
+ opt_dict = {}
206
+
207
+ # If smoothing is set to False
208
+ if params['smoothing'] is False:
209
+
210
+ # Create copy of implied vol data
211
+ tables['data_3D'] = copy.deepcopy(tables['imp_vol_data'])
212
+
213
+ # Filter out any zero prices
214
+ tables['data_3D'] = tables['data_3D'][tables['data_3D'][str(
215
+ params['prices_dict'][str(params['voltype'])])] != 0]
216
+
217
+ # Set 'graph vol' to be the specified voltype
218
+ tables['data_3D']['Graph Vol'] = tables['data_3D'][str(
219
+ params['vols_dict'][str(params['voltype'])])]
220
+
221
+ # Otherwise, if smoothing is set to True
222
+ else:
223
+ # Apply the smoothing function to the specified voltype
224
+ params, tables = VolMethods.smooth(params=params, tables=tables)
225
+
226
+ # Create copy of implied vol data
227
+ tables['data_3D'] = copy.deepcopy(tables['imp_vol_data_smoothed'])
228
+
229
+ # Filter out any zero prices
230
+ tables['data_3D'] = tables['data_3D'][tables['data_3D'][str(
231
+ params['prices_dict'][str(params['voltype'])])] != 0]
232
+
233
+ # Set 'graph vol' to be the smoothed vol
234
+ tables['data_3D']['Graph Vol'] = tables['data_3D']['Smoothed Vol']
235
+
236
+ # Specify the 3 axis values
237
+ params['x'] = tables['data_3D']['Strike']
238
+ params['y'] = tables['data_3D']['TTM'] * 365
239
+ params['z'] = tables['data_3D']['Graph Vol'] * 100
240
+
241
+ if params['surfacetype'] == 'trisurf':
242
+ opt_dict = cls._trisurf_graph(params=params, opt_dict=opt_dict)
243
+
244
+ elif params['surfacetype'] == 'mesh':
245
+ opt_dict = cls._mesh_graph(params=params, opt_dict=opt_dict)
246
+
247
+ elif params['surfacetype'] == 'spline':
248
+ opt_dict = cls._spline_graph(params=params, tables=tables, opt_dict=opt_dict)
249
+
250
+ elif params['surfacetype'] in [
251
+ 'interactive_mesh',
252
+ 'interactive_spline']:
253
+ opt_dict = cls._interactive_graph(params=params, tables=tables, opt_dict=opt_dict)
254
+
255
+ else:
256
+ print("Enter a valid surfacetype from 'trisurf', 'mesh', "\
257
+ "'spline', 'interactive_mesh', 'interactive_spline'")
258
+
259
+ # Set warnings back to default
260
+ warnings.filterwarnings("default", category=UserWarning)
261
+
262
+ data_dict = {
263
+ 'params': params,
264
+ 'tables': tables,
265
+ 'opt_dict': opt_dict
266
+ }
267
+
268
+ return data_dict
269
+
270
+
271
+ @classmethod
272
+ def _trisurf_graph(
273
+ cls,
274
+ params: dict,
275
+ opt_dict: dict) -> dict:
276
+
277
+ # Create figure and axis objects and format
278
+ opt_dict = cls._create_opt_labels(
279
+ params=params,
280
+ opt_dict=opt_dict,
281
+ output='mpl'
282
+ )
283
+
284
+ opt_dict['strikes'] = np.array(params['x'])
285
+ opt_dict['ttms'] = np.array(params['y'])
286
+ opt_dict['vols'] = np.array(params['z'])
287
+
288
+ return opt_dict
289
+
290
+
291
+ @classmethod
292
+ def _mesh_graph(
293
+ cls,
294
+ params: dict,
295
+ opt_dict: dict) -> dict:
296
+
297
+ # Create arrays across x and y-axes of equally spaced points
298
+ # from min to max values
299
+ x1, y1 = np.meshgrid(
300
+ np.linspace(min(params['x']),
301
+ max(params['x']),
302
+ int(params['spacegrain'])),
303
+ np.linspace(min(params['y']),
304
+ max(params['y']),
305
+ int(params['spacegrain'])))
306
+
307
+ # Map the z-axis with the scipy griddata method, applying
308
+ # cubic spline interpolation
309
+ z1 = griddata(np.array([params['x'],params['y']]).T,
310
+ np.array(params['z']),
311
+ (x1,y1),
312
+ method='cubic')
313
+
314
+ # Create figure and axis objects and format
315
+ opt_dict = cls._create_opt_labels(
316
+ params=params,
317
+ opt_dict=opt_dict,
318
+ output='mpl'
319
+ )
320
+
321
+ opt_dict['strikes_array'] = x1
322
+ opt_dict['ttms_array'] = y1
323
+ opt_dict['vol_surface'] = z1
324
+
325
+ return opt_dict
326
+
327
+
328
+ @classmethod
329
+ def _spline_graph(
330
+ cls,
331
+ params: dict,
332
+ tables: dict,
333
+ opt_dict: dict) -> dict:
334
+
335
+ # Create arrays across x and y-axes of equally spaced points
336
+ # from min to max values
337
+ x1 = np.linspace(min(params['x']),
338
+ max(params['x']),
339
+ int(params['spacegrain']))
340
+ y1 = np.linspace(min(params['y']),
341
+ max(params['y']),
342
+ int(params['spacegrain']))
343
+ x2, y2 = np.meshgrid(x1, y1, indexing='xy')
344
+
345
+ # Initialize the z-axis as an array of zero values
346
+ z2 = np.zeros((params['x'].size, params['z'].size))
347
+
348
+ # Apply scipy interpolate radial basis function, choosing
349
+ # the rbffunc parameter
350
+ spline = sp.interpolate.Rbf(
351
+ params['x'],
352
+ params['y'],
353
+ params['z'],
354
+ function=params['rbffunc'],
355
+ smooth=5,
356
+ epsilon=5)
357
+
358
+ # Populate z-axis array using this function
359
+ z2 = spline(x2, y2)
360
+
361
+ # Create figure and axis objects and format
362
+ opt_dict = cls._create_opt_labels(
363
+ params=params,
364
+ opt_dict=opt_dict,
365
+ output='mpl'
366
+ )
367
+
368
+ opt_dict['strikes'] = np.array(params['x'])
369
+ opt_dict['ttms'] = np.array(params['y'])
370
+ opt_dict['vols'] = np.array(params['z'])
371
+ opt_dict['strikes_linspace'] = x1
372
+ opt_dict['ttms_linspace'] = y1
373
+ opt_dict['strikes_linspace_array'] = x2
374
+ opt_dict['ttms_linspace_array'] = y2
375
+ opt_dict['vol_surface'] = z2
376
+
377
+ return opt_dict
378
+
379
+
380
+ @classmethod
381
+ def _interactive_graph(
382
+ cls,
383
+ params: dict,
384
+ tables: dict,
385
+ opt_dict: dict) -> dict:
386
+
387
+ params = cls._set_contours(params=params, tables=tables)
388
+
389
+ # Specify the 3 axis values
390
+ params['x'] = tables['data_3D']['TTM'] * 365
391
+ params['y'] = tables['data_3D']['Strike']
392
+ params['z'] = tables['data_3D']['Graph Vol'] * 100
393
+
394
+ # Create arrays across x and y-axes of equally spaced
395
+ # points from min to max values
396
+ x1 = np.linspace(
397
+ params['x'].min(),
398
+ params['x'].max(),
399
+ int(params['spacegrain'])
400
+ )
401
+ y1 = np.linspace(
402
+ params['y'].min(),
403
+ params['y'].max(),
404
+ int(params['spacegrain'])
405
+ )
406
+ params['x2'], params['y2'] = np.meshgrid(x1, y1, indexing='xy')
407
+
408
+ # If surfacetype is 'interactive_mesh', map the z-axis with
409
+ # the scipy griddata method, applying cubic spline
410
+ # interpolation
411
+ if params['surfacetype'] == 'interactive_mesh':
412
+ params['z2'] = griddata((params['x'], params['y']),
413
+ params['z'],
414
+ (params['x2'], params['y2']),
415
+ method='cubic')
416
+
417
+ # If surfacetype is 'interactive_spline', apply scipy
418
+ # interpolate radial basis function, choosing the rbffunc
419
+ # parameter
420
+ if params['surfacetype'] == 'interactive_spline':
421
+ params['z2'] = np.zeros((params['x'].size, params['z'].size))
422
+ spline = sp.interpolate.Rbf(
423
+ params['x'],
424
+ params['y'],
425
+ params['z'],
426
+ function=params['rbffunc'],
427
+ smooth=5,
428
+ epsilon=5)
429
+ params['z2'] = spline(params['x2'], params['y2'])
430
+
431
+ opt_dict = cls._create_opt_labels(
432
+ params=params,
433
+ opt_dict=opt_dict,
434
+ output='plotly')
435
+
436
+ opt_dict['strikes'] = np.array(tables['data_3D']['Strike'])
437
+ opt_dict['ttms'] = np.array(tables['data_3D']['TTM'] * 365)
438
+ opt_dict['vols'] = np.array(tables['data_3D']['Graph Vol'] * 100)
439
+ opt_dict['ttms_linspace'] = x1
440
+ opt_dict['strikes_linspace'] = y1
441
+ opt_dict['ttms_linspace_array'] = params['x2']
442
+ opt_dict['strikes_linspace_array'] = params['y2']
443
+ opt_dict['vol_surface'] = params['z2']
444
+
445
+ return opt_dict
446
+
447
+
448
+ @staticmethod
449
+ def _set_contours(
450
+ params: dict,
451
+ tables: dict) -> dict:
452
+
453
+ # Set the range of x, y and z contours and interval
454
+ params['contour_x_start'] = 0
455
+ params['contour_x_stop'] = 2 * 360
456
+ params['contour_x_size'] = params['contour_x_stop'] / 18
457
+ params['contour_y_start'] = tables['data_3D']['Strike'].min()
458
+ params['contour_y_stop'] = tables['data_3D']['Strike'].max()
459
+
460
+ # Vary the strike interval based on spot level
461
+ if ((tables['data_3D']['Strike'].max()
462
+ - tables['data_3D']['Strike'].min()) > 2000):
463
+ params['contour_y_size'] = 200
464
+ elif ((tables['data_3D']['Strike'].max()
465
+ - tables['data_3D']['Strike'].min()) > 1000):
466
+ params['contour_y_size'] = 100
467
+ elif ((tables['data_3D']['Strike'].max()
468
+ - tables['data_3D']['Strike'].min()) > 250):
469
+ params['contour_y_size'] = 50
470
+ elif ((tables['data_3D']['Strike'].max()
471
+ - tables['data_3D']['Strike'].min()) > 50):
472
+ params['contour_y_size'] = 10
473
+ else:
474
+ params['contour_y_size'] = 5
475
+
476
+ # Set z contours
477
+ params['contour_z_start'] = 0
478
+ params['contour_z_stop'] = 100
479
+ params['contour_z_size'] = 5
480
+
481
+ return params
482
+
483
+
484
+ @staticmethod
485
+ def _create_opt_labels(
486
+ params: dict,
487
+ opt_dict: dict,
488
+ output: str) -> dict:
489
+
490
+ if output == 'mpl':
491
+ # Add labels to option dictionary
492
+ opt_dict['x_label'] = 'Strike'
493
+ opt_dict['y_label'] = 'Time to Expiration (Days)'
494
+ opt_dict['z_label'] = 'Implied Volatility %'
495
+
496
+
497
+ elif output == 'line':
498
+ opt_dict['x_label'] = 'Strike'
499
+ opt_dict['y_label'] = 'Implied Volatility %'
500
+ opt_dict['legend_title'] = 'Option Expiry'
501
+
502
+ else:
503
+ opt_dict['x_label'] = 'Time to Expiration (Days)'
504
+ opt_dict['y_label'] = 'Strike'
505
+ opt_dict['z_label'] = 'Implied Volatility %'
506
+
507
+ opt_dict['title'] = (
508
+ str(params['ticker_label'])
509
+ +' Implied Volatility '
510
+ +str(params['voltype'].title())
511
+ +' Price '
512
+ +str(params['start_date'])
513
+ )
514
+
515
+ return opt_dict