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,501 @@
1
+ """
2
+ Market data import and transformation functions
3
+
4
+ """
5
+ import copy
6
+ from datetime import date, timedelta
7
+ from io import StringIO
8
+ import time
9
+ import warnings
10
+ #import datetime as dt
11
+ from bs4 import BeautifulSoup
12
+ from dateutil import parser
13
+ import pandas as pd
14
+ from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory, GoodFriday
15
+ import yfinance as yf
16
+ from volvisdata.market_data_prep import DataPrep, UrlOpener
17
+ warnings.filterwarnings("ignore", category=DeprecationWarning)
18
+ # pylint: disable=invalid-name
19
+
20
+ class Data():
21
+ """
22
+ Market data import and transformation functions
23
+
24
+ """
25
+ @classmethod
26
+ def create_option_data(
27
+ cls,
28
+ params: dict,
29
+ tables: dict) -> tuple[dict, dict]:
30
+ """
31
+ Extract the URL for each of the listed option on Yahoo Finance
32
+ for the given ticker. Extract option data from each URL.
33
+
34
+ Filter / transform the data and calculate implied volatilities for
35
+ specified put and call strikes.
36
+
37
+ Parameters
38
+ ----------
39
+ start_date : Str
40
+ Date from when to include prices (some of the options
41
+ won't have traded for days / weeks and therefore will
42
+ have stale prices).
43
+ ticker : Str
44
+ The ticker identifier used by Yahoo for the chosen stock. The
45
+ default is '^SPX'.
46
+ ticker_label : Str
47
+ The ticker label used in charts.
48
+ wait : Int
49
+ Number of seconds to wait between each url query
50
+ lastmins : Int, Optional
51
+ Restrict to trades within number of minutes since last
52
+ trade time recorded
53
+ mindays : Int, Optional
54
+ Restrict to options greater than certain option expiry
55
+ minopts : Int, Optional
56
+ Restrict to minimum number of options to include that
57
+ option expiry
58
+ volume : Int, Optional
59
+ Restrict to minimum Volume
60
+ openint : Int, Optional
61
+ Restrict to minimum Open Interest
62
+ monthlies : Bool
63
+ Restrict expiries to only 3rd Friday of the month. Default
64
+ is False.
65
+ spot : Float
66
+ Underlying reference level.
67
+ put_strikes : List
68
+ Range of put strikes to calculate implied volatility for.
69
+ call_strikes : List
70
+ Range of call strikes to calculate implied volatility for.
71
+ strike_limits : Tuple
72
+ min and max strikes to use expressed as a decimal
73
+ percentage. The default is (0.5, 2.0).
74
+ divisor : Int
75
+ Distance between each strike in dollars. The default is 25 for SPX
76
+ and 10 otherwise.
77
+ r : Float
78
+ Interest Rate. The default is 0.005.
79
+ q : Float
80
+ Dividend Yield. The default is 0.
81
+ epsilon : Float
82
+ Degree of precision to return implied vol. The default
83
+ is 0.001.
84
+ method : Str
85
+ Implied Vol method; 'nr', 'bisection' or 'naive'. The
86
+ default is 'nr'.
87
+
88
+ Returns
89
+ -------
90
+ DataFrame
91
+ DataFrame of Option data.
92
+
93
+ """
94
+ # Extract URLs and option data
95
+ # params, tables = cls.extractoptions(params=params, tables=tables)
96
+ params, tables = cls.get_option_data(params=params, tables=tables)
97
+ print("Options data extracted")
98
+
99
+ # Filter / transform data
100
+ params, tables = DataPrep.transform(params=params, tables=tables)
101
+ print("Data transformed")
102
+
103
+ # Calculate implied volatilities and combine
104
+ params, tables = DataPrep.combine(params=params, tables=tables)
105
+ print("Data combined")
106
+
107
+ return params, tables
108
+
109
+
110
+ @staticmethod
111
+ def get_option_data(params, tables):
112
+ """
113
+
114
+
115
+ Parameters
116
+ ----------
117
+ ticker : TYPE
118
+ DESCRIPTION.
119
+ params : TYPE
120
+ DESCRIPTION.
121
+ tables : TYPE
122
+ DESCRIPTION.
123
+
124
+ Returns
125
+ -------
126
+ params : TYPE
127
+ DESCRIPTION.
128
+ tables : TYPE
129
+ DESCRIPTION.
130
+
131
+ """
132
+ params['option_dict'] = {}
133
+ params['opt_except_list'] = []
134
+ tables['full_data'] = pd.DataFrame()
135
+ asset = yf.Ticker(params['ticker'])
136
+
137
+ try:
138
+ extracted_spot = asset.info['currentPrice']
139
+ except KeyError:
140
+ try:
141
+ extracted_spot = (asset.info['bid'] + asset.info['ask'])/2
142
+ except KeyError:
143
+ try:
144
+ extracted_spot = asset.info['navPrice']
145
+ except:
146
+ extracted_spot = asset.info['previousClose']
147
+ params['extracted_spot'] = extracted_spot
148
+
149
+ opt_list = asset.options
150
+ params['date_list'] = opt_list
151
+ for expiry in opt_list:
152
+ params['option_dict'][expiry] = []
153
+ chain = asset.option_chain(expiry)
154
+ try:
155
+ calls = chain.calls
156
+
157
+ # Create a column designating these as calls
158
+ calls['Option Type'] = 'call'
159
+ if len(calls) > 0:
160
+ if isinstance(calls['strike'][0], (int, float, complex)):
161
+ params['option_dict'][expiry].append(calls)
162
+ try:
163
+ puts = chain.puts
164
+
165
+ # Create a column designating these as puts
166
+ puts['Option Type'] = 'put'
167
+
168
+ if len(puts) > 0:
169
+ if isinstance(puts['strike'][0], (int, float, complex)):
170
+ params['option_dict'][expiry].append(puts)
171
+ # Concatenate these two DataFrames
172
+ options = pd.concat([calls, puts])
173
+
174
+ # Add an 'Expiry' column with the expiry date
175
+ options['Expiry'] = pd.to_datetime(expiry).date()
176
+
177
+ # Add this DataFrame to 'full_data'
178
+ tables['full_data'] = pd.concat(
179
+ [tables['full_data'], options])
180
+
181
+ except IndexError or KeyError or ValueError:
182
+ # Add an 'Expiry' column with the expiry date
183
+ calls['Expiry'] = pd.to_datetime(expiry).date()
184
+
185
+ # Add this DataFrame to 'full_data'
186
+ tables['full_data'] = pd.concat(
187
+ [tables['full_data'], calls])
188
+
189
+ except IndexError or KeyError or ValueError:
190
+ try:
191
+ # The second entry is 'puts'
192
+ puts = chain.puts
193
+
194
+ # Create a column designating these as puts
195
+ puts['Option Type'] = 'put'
196
+
197
+ if len(puts) > 0:
198
+ if isinstance(puts['strike'][0], (int, float, complex)):
199
+ params['option_dict'][expiry][1] = puts
200
+ # Add an 'Expiry' column with the expiry date
201
+ puts['Expiry'] = pd.to_datetime(expiry).date()
202
+
203
+ # Add this DataFrame to 'full_data'
204
+ tables['full_data'] = pd.concat(
205
+ [tables['full_data'], puts])
206
+
207
+ except IndexError or KeyError or ValueError:
208
+ params['opt_except_list'].append(expiry)
209
+
210
+ tables['full_data'] = tables['full_data'].rename(columns={
211
+ 'lastPrice': 'Last Price',
212
+ 'bid': 'Bid',
213
+ 'ask': 'Ask',
214
+ 'lastTradeDate': 'Last Trade Date',
215
+ 'strike': 'Strike',
216
+ 'openInterest': 'Open Interest',
217
+ 'volume': 'Volume',
218
+ 'impliedVolatility': 'Implied Volatility'
219
+ })
220
+
221
+ return params, tables
222
+
223
+ @classmethod
224
+ def extractoptions(
225
+ cls,
226
+ params: dict,
227
+ tables: dict) -> tuple[dict, dict]:
228
+ """
229
+ Extract the URL for each of the listed option on Yahoo Finance
230
+ for the given ticker. Extract option data from each URL.
231
+
232
+
233
+ Parameters
234
+ ----------
235
+ ticker : Str
236
+ The ticker identifier used by Yahoo for the chosen stock. The
237
+ default is '^SPX'.
238
+ wait : Int
239
+ Number of seconds to wait between each url query
240
+
241
+ Returns
242
+ -------
243
+ DataFrame
244
+ All option data from each of the supplied urls.
245
+
246
+ """
247
+
248
+ # Extract dictionary of option dates and urls
249
+ params = cls._extracturls(params=params)
250
+ print("URL's extracted")
251
+
252
+ params['raw_web_data'] = cls._extract_web_data(params=params)
253
+
254
+ params = cls._read_web_data(params=params)
255
+
256
+ # Create an empty DataFrame
257
+ tables['full_data'] = pd.DataFrame()
258
+
259
+ # Make a list of all the dates of the DataFrames just stored
260
+ # in the default dictionary
261
+ params['date_list'] = list(params['option_dict'].keys())
262
+
263
+ params, tables = cls._process_options(params=params, tables=tables)
264
+
265
+ return params, tables
266
+
267
+
268
+ @staticmethod
269
+ def _extracturls(params: dict) -> dict:
270
+ """
271
+ Extract the URL for each of the listed option on Yahoo Finance
272
+ for the given ticker.
273
+
274
+ Parameters
275
+ ----------
276
+ ticker : Str
277
+ Yahoo ticker (Reuters RIC) for the stock.
278
+
279
+ Returns
280
+ -------
281
+ Dict
282
+ Dictionary of dates and URLs.
283
+
284
+ """
285
+
286
+ # Define the stock root webpage
287
+ url = 'https://finance.yahoo.com/quote/'+params['ticker']\
288
+ +'/options?p='+params['ticker']
289
+
290
+ # Create a UrlOpener object to extract data from the url
291
+ urlopener = UrlOpener()
292
+ response = urlopener.open(url)
293
+
294
+ # Collect the text from this object
295
+ params['html_doc'] = response.text
296
+
297
+ # Use Beautiful Soup to parse this
298
+ soup = BeautifulSoup(params['html_doc'], features="lxml")
299
+
300
+ # Create a list of all the option dates
301
+ #option_dates = [a.get_text() for a in soup.find_all('option')]
302
+ option_dates = [a.get_text() for a in soup.findAll('div', {'role': 'option'})]
303
+
304
+ # Convert this list from string to datetimes
305
+ #dates_list = [dt.datetime.strptime(date, "%B %d, %Y").date() for date
306
+ # in option_dates]
307
+ dates_list = []
308
+ for option_date in option_dates:
309
+ option_date.rstrip()
310
+ try:
311
+ dates_list.append(parser.parse(option_date).date())
312
+ except:
313
+ pass
314
+
315
+ # Convert back to strings in the required format
316
+ str_dates = [date_obj.strftime('%Y-%m-%d') for date_obj in dates_list]
317
+
318
+ # Create a list of all the unix dates used in the url for each
319
+ # of these dates
320
+ #option_pages = [a.attrs['value'] for a in soup.find_all('option')]
321
+ raw_option_pages = [a.attrs['data-value'] for a in soup.findAll('div', {'role': 'option'})]
322
+ option_pages = [num for num in raw_option_pages if ((len(num) == 10) and (num.isdigit()))]
323
+
324
+ # Combine the dates and unixdates in a dictionary
325
+ optodict = dict(zip(str_dates, option_pages))
326
+
327
+ # Create an empty dictionary
328
+ params['url_dict'] = {}
329
+
330
+ # For each date and unixdate in the first dictionary
331
+ for date_val, page in optodict.items():
332
+
333
+ # Create an entry with the date as key and the url plus
334
+ # unix date as value
335
+ params['url_dict'][date_val] = str(
336
+ 'https://finance.yahoo.com/quote/'
337
+ +params['ticker']+'/options?date='+page)
338
+
339
+ return params
340
+
341
+
342
+ @staticmethod
343
+ def _extract_web_data(params: dict) -> dict:
344
+
345
+ # Create an empty dictionary
346
+ raw_web_data = {}
347
+
348
+ # each url needs to have an option expiry date associated with
349
+ # it in the url dict
350
+ for input_date, url in params['url_dict'].items():
351
+
352
+ # UrlOpener function downloads the data
353
+ urlopener = UrlOpener()
354
+ weburl = urlopener.open(url)
355
+ try:
356
+ raw_web_data[input_date] = weburl.text
357
+
358
+ # wait between each query so as not to overload server
359
+ time.sleep(params['wait'])
360
+
361
+ # If there is a problem, report the date and apply extended wait
362
+ except ValueError:
363
+ print("Problem with "+input_date+" data")
364
+ time.sleep(5)
365
+
366
+ return raw_web_data
367
+
368
+
369
+ @staticmethod
370
+ def _read_web_data(params: dict) -> dict:
371
+
372
+ # Create an empty dictionary
373
+ params['option_dict'] = {}
374
+ params['url_except_dict'] = {}
375
+
376
+ for input_date, url in params['url_dict'].items():
377
+ # if data exists
378
+ try:
379
+ # read html data into a DataFrame
380
+ option_frame = pd.read_html(
381
+ StringIO(params['raw_web_data'][input_date]))
382
+
383
+ # Add this DataFrame to the default dictionary, named
384
+ # with the expiry date it refers to
385
+ params['option_dict'][input_date] = option_frame
386
+
387
+ # otherwise collect dictionary of exceptions
388
+ except ValueError:
389
+ params['url_except_dict'][input_date] = url
390
+
391
+ return params
392
+
393
+
394
+ @staticmethod
395
+ def _process_options(
396
+ params: dict,
397
+ tables: dict) -> tuple[dict, dict]:
398
+
399
+ # Create list to store exceptions
400
+ params['opt_except_list'] = []
401
+
402
+ # For each of these dates
403
+ for input_date in params['date_list']:
404
+
405
+ try:
406
+ # The first entry is 'calls'
407
+ calls = params['option_dict'][input_date][0]
408
+
409
+ # Create a column designating these as calls
410
+ calls['Option Type'] = 'call'
411
+
412
+ if str(calls['Strike'][0]).isdigit():
413
+ try:
414
+ # The second entry is 'puts'
415
+ puts = params['option_dict'][input_date][1]
416
+
417
+ # Create a column designating these as puts
418
+ puts['Option Type'] = 'put'
419
+
420
+ if str(puts['Strike'][0]).isdigit():
421
+ # Concatenate these two DataFrames
422
+ options = pd.concat([calls, puts])
423
+
424
+ # Add an 'Expiry' column with the expiry date
425
+ options['Expiry'] = pd.to_datetime(input_date).date()
426
+
427
+ # Add this DataFrame to 'full_data'
428
+ tables['full_data'] = pd.concat(
429
+ [tables['full_data'], options])
430
+
431
+ except IndexError:
432
+
433
+ # Add an 'Expiry' column with the expiry date
434
+ calls['Expiry'] = pd.to_datetime(input_date).date()
435
+
436
+ # Add this DataFrame to 'full_data'
437
+ tables['full_data'] = pd.concat(
438
+ [tables['full_data'], calls])
439
+
440
+ except IndexError:
441
+
442
+ try:
443
+ # The second entry is 'puts'
444
+ puts = params['option_dict'][input_date][1]
445
+
446
+ # Create a column designating these as puts
447
+ puts['Option Type'] = 'put'
448
+
449
+ if str(puts['Strike'][0]).isdigit():
450
+ # Add an 'Expiry' column with the expiry date
451
+ puts['Expiry'] = pd.to_datetime(input_date).date()
452
+
453
+ # Add this DataFrame to 'full_data'
454
+ tables['full_data'] = pd.concat(
455
+ [tables['full_data'], puts])
456
+
457
+ except IndexError:
458
+ params['opt_except_list'].append(input_date)
459
+
460
+ return params, tables
461
+
462
+
463
+ @staticmethod
464
+ def trading_calendar(params: dict) -> dict:
465
+ """
466
+ Generate list of trading holidays
467
+
468
+ Parameters
469
+ ----------
470
+ params : Dict
471
+ Dictionary of key parameters.
472
+
473
+ Returns
474
+ -------
475
+ params : Dict
476
+ Dictionary of key parameters.
477
+
478
+ """
479
+ # Create calendar instance
480
+ cal = get_calendar('USFederalHolidayCalendar')
481
+ cal_mod = copy.deepcopy(cal)
482
+
483
+ start = date.today()
484
+ end = start + timedelta(days=2500)
485
+
486
+ # Remove Columbus Day rule and Veteran's Day rule
487
+ cal_mod.rules = cal_mod.rules[0:6] + cal_mod.rules[8:]
488
+
489
+ # Create new calendar generator
490
+ tradingCal = HolidayCalendarFactory(
491
+ 'TradingCalendar', cal_mod, GoodFriday)
492
+
493
+ tcal = tradingCal()
494
+
495
+ holiday_array = tcal.holidays(start=start, end=end).to_pydatetime()
496
+
497
+ params['trade_holidays'] = []
498
+ for hol in holiday_array:
499
+ params['trade_holidays'].append(hol.date())
500
+
501
+ return params