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 +1 -0
- volvisdata/graph_data.py +515 -0
- volvisdata/market_data.py +501 -0
- volvisdata/market_data_prep.py +857 -0
- volvisdata/utils.py +119 -0
- volvisdata/vol_methods.py +916 -0
- volvisdata/volatility.py +547 -0
- volvisdata/volatility_params.py +139 -0
- volvisdata-1.0.1.dist-info/LICENSE +21 -0
- volvisdata-1.0.1.dist-info/METADATA +36 -0
- volvisdata-1.0.1.dist-info/RECORD +13 -0
- volvisdata-1.0.1.dist-info/WHEEL +5 -0
- volvisdata-1.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Market data transformation and combination functions
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
import calendar
|
|
6
|
+
from collections import Counter
|
|
7
|
+
import copy
|
|
8
|
+
import datetime as dt
|
|
9
|
+
from datetime import date, timedelta
|
|
10
|
+
import random
|
|
11
|
+
import warnings
|
|
12
|
+
from bs4 import BeautifulSoup
|
|
13
|
+
from lxml import html
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
import pytz
|
|
17
|
+
import requests
|
|
18
|
+
from scipy import interpolate
|
|
19
|
+
from volvisdata.vol_methods import ImpliedVol
|
|
20
|
+
from volvisdata.volatility_params import USER_AGENTS
|
|
21
|
+
|
|
22
|
+
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
|
23
|
+
# pylint: disable=invalid-name
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class UrlOpener:
|
|
27
|
+
"""
|
|
28
|
+
Extract data from Yahoo Finance URL
|
|
29
|
+
|
|
30
|
+
"""
|
|
31
|
+
request_headers = {
|
|
32
|
+
"accept": "*/*",
|
|
33
|
+
"accept-encoding": "gzip, deflate, br",
|
|
34
|
+
"accept-language": "en-US,en;q=0.9",
|
|
35
|
+
"origin": "https://finance.yahoo.com",
|
|
36
|
+
"referer": "https://finance.yahoo.com",
|
|
37
|
+
"sec-fetch-dest": "empty",
|
|
38
|
+
"sec-fetch-mode": "cors",
|
|
39
|
+
"sec-fetch-site": "same-site",
|
|
40
|
+
}
|
|
41
|
+
user_agent = random.choice(USER_AGENTS)
|
|
42
|
+
request_headers["User-Agent"] = user_agent
|
|
43
|
+
|
|
44
|
+
def __init__(self):
|
|
45
|
+
self._session = requests
|
|
46
|
+
|
|
47
|
+
def open(self, url: str) -> requests.models.Response:
|
|
48
|
+
"""
|
|
49
|
+
Extract data from Yahoo Finance URL
|
|
50
|
+
|
|
51
|
+
Parameters
|
|
52
|
+
----------
|
|
53
|
+
url : Str
|
|
54
|
+
The URL to extract data from.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
response : Response object
|
|
59
|
+
Response object of requests module.
|
|
60
|
+
|
|
61
|
+
"""
|
|
62
|
+
response = self._session.get(
|
|
63
|
+
url=url, headers=self.request_headers, timeout=10)
|
|
64
|
+
|
|
65
|
+
return response
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class DataPrep():
|
|
69
|
+
"""
|
|
70
|
+
Market data transformation and combination functions
|
|
71
|
+
|
|
72
|
+
"""
|
|
73
|
+
@classmethod
|
|
74
|
+
def transform(
|
|
75
|
+
cls,
|
|
76
|
+
params: dict,
|
|
77
|
+
tables: dict) -> tuple[dict, dict]:
|
|
78
|
+
"""
|
|
79
|
+
Perform some filtering / transforming of the option data
|
|
80
|
+
|
|
81
|
+
Parameters
|
|
82
|
+
----------
|
|
83
|
+
start_date : Str
|
|
84
|
+
Date from when to include prices (some of the options
|
|
85
|
+
won't have traded for days / weeks and therefore will
|
|
86
|
+
have stale prices).
|
|
87
|
+
lastmins : Int, Optional
|
|
88
|
+
Restrict to trades within number of minutes since last
|
|
89
|
+
trade time recorded
|
|
90
|
+
mindays : Int, Optional
|
|
91
|
+
Restrict to options greater than certain option expiry
|
|
92
|
+
minopts : Int, Optional
|
|
93
|
+
Restrict to minimum number of options to include that
|
|
94
|
+
option expiry
|
|
95
|
+
volume : Int, Optional
|
|
96
|
+
Restrict to minimum Volume
|
|
97
|
+
openint : Int, Optional
|
|
98
|
+
Restrict to minimum Open Interest
|
|
99
|
+
monthlies : Bool
|
|
100
|
+
Restrict expiries to only 3rd Friday of the month. Default
|
|
101
|
+
is False.
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
DataFrame
|
|
106
|
+
Creates a new DataFrame as a modification of 'full_data'.
|
|
107
|
+
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
# Make a copy of 'full_data'
|
|
111
|
+
tables['data'] = copy.deepcopy(tables['full_data'])
|
|
112
|
+
|
|
113
|
+
# Set timezone
|
|
114
|
+
est = pytz.timezone('US/Eastern')
|
|
115
|
+
|
|
116
|
+
# Convert 'Last Trade Date' to a DateTime variable
|
|
117
|
+
tables['data']['Last Trade Date Raw'] = (
|
|
118
|
+
tables['data']['Last Trade Date'])
|
|
119
|
+
|
|
120
|
+
# Format date based on Eastern Daylight or Standard Time
|
|
121
|
+
# try:
|
|
122
|
+
# tables['data']['Last Trade Date'] = pd.to_datetime(
|
|
123
|
+
# tables['data']['Last Trade Date'],
|
|
124
|
+
# format='%Y-%m-%d %I:%M%p EDT')
|
|
125
|
+
|
|
126
|
+
# except ValueError:
|
|
127
|
+
# try:
|
|
128
|
+
# tables['data']['Last Trade Date'] = pd.to_datetime(
|
|
129
|
+
# tables['data']['Last Trade Date'],
|
|
130
|
+
# format='%Y-%m-%d %I:%M%p EST')
|
|
131
|
+
# except:
|
|
132
|
+
tables['data']['Last Trade Date'] = pd.to_datetime(
|
|
133
|
+
tables['data']['Last Trade Date'],
|
|
134
|
+
format='%m/%d/%Y %I:%M %p')
|
|
135
|
+
|
|
136
|
+
tables['data']['Last Trade Date'] = (
|
|
137
|
+
tables['data']['Last Trade Date'].apply(
|
|
138
|
+
lambda x: x.replace(tzinfo=est)))
|
|
139
|
+
|
|
140
|
+
# Create columns of expiry date as datetime object and str
|
|
141
|
+
tables['data']['Expiry_datetime'] = pd.to_datetime(
|
|
142
|
+
tables['data']['Expiry'], format='%Y-%m-%d')
|
|
143
|
+
tables['data']['Expiry_str'] = (
|
|
144
|
+
tables['data']['Expiry_datetime'].dt.strftime('%Y-%m-%d'))
|
|
145
|
+
|
|
146
|
+
# Filter data from start date
|
|
147
|
+
tables['data'] = (
|
|
148
|
+
tables['data'][tables['data']['Last Trade Date']>=str(
|
|
149
|
+
pd.to_datetime(params['start_date']))])
|
|
150
|
+
|
|
151
|
+
tables = cls._trade_columns(tables=tables)
|
|
152
|
+
|
|
153
|
+
# Create Time To Maturity (in years) column
|
|
154
|
+
tables['data']['TTM'] = (
|
|
155
|
+
pd.to_datetime(tables['data']['Expiry'])
|
|
156
|
+
- pd.to_datetime(date.today())) / (pd.Timedelta(days=1) * 365)
|
|
157
|
+
|
|
158
|
+
# Create Days to Maturity column
|
|
159
|
+
tables['data']['Days'] = np.round(tables['data']['TTM']*365, 0)
|
|
160
|
+
|
|
161
|
+
# Remove Zero Maturities
|
|
162
|
+
tables['data'] = tables['data'][tables['data']['TTM'] !=0]
|
|
163
|
+
|
|
164
|
+
params, tables = cls._filters(params=params, tables=tables)
|
|
165
|
+
|
|
166
|
+
return params, tables
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@staticmethod
|
|
170
|
+
def _trade_columns(tables: dict) -> dict:
|
|
171
|
+
|
|
172
|
+
# Create a column of the Trade Day
|
|
173
|
+
tables['data']['Last Trade Day'] = (
|
|
174
|
+
tables['data']['Last Trade Date'].dt.date)
|
|
175
|
+
|
|
176
|
+
# Create a column of the Trade Time of Day
|
|
177
|
+
tables['data']['Last Trade Time'] = (
|
|
178
|
+
tables['data']['Last Trade Date'].dt.time)
|
|
179
|
+
|
|
180
|
+
# Create a column of the Trade Hour of Day
|
|
181
|
+
tables['data']['Last Trade Hour'] = (
|
|
182
|
+
tables['data']['Last Trade Date'].dt.hour)
|
|
183
|
+
|
|
184
|
+
# Create a column of the Trade Date represented in unixtime
|
|
185
|
+
tables['data']['Unixtime'] = (
|
|
186
|
+
tables['data']['Last Trade Date'].astype(np.int64) // 10**9)
|
|
187
|
+
|
|
188
|
+
# Clean Volume column
|
|
189
|
+
tables['data']['Volume'] = tables['data']['Volume'].fillna(0)
|
|
190
|
+
tables['data']['Volume'] = (
|
|
191
|
+
tables['data']['Volume'].replace('-',0).astype(int))
|
|
192
|
+
|
|
193
|
+
# Clean Open Interest column
|
|
194
|
+
tables['data']['Open Interest'] = tables['data']['Open Interest'].fillna(0)
|
|
195
|
+
tables['data']['Open Interest'] = (
|
|
196
|
+
tables['data']['Open Interest'].replace('-',0).astype(int))
|
|
197
|
+
|
|
198
|
+
# Clean Ask column
|
|
199
|
+
tables['data']['Ask'] = tables['data']['Ask'].fillna(0)
|
|
200
|
+
tables['data']['Ask'] = (
|
|
201
|
+
tables['data']['Ask'].replace('-',0).astype(float))
|
|
202
|
+
|
|
203
|
+
# Clean Bid column
|
|
204
|
+
tables['data']['Bid'] = tables['data']['Bid'].fillna(0)
|
|
205
|
+
tables['data']['Bid'] = (
|
|
206
|
+
tables['data']['Bid'].replace('-',0).astype(float))
|
|
207
|
+
|
|
208
|
+
# Create Mid column
|
|
209
|
+
tables['data']['Mid'] = (
|
|
210
|
+
tables['data']['Ask'] + tables['data']['Bid']) / 2
|
|
211
|
+
|
|
212
|
+
return tables
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
@classmethod
|
|
216
|
+
def _filters(
|
|
217
|
+
cls,
|
|
218
|
+
params: dict,
|
|
219
|
+
tables: dict) -> tuple[dict, dict]:
|
|
220
|
+
|
|
221
|
+
# If a minutes parameter is supplied, filter for most recent
|
|
222
|
+
# minutes
|
|
223
|
+
if params['lastmins'] is not None:
|
|
224
|
+
tables['data'] = (tables['data'][tables['data']['Unixtime'] >= (
|
|
225
|
+
max(tables['data']['Unixtime']) - params['lastmins'] * 60)])
|
|
226
|
+
|
|
227
|
+
# If a mindays parameter is supplied, filter for option expiry
|
|
228
|
+
# greater than parameter
|
|
229
|
+
if params['mindays'] is not None:
|
|
230
|
+
tables['data'] = (
|
|
231
|
+
tables['data'][tables['data']['Days'] >= params['mindays']])
|
|
232
|
+
|
|
233
|
+
# If a volume parameter is supplied, filter for volume greater
|
|
234
|
+
# than parameter
|
|
235
|
+
if params['volume'] is not None:
|
|
236
|
+
tables['data'] = (
|
|
237
|
+
tables['data'][tables['data']['Volume'] >= params['volume']])
|
|
238
|
+
|
|
239
|
+
# If an openint parameter is supplied, filter for Open Interest
|
|
240
|
+
# greater than parameter
|
|
241
|
+
if params['openint'] is not None:
|
|
242
|
+
tables['data'] = (
|
|
243
|
+
tables['data'][tables['data']['Open Interest']
|
|
244
|
+
>= params['openint']])
|
|
245
|
+
|
|
246
|
+
# If a minopts parameter is supplied, filter for number of options
|
|
247
|
+
# greater than parameter
|
|
248
|
+
if params['minopts'] is not None:
|
|
249
|
+
|
|
250
|
+
tables['data'] = cls._minopts(params=params, data=tables['data'])
|
|
251
|
+
|
|
252
|
+
params, tables = cls._monthlies(params=params, tables=tables)
|
|
253
|
+
|
|
254
|
+
return params, tables
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@staticmethod
|
|
258
|
+
def _minopts(
|
|
259
|
+
params: dict,
|
|
260
|
+
data: pd.DataFrame) -> pd.DataFrame:
|
|
261
|
+
# Create a dictionary of the number of options for each
|
|
262
|
+
# maturity
|
|
263
|
+
mat_dict = dict(Counter(data['Days']))
|
|
264
|
+
for ttm, count in mat_dict.items():
|
|
265
|
+
|
|
266
|
+
# if there are less than minopts options for a given
|
|
267
|
+
# maturity
|
|
268
|
+
if count < params['minopts']:
|
|
269
|
+
|
|
270
|
+
# remove that maturity from the DataFrame
|
|
271
|
+
data = (
|
|
272
|
+
data[data['Days'] != ttm])
|
|
273
|
+
|
|
274
|
+
return data
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@staticmethod
|
|
278
|
+
def _monthlies(
|
|
279
|
+
params: dict,
|
|
280
|
+
tables: dict) -> tuple[dict, dict]:
|
|
281
|
+
|
|
282
|
+
# If the monthlies flag is set
|
|
283
|
+
if params['monthlies'] is True:
|
|
284
|
+
|
|
285
|
+
# Create an empty list
|
|
286
|
+
date_list = []
|
|
287
|
+
|
|
288
|
+
# For each date in the url_dict
|
|
289
|
+
for key in params['date_list']:
|
|
290
|
+
|
|
291
|
+
# Format that string as a datetime object
|
|
292
|
+
key_date = dt.datetime.strptime(key, "%Y-%m-%d")
|
|
293
|
+
|
|
294
|
+
# Store the year and month as a tuple in date_list
|
|
295
|
+
date_list.append((key_date.year, key_date.month))
|
|
296
|
+
|
|
297
|
+
# Create a sorted list from the unique dates in date_list
|
|
298
|
+
sorted_dates = sorted(list(set(date_list)))
|
|
299
|
+
|
|
300
|
+
# Create an empty list
|
|
301
|
+
days_list = []
|
|
302
|
+
|
|
303
|
+
# Create a calendar object
|
|
304
|
+
c = calendar.Calendar(firstweekday=calendar.SATURDAY)
|
|
305
|
+
|
|
306
|
+
# For each tuple of year, month in sorted_dates
|
|
307
|
+
for tup in sorted_dates:
|
|
308
|
+
|
|
309
|
+
# Create a list of lists of days in that month
|
|
310
|
+
monthcal = c.monthdatescalendar(tup[0], tup[1])
|
|
311
|
+
|
|
312
|
+
# Extract the date corresponding to the 3rd Friday
|
|
313
|
+
expiry = monthcal[2][-1]
|
|
314
|
+
|
|
315
|
+
if expiry in params['trade_holidays']:
|
|
316
|
+
expiry = expiry - timedelta(days=1)
|
|
317
|
+
|
|
318
|
+
# Calculate the number of days until that expiry
|
|
319
|
+
ttm = (expiry - dt.date.today()).days
|
|
320
|
+
|
|
321
|
+
# Append this to the days_list
|
|
322
|
+
days_list.append(ttm)
|
|
323
|
+
|
|
324
|
+
# For each unique number of days to expiry
|
|
325
|
+
for days_to_expiry in set(tables['data']['Days']):
|
|
326
|
+
|
|
327
|
+
# if the expiry is not in the list of monthly expiries
|
|
328
|
+
if days_to_expiry not in days_list:
|
|
329
|
+
|
|
330
|
+
# Remove that expiry from the DataFrame
|
|
331
|
+
tables['data'] = (
|
|
332
|
+
tables['data'][tables['data']['Days']
|
|
333
|
+
!= days_to_expiry])
|
|
334
|
+
|
|
335
|
+
return params, tables
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
@classmethod
|
|
339
|
+
def combine(
|
|
340
|
+
cls,
|
|
341
|
+
params: dict,
|
|
342
|
+
tables: dict) -> tuple[dict, dict]:
|
|
343
|
+
"""
|
|
344
|
+
Calculate implied volatilities for specified put and call
|
|
345
|
+
strikes and combine.
|
|
346
|
+
|
|
347
|
+
Parameters
|
|
348
|
+
----------
|
|
349
|
+
ticker_label : Str
|
|
350
|
+
Stock Ticker.
|
|
351
|
+
spot : Float
|
|
352
|
+
Underlying reference level.
|
|
353
|
+
put_strikes : List
|
|
354
|
+
Range of put strikes to calculate implied volatility for.
|
|
355
|
+
call_strikes : List
|
|
356
|
+
Range of call strikes to calculate implied volatility for.
|
|
357
|
+
strike_limit : Tuple
|
|
358
|
+
min and max strikes to use expressed as a decimal
|
|
359
|
+
percentage. The default is (0.5, 2.0).
|
|
360
|
+
divisor : Int
|
|
361
|
+
Distance between each strike in dollars. The default is 25 for SPX
|
|
362
|
+
and 10 otherwise.
|
|
363
|
+
r : Float
|
|
364
|
+
Interest Rate. The default is 0.005.
|
|
365
|
+
q : Float
|
|
366
|
+
Dividend Yield. The default is 0.
|
|
367
|
+
epsilon : Float
|
|
368
|
+
Degree of precision to return implied vol. The default
|
|
369
|
+
is 0.001.
|
|
370
|
+
method : Str
|
|
371
|
+
Implied Vol method; 'nr', 'bisection' or 'naive'. The
|
|
372
|
+
default is 'nr'.
|
|
373
|
+
|
|
374
|
+
Returns
|
|
375
|
+
-------
|
|
376
|
+
DataFrame
|
|
377
|
+
DataFrame of Option prices.
|
|
378
|
+
|
|
379
|
+
"""
|
|
380
|
+
|
|
381
|
+
# create copy of filtered data
|
|
382
|
+
input_data = copy.deepcopy(tables['data'])
|
|
383
|
+
|
|
384
|
+
# Calculate strikes if strikes and spot price are not supplied.
|
|
385
|
+
params = cls._create_strike_range(params=params, tables=tables)
|
|
386
|
+
|
|
387
|
+
# Assign ticker label to the object
|
|
388
|
+
if params['ticker_label'] is None:
|
|
389
|
+
params['ticker_label'] = params['ticker'].lstrip('^')
|
|
390
|
+
|
|
391
|
+
# Create empty list and dictionary for storing options
|
|
392
|
+
params['opt_list'] = []
|
|
393
|
+
opt_dict = {}
|
|
394
|
+
|
|
395
|
+
# For each put strike price
|
|
396
|
+
for strike in params['put_strikes']:
|
|
397
|
+
|
|
398
|
+
# Assign an option name of ticker plus strike
|
|
399
|
+
opt_name = params['ticker_label']+'_'+str(strike)
|
|
400
|
+
|
|
401
|
+
# store the implied vol results for that strike in the
|
|
402
|
+
# option dictionary
|
|
403
|
+
opt_dict[opt_name] = cls._imp_vol_apply(
|
|
404
|
+
params=params, input_data=input_data, strike=strike,
|
|
405
|
+
option='put')
|
|
406
|
+
|
|
407
|
+
# store the implied vol results for that strike in the
|
|
408
|
+
# option list
|
|
409
|
+
params['opt_list'].append(opt_dict[opt_name])
|
|
410
|
+
|
|
411
|
+
print('Put option: ', opt_name)
|
|
412
|
+
|
|
413
|
+
# For each put strike price
|
|
414
|
+
for strike in params['call_strikes']:
|
|
415
|
+
|
|
416
|
+
# Assign an option name of ticker plus strike
|
|
417
|
+
opt_name = params['ticker_label']+'_'+str(strike)
|
|
418
|
+
|
|
419
|
+
# store the implied vol results DataFrame for that strike
|
|
420
|
+
# in the option dictionary
|
|
421
|
+
opt_dict[opt_name] = cls._imp_vol_apply(
|
|
422
|
+
params=params, input_data=input_data, strike=strike,
|
|
423
|
+
option='call')
|
|
424
|
+
|
|
425
|
+
# store the implied vol results DataFrame for that strike
|
|
426
|
+
# in the option list
|
|
427
|
+
params['opt_list'].append(opt_dict[opt_name])
|
|
428
|
+
|
|
429
|
+
print('Call option: ', opt_name)
|
|
430
|
+
|
|
431
|
+
# Concatenate all the option results into a single DataFrame and drop
|
|
432
|
+
# any null values
|
|
433
|
+
tables['imp_vol_data'] = pd.concat(params['opt_list']).dropna()
|
|
434
|
+
|
|
435
|
+
# If a minopts parameter is supplied, filter for number of options
|
|
436
|
+
# greater than parameter
|
|
437
|
+
if params['minopts'] is not None:
|
|
438
|
+
tables['imp_vol_data'] = cls._minopts(
|
|
439
|
+
params=params, data=tables['imp_vol_data'])
|
|
440
|
+
|
|
441
|
+
return params, tables
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
@classmethod
|
|
445
|
+
def _create_strike_range(
|
|
446
|
+
cls,
|
|
447
|
+
params: dict,
|
|
448
|
+
tables: dict) -> dict:
|
|
449
|
+
|
|
450
|
+
# Extract the spot level from the html data
|
|
451
|
+
if params['spot'] is None:
|
|
452
|
+
# tree = html.fromstring(params['html_doc'])
|
|
453
|
+
# priceparse = tree.xpath(
|
|
454
|
+
# '//fin-streamer[@class="Fw(b) Fz(36px) Mb(-4px) D(ib)"]/text()')
|
|
455
|
+
# params['spot'] = float(
|
|
456
|
+
# [str(p) for p in priceparse][0].replace(',',''))
|
|
457
|
+
# soup = BeautifulSoup(params['html_doc'], features="lxml")
|
|
458
|
+
# params['spot'] = float(
|
|
459
|
+
# [a.attrs['data-value'] for a in soup.findAll(
|
|
460
|
+
# 'fin-streamer', {'data-testid': 'qsp-price'})][0])
|
|
461
|
+
params['spot'] = params['extracted_spot']
|
|
462
|
+
|
|
463
|
+
# Calculate initial spot, min and max strikes to use in divisor
|
|
464
|
+
# calculation
|
|
465
|
+
params['init_roundspot'], params['init_put_min'], \
|
|
466
|
+
params['init_call_max'] = cls._strike_filters(
|
|
467
|
+
params=params, divisor=10)
|
|
468
|
+
|
|
469
|
+
# If a divisor value is not provided
|
|
470
|
+
if params['divisor'] is None:
|
|
471
|
+
params = cls._create_divisor(params=params, tables=tables)
|
|
472
|
+
|
|
473
|
+
# Calculate final spot, min and max strikes using chosen divisor
|
|
474
|
+
params['roundspot'], params['put_min'], \
|
|
475
|
+
params['call_max'] = cls._strike_filters(
|
|
476
|
+
params=params, divisor=params['divisor'])
|
|
477
|
+
|
|
478
|
+
# Calculate put options (default is 1/2 spot level)
|
|
479
|
+
if params['put_strikes'] is None:
|
|
480
|
+
params['put_strikes'] = list(
|
|
481
|
+
np.linspace(
|
|
482
|
+
params['put_min'],
|
|
483
|
+
params['roundspot'],
|
|
484
|
+
int((params['roundspot'] - params['put_min'])
|
|
485
|
+
/ params['divisor']) + 1))
|
|
486
|
+
|
|
487
|
+
# Calculate call options (default is twice the spot level)
|
|
488
|
+
if params['call_strikes'] is None:
|
|
489
|
+
params['call_strikes'] = list(
|
|
490
|
+
np.linspace(
|
|
491
|
+
params['roundspot'],
|
|
492
|
+
params['call_max'],
|
|
493
|
+
int((params['call_max'] - params['roundspot'])
|
|
494
|
+
/ params['divisor']) + 1))
|
|
495
|
+
|
|
496
|
+
return params
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
@staticmethod
|
|
500
|
+
def _strike_filters(
|
|
501
|
+
params: dict,
|
|
502
|
+
divisor: float) -> tuple[float, float, float]:
|
|
503
|
+
|
|
504
|
+
# Calculate the point to switch from put to call options
|
|
505
|
+
roundspot = (
|
|
506
|
+
round(params['spot'] / divisor) * divisor)
|
|
507
|
+
|
|
508
|
+
put_min = (
|
|
509
|
+
round(params['spot'] * params['strike_limits'][0] / divisor)
|
|
510
|
+
* divisor)
|
|
511
|
+
|
|
512
|
+
call_max = (
|
|
513
|
+
round(params['spot'] * params['strike_limits'][1] / divisor)
|
|
514
|
+
* divisor)
|
|
515
|
+
|
|
516
|
+
return roundspot, put_min, call_max
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
@staticmethod
|
|
520
|
+
def _create_divisor(
|
|
521
|
+
params: dict,
|
|
522
|
+
tables: dict) -> dict:
|
|
523
|
+
|
|
524
|
+
# Take the set of all the option strikes in the data
|
|
525
|
+
strikes = set(tables['data']['Strike'])
|
|
526
|
+
|
|
527
|
+
# Find the number of options with a remainder of zero for each of the
|
|
528
|
+
# listed potential divisors
|
|
529
|
+
avail_strikes = {}
|
|
530
|
+
for div in [0.5, 1, 1.25, 2.5, 5, 10, 25, 50, 100]:
|
|
531
|
+
avail_strikes[div] = len(
|
|
532
|
+
{x for x in strikes if (
|
|
533
|
+
x%(div) == 0
|
|
534
|
+
and params['init_put_min'] < x < params['init_call_max'])})
|
|
535
|
+
|
|
536
|
+
# Find the maximum divisor of those with the highest number of options
|
|
537
|
+
params['divisor'] = max(
|
|
538
|
+
[divisor for max_strike_count in [max(avail_strikes.values())]
|
|
539
|
+
for divisor, strike_count in avail_strikes.items()
|
|
540
|
+
if strike_count == max_strike_count])
|
|
541
|
+
|
|
542
|
+
return params
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
@classmethod
|
|
546
|
+
def _imp_vol_apply(
|
|
547
|
+
cls,
|
|
548
|
+
params: dict,
|
|
549
|
+
input_data: pd.DataFrame,
|
|
550
|
+
strike: float,
|
|
551
|
+
option: str) -> pd.DataFrame:
|
|
552
|
+
"""
|
|
553
|
+
Apply _implied_vol_by_row method to each row of a DataFrame.
|
|
554
|
+
|
|
555
|
+
Parameters
|
|
556
|
+
----------
|
|
557
|
+
input_data : DataFrame
|
|
558
|
+
DataFrame of Option prices.
|
|
559
|
+
S : Float
|
|
560
|
+
Stock Price.
|
|
561
|
+
K : Float
|
|
562
|
+
Strike Price.
|
|
563
|
+
r : Float
|
|
564
|
+
Interest Rate. The default is 0.005.
|
|
565
|
+
q : Float
|
|
566
|
+
Dividend Yield. The default is 0.
|
|
567
|
+
epsilon : Float
|
|
568
|
+
Degree of precision to return implied vol. The default is
|
|
569
|
+
0.001.
|
|
570
|
+
option : Str
|
|
571
|
+
Option type; 'put' or 'call'.
|
|
572
|
+
method : Str
|
|
573
|
+
Implied Vol method; 'nr', 'bisection' or 'naive'. The
|
|
574
|
+
default is 'nr'.
|
|
575
|
+
|
|
576
|
+
Returns
|
|
577
|
+
-------
|
|
578
|
+
input_data : DataFrame
|
|
579
|
+
DataFrame of Option prices.
|
|
580
|
+
|
|
581
|
+
"""
|
|
582
|
+
|
|
583
|
+
# Filter data by strike and option type
|
|
584
|
+
input_data = (input_data[(input_data['Strike'] == strike)
|
|
585
|
+
& (input_data['Option Type'] == option)])
|
|
586
|
+
|
|
587
|
+
# Apply implied vol method to each row
|
|
588
|
+
input_data = input_data.apply(
|
|
589
|
+
lambda x: cls._imp_vol_by_row(x, params, strike, option), axis=1)
|
|
590
|
+
|
|
591
|
+
return input_data
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
@classmethod
|
|
595
|
+
def _imp_vol_by_row(
|
|
596
|
+
cls,
|
|
597
|
+
row: pd.Series,
|
|
598
|
+
params: dict,
|
|
599
|
+
strike: float,
|
|
600
|
+
option: str) -> pd.Series:
|
|
601
|
+
"""
|
|
602
|
+
Calculate implied vol for one row of a DataFrame.
|
|
603
|
+
|
|
604
|
+
Parameters
|
|
605
|
+
----------
|
|
606
|
+
row : Array
|
|
607
|
+
Each row in the DataFrame.
|
|
608
|
+
S : Float
|
|
609
|
+
Stock Price.
|
|
610
|
+
K : Float
|
|
611
|
+
Strike Price.
|
|
612
|
+
r : Float
|
|
613
|
+
Interest Rate.
|
|
614
|
+
q : Float
|
|
615
|
+
Dividend Yield.
|
|
616
|
+
epsilon : Float
|
|
617
|
+
Degree of precision to return implied vol.
|
|
618
|
+
option : Str
|
|
619
|
+
Option type; 'put' or 'call'.
|
|
620
|
+
method : Str
|
|
621
|
+
Implied Vol method; 'newtonraphson', 'bisection' or
|
|
622
|
+
'iv_naive'.
|
|
623
|
+
|
|
624
|
+
Returns
|
|
625
|
+
-------
|
|
626
|
+
row : Array
|
|
627
|
+
Each row in the DataFrame.
|
|
628
|
+
|
|
629
|
+
"""
|
|
630
|
+
|
|
631
|
+
# Suppress runtime warnings caused by bad vol data
|
|
632
|
+
warnings.filterwarnings("ignore", category=RuntimeWarning)
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
# Select the chosen implied vol method from the dictionary
|
|
636
|
+
func_name = params['method_dict'][params['method']]
|
|
637
|
+
|
|
638
|
+
# for each of the prices: bid, mid, ask, last
|
|
639
|
+
for input_row, output_row in params['row_dict'].items():
|
|
640
|
+
|
|
641
|
+
opt_params = {
|
|
642
|
+
'S':params['spot'],
|
|
643
|
+
'K':strike,
|
|
644
|
+
'T':row['TTM'],
|
|
645
|
+
'r':cls.interest_rate(row['Days'], params['yield_curve']),
|
|
646
|
+
'q':params['q'],
|
|
647
|
+
'cm':row[input_row],
|
|
648
|
+
'epsilon':params['epsilon'],
|
|
649
|
+
'option':option
|
|
650
|
+
}
|
|
651
|
+
try:
|
|
652
|
+
# populate the column using the chosen implied
|
|
653
|
+
# vol method (using getattr() to select
|
|
654
|
+
# dynamically)
|
|
655
|
+
# check if n/a value is returned and print error
|
|
656
|
+
# message if so
|
|
657
|
+
output = getattr(
|
|
658
|
+
ImpliedVol, func_name)(opt_params=opt_params)
|
|
659
|
+
|
|
660
|
+
output = float(output)
|
|
661
|
+
row[output_row] = output
|
|
662
|
+
|
|
663
|
+
except KeyError:
|
|
664
|
+
print("Key Error with option: Strike="+str(strike)+
|
|
665
|
+
" TTM="+str(round(row['TTM'], 3))+
|
|
666
|
+
" vol="+str(row[input_row])+
|
|
667
|
+
" option="+option)
|
|
668
|
+
|
|
669
|
+
except ValueError:
|
|
670
|
+
print("Value Error with option: Strike="+str(strike)+
|
|
671
|
+
" TTM="+str(round(row['TTM'], 3))+
|
|
672
|
+
" vol="+str(row[input_row])+
|
|
673
|
+
" option="+option)
|
|
674
|
+
|
|
675
|
+
# Return warnings to default setting
|
|
676
|
+
warnings.filterwarnings("default", category=RuntimeWarning)
|
|
677
|
+
|
|
678
|
+
return row
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
@classmethod
|
|
682
|
+
def interest_rate(
|
|
683
|
+
cls,
|
|
684
|
+
ttm: int,
|
|
685
|
+
yield_curve: interpolate.interp1d | None = None) -> float:
|
|
686
|
+
"""
|
|
687
|
+
Returns the interest rate for a given number of days to maturity
|
|
688
|
+
|
|
689
|
+
Parameters
|
|
690
|
+
----------
|
|
691
|
+
ttm : Int
|
|
692
|
+
Number of days to maturity.
|
|
693
|
+
yield_curve : Scipy Interpolate object, optional
|
|
694
|
+
The yield curve interpolation function. The default is None in which
|
|
695
|
+
case it will be generated.
|
|
696
|
+
|
|
697
|
+
Returns
|
|
698
|
+
-------
|
|
699
|
+
Float
|
|
700
|
+
The interest rate for the given TTM.
|
|
701
|
+
|
|
702
|
+
"""
|
|
703
|
+
if yield_curve is None:
|
|
704
|
+
yield_curve = cls.generate_yield_curve()
|
|
705
|
+
|
|
706
|
+
return np.round(float(yield_curve(ttm))/100, 5)
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
@staticmethod
|
|
710
|
+
def generate_yield_curve(r: float | None = None) -> interpolate.interp1d:
|
|
711
|
+
"""
|
|
712
|
+
Returns a yield curve interpolation function
|
|
713
|
+
|
|
714
|
+
Parameters
|
|
715
|
+
----------
|
|
716
|
+
r : Float, optional
|
|
717
|
+
If a single interest rate is supplied, the method will calculate a
|
|
718
|
+
flat curve. The default is None.
|
|
719
|
+
|
|
720
|
+
Returns
|
|
721
|
+
-------
|
|
722
|
+
yield_curve : Scipy Interpolate object
|
|
723
|
+
The yield curve interpolation function.
|
|
724
|
+
|
|
725
|
+
"""
|
|
726
|
+
|
|
727
|
+
if r is None:
|
|
728
|
+
|
|
729
|
+
year = dt.date.today().strftime("%Y")
|
|
730
|
+
|
|
731
|
+
# Extract Daily Treasury Par Yield Curve Rates
|
|
732
|
+
url = 'https://home.treasury.gov/resource-center/data-chart-center'+\
|
|
733
|
+
'/interest-rates/TextView?type=daily_treasury_yield_curve'+\
|
|
734
|
+
'&field_tdr_date_value='+year
|
|
735
|
+
data = pd.read_html(url)[0]
|
|
736
|
+
|
|
737
|
+
# Dictionary mapping tenors to days
|
|
738
|
+
ir_tenor_dict = {
|
|
739
|
+
'1 Mo':30,
|
|
740
|
+
'2 Mo':60,
|
|
741
|
+
'3 Mo':90,
|
|
742
|
+
'6 Mo':180,
|
|
743
|
+
'1 Yr':365,
|
|
744
|
+
'2 Yr':730,
|
|
745
|
+
'3 Yr':1095,
|
|
746
|
+
'5 Yr':1826,
|
|
747
|
+
'7 Yr':2556,
|
|
748
|
+
'10 Yr':3652,
|
|
749
|
+
'20 Yr':7305,
|
|
750
|
+
'30 Yr':10952
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
# Take the last row as most recent data and convert to Pandas Series
|
|
754
|
+
current_rate = data.iloc[-1]
|
|
755
|
+
current_rate = current_rate[list(ir_tenor_dict.keys())].squeeze()
|
|
756
|
+
|
|
757
|
+
# Create lists of tenors and interest rates, adding a point at 1 day equal
|
|
758
|
+
# to the 30 day point to allow interpolation of those dates
|
|
759
|
+
tenors = []
|
|
760
|
+
tenors.append(1)
|
|
761
|
+
for bucket in current_rate.index:
|
|
762
|
+
tenors.append(ir_tenor_dict[bucket])
|
|
763
|
+
|
|
764
|
+
rates = []
|
|
765
|
+
for rate in current_rate:
|
|
766
|
+
if not rates:
|
|
767
|
+
rates.append(rate)
|
|
768
|
+
rates.append(rate)
|
|
769
|
+
else:
|
|
770
|
+
rates.append(rate)
|
|
771
|
+
|
|
772
|
+
else:
|
|
773
|
+
rate = r * 100
|
|
774
|
+
tenors = [1, 2738, 5476, 8214, 10952]
|
|
775
|
+
rates = [rate, rate, rate, rate, rate]
|
|
776
|
+
|
|
777
|
+
# Create a curve using cubic spline interpolation
|
|
778
|
+
yield_curve = interpolate.interp1d(tenors, rates, kind='cubic')
|
|
779
|
+
|
|
780
|
+
return yield_curve
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
@classmethod
|
|
784
|
+
def dividend_yield(cls, ticker: str) -> float:
|
|
785
|
+
"""
|
|
786
|
+
Returns the dividend yield for a given ticker
|
|
787
|
+
|
|
788
|
+
Parameters
|
|
789
|
+
----------
|
|
790
|
+
ticker : Str
|
|
791
|
+
The underlying to calculate dividend yield for.
|
|
792
|
+
|
|
793
|
+
Returns
|
|
794
|
+
-------
|
|
795
|
+
Float
|
|
796
|
+
The dividend yield for the given ticker.
|
|
797
|
+
|
|
798
|
+
"""
|
|
799
|
+
|
|
800
|
+
# If the ticker is not valid return zero
|
|
801
|
+
if ticker == '^SPX':
|
|
802
|
+
try:
|
|
803
|
+
div_yield = cls._spx_div_yield()
|
|
804
|
+
except ValueError:
|
|
805
|
+
print("No dividend data for SPX")
|
|
806
|
+
div_yield = '0.0%'
|
|
807
|
+
else:
|
|
808
|
+
try:
|
|
809
|
+
div_yield = cls._stock_dividend_yield(ticker)
|
|
810
|
+
except ValueError:
|
|
811
|
+
print("No dividend data for "+ticker+" - Empty string")
|
|
812
|
+
div_yield = '0.0%'
|
|
813
|
+
except IndexError:
|
|
814
|
+
print("No dividend data for "+ticker+" - Invalid index")
|
|
815
|
+
div_yield = '0.0%'
|
|
816
|
+
|
|
817
|
+
try:
|
|
818
|
+
result = np.round(float(div_yield.rstrip('%'))/100, 5)
|
|
819
|
+
except ValueError:
|
|
820
|
+
print("No valid dividend data for "+ticker)
|
|
821
|
+
result = 0.0
|
|
822
|
+
|
|
823
|
+
return result
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
@staticmethod
|
|
827
|
+
def _stock_dividend_yield(ticker: str) -> str:
|
|
828
|
+
|
|
829
|
+
url = 'https://stockanalysis.com/stocks/'+ticker+'/dividend/'
|
|
830
|
+
|
|
831
|
+
r = requests.get(url, timeout=10)
|
|
832
|
+
|
|
833
|
+
html_doc = r.text
|
|
834
|
+
|
|
835
|
+
tree = html.fromstring(html_doc)
|
|
836
|
+
|
|
837
|
+
parse = tree.xpath("//*[contains(text(), 'Dividend Yield')]/div/text()")
|
|
838
|
+
|
|
839
|
+
return [str(p) for p in parse][0].replace('\n','')
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
@staticmethod
|
|
843
|
+
def _spx_div_yield() -> str:
|
|
844
|
+
|
|
845
|
+
url = 'https://www.multpl.com/s-p-500-dividend-yield'
|
|
846
|
+
|
|
847
|
+
urlopener = UrlOpener()
|
|
848
|
+
response = urlopener.open(url)
|
|
849
|
+
|
|
850
|
+
html_doc = response.text
|
|
851
|
+
|
|
852
|
+
tree = html.fromstring(html_doc)
|
|
853
|
+
|
|
854
|
+
parse = tree.xpath(
|
|
855
|
+
'//div[@id="current"]/text()')
|
|
856
|
+
|
|
857
|
+
return [str(p) for p in parse][1].replace('\n','')
|