volbatch 0.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.
- volbatch/__init__.py +1 -0
- volbatch/data.py +184 -0
- volbatch/transform.py +111 -0
- volbatch/utils.py +245 -0
- volbatch/vol_params.py +477 -0
- volbatch/volbatch.py +137 -0
- volbatch-0.0.1.dist-info/METADATA +20 -0
- volbatch-0.0.1.dist-info/RECORD +11 -0
- volbatch-0.0.1.dist-info/WHEEL +5 -0
- volbatch-0.0.1.dist-info/licenses/LICENSE +21 -0
- volbatch-0.0.1.dist-info/top_level.txt +1 -0
volbatch/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
volbatch/data.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Data acquisition base class for volatility calculations.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import datetime as dt
|
|
6
|
+
import json
|
|
7
|
+
import random
|
|
8
|
+
from io import StringIO
|
|
9
|
+
from time import sleep
|
|
10
|
+
from typing import Dict, Any, Optional, List, Union
|
|
11
|
+
|
|
12
|
+
import pandas as pd
|
|
13
|
+
from volvisdata.volatility import Volatility
|
|
14
|
+
from voldiscount.voldiscount import VolDiscount
|
|
15
|
+
|
|
16
|
+
from volbatch.utils import NumpyDateEncoder, UrlOpener, NanConverter, timeout
|
|
17
|
+
from volbatch.transform import VolBatchTransform
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class VolBatchData:
|
|
21
|
+
"""
|
|
22
|
+
Data acquisition methods for volatility batch processing.
|
|
23
|
+
"""
|
|
24
|
+
@staticmethod
|
|
25
|
+
@timeout
|
|
26
|
+
def get_vol_data(
|
|
27
|
+
ticker: str,
|
|
28
|
+
start_date: str,
|
|
29
|
+
discount_type: str,
|
|
30
|
+
skew_tenors: int
|
|
31
|
+
) -> Optional[Dict[str, Any]]:
|
|
32
|
+
"""
|
|
33
|
+
Get volatility data for a ticker.
|
|
34
|
+
"""
|
|
35
|
+
print(f"Starting volatility calculation for {ticker}")
|
|
36
|
+
|
|
37
|
+
args = {
|
|
38
|
+
'ticker': ticker,
|
|
39
|
+
'filename': None,
|
|
40
|
+
'underlying_price': None
|
|
41
|
+
}
|
|
42
|
+
vol = VolDiscount(**args)
|
|
43
|
+
discount_df = vol.get_data_with_rates()
|
|
44
|
+
|
|
45
|
+
inputs = {
|
|
46
|
+
'ticker': ticker,
|
|
47
|
+
'wait': 1,
|
|
48
|
+
'monthlies': True,
|
|
49
|
+
'start_date': start_date,
|
|
50
|
+
'discount_type': discount_type,
|
|
51
|
+
'precomputed_data': discount_df
|
|
52
|
+
}
|
|
53
|
+
imp = Volatility(**inputs)
|
|
54
|
+
|
|
55
|
+
imp.data()
|
|
56
|
+
imp.skewreport(skew_tenors)
|
|
57
|
+
|
|
58
|
+
vol_dict = VolBatchTransform.create_vol_dict(imp, skew_tenors)
|
|
59
|
+
vol_dict['skew_dict']['ticker'] = imp.params['ticker']
|
|
60
|
+
vol_dict['skew_dict']['start_date'] = imp.params['start_date']
|
|
61
|
+
|
|
62
|
+
jsonstring = json.dumps(vol_dict, cls=NumpyDateEncoder)
|
|
63
|
+
voldata = json.loads(jsonstring)
|
|
64
|
+
|
|
65
|
+
return voldata
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
@timeout
|
|
69
|
+
def get_vol_data_with_divs(
|
|
70
|
+
ticker: str,
|
|
71
|
+
div_yield: Union[float, str],
|
|
72
|
+
interest_rate: float,
|
|
73
|
+
start_date: str,
|
|
74
|
+
skew_tenors: int
|
|
75
|
+
) -> Optional[Dict[str, Any]]:
|
|
76
|
+
"""
|
|
77
|
+
Get volatility data for a ticker incorporating dividend yields.
|
|
78
|
+
"""
|
|
79
|
+
div_yield = float(div_yield)
|
|
80
|
+
|
|
81
|
+
inputs = {
|
|
82
|
+
'ticker': ticker,
|
|
83
|
+
'start_date': start_date,
|
|
84
|
+
'monthlies': True,
|
|
85
|
+
'q': div_yield,
|
|
86
|
+
'r': interest_rate,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
imp = Volatility(**inputs)
|
|
90
|
+
imp.data()
|
|
91
|
+
imp.skewreport(skew_tenors)
|
|
92
|
+
|
|
93
|
+
vol_dict = VolBatchTransform.create_vol_dict(imp, skew_tenors)
|
|
94
|
+
vol_dict['skew_dict']['ticker'] = imp.params['ticker']
|
|
95
|
+
vol_dict['skew_dict']['start_date'] = imp.params['start_date']
|
|
96
|
+
|
|
97
|
+
jsonstring = json.dumps(vol_dict, cls=NumpyDateEncoder)
|
|
98
|
+
voldata = json.loads(jsonstring)
|
|
99
|
+
|
|
100
|
+
return voldata
|
|
101
|
+
|
|
102
|
+
@staticmethod
|
|
103
|
+
def get_div_yields(params: Dict[str, Any]) -> Dict[str, Any]:
|
|
104
|
+
"""
|
|
105
|
+
Fetch dividend yields for all tickers in tickerMap.
|
|
106
|
+
Returns modified params dictionary with div_map added.
|
|
107
|
+
"""
|
|
108
|
+
params_copy = params.copy() # Create a copy to avoid modifying the original
|
|
109
|
+
div_map: Dict[str, float] = {}
|
|
110
|
+
|
|
111
|
+
for key in params_copy['tickerMap'].keys():
|
|
112
|
+
random.seed(dt.datetime.now().timestamp())
|
|
113
|
+
user_agent = random.choice(params_copy['USER_AGENTS'])
|
|
114
|
+
params_copy['request_headers']["User-Agent"] = user_agent
|
|
115
|
+
urlopener = UrlOpener()
|
|
116
|
+
key_lower = key.lower()
|
|
117
|
+
try:
|
|
118
|
+
url = 'https://stockanalysis.com/stocks/'+key_lower+'/'
|
|
119
|
+
response = urlopener.open(url, params_copy['request_headers'])
|
|
120
|
+
html_doc = response.text
|
|
121
|
+
data_list = pd.read_html(StringIO(html_doc))
|
|
122
|
+
div_str = data_list[0].iloc[7, 1]
|
|
123
|
+
print(div_str)
|
|
124
|
+
try:
|
|
125
|
+
divo = div_str.split(" ", 1)[1].rsplit(" ", 1)[0] # type: ignore
|
|
126
|
+
div_yield = divo[1:-2]
|
|
127
|
+
div_map[key] = float(div_yield) / 100
|
|
128
|
+
print("Stock div yield for ticker: ", key)
|
|
129
|
+
except:
|
|
130
|
+
print("No stock div yield for ticker: ", key)
|
|
131
|
+
div_map[key] = 0.0
|
|
132
|
+
|
|
133
|
+
except:
|
|
134
|
+
try:
|
|
135
|
+
url = 'https://stockanalysis.com/etf/'+key_lower+'/'
|
|
136
|
+
response = urlopener.open(url, params_copy['request_headers'])
|
|
137
|
+
html_doc = response.text
|
|
138
|
+
data_list = pd.read_html(StringIO(html_doc))
|
|
139
|
+
div_str = data_list[0].iloc[5, 1]
|
|
140
|
+
print(div_str)
|
|
141
|
+
try:
|
|
142
|
+
div_yield = div_str[0:-2] # type: ignore
|
|
143
|
+
div_map[key] = float(div_yield) / 100
|
|
144
|
+
print("Etf div yield for ticker: ", key)
|
|
145
|
+
except:
|
|
146
|
+
print("No etf div yield for ticker: ", key)
|
|
147
|
+
div_map[key] = 0.0
|
|
148
|
+
|
|
149
|
+
except:
|
|
150
|
+
print("problem with: ", key)
|
|
151
|
+
div_map[key] = 0.0
|
|
152
|
+
|
|
153
|
+
sleep(random.randint(5, 15))
|
|
154
|
+
|
|
155
|
+
div_map['SPX'] = div_map['SPY']
|
|
156
|
+
|
|
157
|
+
for key in params_copy['tickerMap'].keys():
|
|
158
|
+
params_copy['tickerMap'][key]['divYield'] = div_map[key]
|
|
159
|
+
|
|
160
|
+
jsonstring = json.dumps(params_copy['tickerMap'], cls=NanConverter)
|
|
161
|
+
tickerdata = json.loads(jsonstring)
|
|
162
|
+
filename = 'tickerMap.json'
|
|
163
|
+
|
|
164
|
+
if params_copy['save']:
|
|
165
|
+
with open(filename, "w") as fp:
|
|
166
|
+
json.dump(tickerdata, fp, cls=NanConverter)
|
|
167
|
+
|
|
168
|
+
params_copy['div_map'] = div_map
|
|
169
|
+
return params_copy
|
|
170
|
+
|
|
171
|
+
@staticmethod
|
|
172
|
+
def load_div_yields(filename: str = 'tickerMap.json') -> Dict[str, float]:
|
|
173
|
+
"""
|
|
174
|
+
Load dividend yields from a previously saved tickerMap JSON file.
|
|
175
|
+
"""
|
|
176
|
+
with open(filename) as f:
|
|
177
|
+
ticker_map = json.load(f)
|
|
178
|
+
|
|
179
|
+
div_map: Dict[str, float] = {}
|
|
180
|
+
for key, value in ticker_map.items():
|
|
181
|
+
div_map[key] = value['divYield']
|
|
182
|
+
|
|
183
|
+
return div_map
|
|
184
|
+
|
volbatch/transform.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Data transformation base class for volatility calculations.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
from typing import Dict, Any, List, Tuple
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from volvisdata.volatility import Volatility
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class VolBatchTransform:
|
|
13
|
+
"""
|
|
14
|
+
Data transformation methods for volatility batch processing.
|
|
15
|
+
"""
|
|
16
|
+
@staticmethod
|
|
17
|
+
def create_vol_dict(
|
|
18
|
+
imp: Volatility,
|
|
19
|
+
skew_tenors: int
|
|
20
|
+
) -> Dict[str, Any]:
|
|
21
|
+
"""
|
|
22
|
+
Create a volatility dictionary from a Volatility instance.
|
|
23
|
+
"""
|
|
24
|
+
vol_dict: Dict[str, Any] = {}
|
|
25
|
+
vol_dict['data_dict'] = copy.deepcopy(imp.data_dict)
|
|
26
|
+
vol_types = list(vol_dict['data_dict'].keys())
|
|
27
|
+
for vt in vol_types:
|
|
28
|
+
try:
|
|
29
|
+
del vol_dict['data_dict'][vt]['params']['yield_curve']
|
|
30
|
+
except KeyError:
|
|
31
|
+
pass
|
|
32
|
+
try:
|
|
33
|
+
del vol_dict['data_dict'][vt]['tables']
|
|
34
|
+
except KeyError:
|
|
35
|
+
pass
|
|
36
|
+
try:
|
|
37
|
+
del vol_dict['data_dict'][vt]['params']['option_dict']
|
|
38
|
+
del vol_dict['data_dict'][vt]['params']['opt_list']
|
|
39
|
+
except KeyError:
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
raw_skew_dict = copy.deepcopy(imp.vol_dict)
|
|
43
|
+
|
|
44
|
+
skew_df = pd.DataFrame()
|
|
45
|
+
skew_df['keys'] = list(raw_skew_dict.keys())
|
|
46
|
+
skew_df['vol'] = list(raw_skew_dict.values())
|
|
47
|
+
skew_df['tenor'] = skew_df['keys'].str[0]
|
|
48
|
+
skew_df['strike'] = skew_df['keys'].str[1]
|
|
49
|
+
skew_df = skew_df.drop(['keys'], axis=1)
|
|
50
|
+
skew_df = skew_df.reindex(['tenor', 'strike', 'vol'], axis=1)
|
|
51
|
+
tenors = list(set(skew_df['tenor']))
|
|
52
|
+
|
|
53
|
+
skew_data: Dict[str, Dict[str, float]] = {}
|
|
54
|
+
str_tenors: List[str] = []
|
|
55
|
+
for tenor in tenors:
|
|
56
|
+
str_tenors.append(str(tenor)+'M')
|
|
57
|
+
|
|
58
|
+
for tenor in str_tenors:
|
|
59
|
+
skew_data[tenor] = {}
|
|
60
|
+
|
|
61
|
+
for index, _ in skew_df.iterrows():
|
|
62
|
+
skew_data[str(skew_df['tenor'].iloc[index])+'M'][str(int( #type:ignore
|
|
63
|
+
skew_df['strike'].iloc[index]))] = float(skew_df['vol'].iloc[index]) #type:ignore
|
|
64
|
+
|
|
65
|
+
vol_dict['skew_dict'] = skew_data
|
|
66
|
+
|
|
67
|
+
full_skew_dict = VolBatchTransform.create_skew_data(skew_tenors, raw_skew_dict, imp)
|
|
68
|
+
vol_dict['skew_data'] = full_skew_dict
|
|
69
|
+
|
|
70
|
+
return vol_dict
|
|
71
|
+
|
|
72
|
+
@staticmethod
|
|
73
|
+
def create_skew_data(
|
|
74
|
+
num_tenors: int,
|
|
75
|
+
skew_dict: Dict[Tuple[int, int], float],
|
|
76
|
+
imp: Volatility
|
|
77
|
+
) -> Dict[str, Any]:
|
|
78
|
+
"""
|
|
79
|
+
Create a detailed skew data structure from volatility data.
|
|
80
|
+
"""
|
|
81
|
+
skew_df = pd.DataFrame(index=range(num_tenors), columns=range(5))
|
|
82
|
+
skew_df.columns = [80, 90, 100, 110, 120]
|
|
83
|
+
tenors = list(range(1, 25))
|
|
84
|
+
skew_df.index = tenors # type: ignore
|
|
85
|
+
|
|
86
|
+
for (tenor, strike) in skew_dict.keys():
|
|
87
|
+
skew_df.loc[tenor, strike] = skew_dict[(tenor, strike)]
|
|
88
|
+
|
|
89
|
+
skew_df.columns = ['80%', '90%', 'ATM', '110%', '120%']
|
|
90
|
+
|
|
91
|
+
skew_df['-20% Skew'] = (skew_df['80%'] - skew_df['ATM']) / 20
|
|
92
|
+
skew_df['-10% Skew'] = (skew_df['90%'] - skew_df['ATM']) / 10
|
|
93
|
+
skew_df['+10% Skew'] = (skew_df['110%'] - skew_df['ATM']) / 10
|
|
94
|
+
skew_df['+20% Skew'] = (skew_df['120%'] - skew_df['ATM']) / 20
|
|
95
|
+
|
|
96
|
+
skew_df['label'] = skew_df.index
|
|
97
|
+
skew_df['label'] = skew_df['label'].astype(str)
|
|
98
|
+
|
|
99
|
+
shifts = ['-20% Skew', '-10% Skew', '+10% Skew', '+20% Skew']
|
|
100
|
+
for item in shifts:
|
|
101
|
+
skew_df[item] = skew_df[item].apply(lambda x: round(x, 2))
|
|
102
|
+
|
|
103
|
+
skew_dict2 = skew_df.to_dict(orient='index')
|
|
104
|
+
|
|
105
|
+
skew_data: Dict[str, Any] = {}
|
|
106
|
+
skew_data['skew_dict'] = skew_dict2
|
|
107
|
+
skew_data['ticker'] = imp.params['ticker']
|
|
108
|
+
skew_data['start_date'] = imp.params['start_date']
|
|
109
|
+
|
|
110
|
+
return skew_data
|
|
111
|
+
|
volbatch/utils.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utility functions and classes for financial data processing and volatility calculations.
|
|
3
|
+
|
|
4
|
+
This module provides specialized JSON encoders for numpy and pandas types,
|
|
5
|
+
utilities for HTTP requests to financial data sources, timeout mechanisms,
|
|
6
|
+
and other helper functions for handling financial data structures.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import datetime as dt
|
|
10
|
+
import functools
|
|
11
|
+
from json import JSONEncoder
|
|
12
|
+
import math
|
|
13
|
+
import threading
|
|
14
|
+
from typing import List, Optional, Any, Dict, Callable, TypeVar
|
|
15
|
+
import numpy as np
|
|
16
|
+
import pandas as pd
|
|
17
|
+
import requests
|
|
18
|
+
from volbatch.vol_params import vol_params
|
|
19
|
+
|
|
20
|
+
TIMEOUT_SECONDS = vol_params.get('timeout_seconds')
|
|
21
|
+
|
|
22
|
+
T = TypeVar('T')
|
|
23
|
+
R = TypeVar('R')
|
|
24
|
+
|
|
25
|
+
class NumpyDateEncoder(JSONEncoder):
|
|
26
|
+
"""
|
|
27
|
+
Special JSON encoder for numpy types.
|
|
28
|
+
|
|
29
|
+
This encoder handles various numpy and pandas data types and converts them
|
|
30
|
+
to standard Python types that can be serialized to JSON.
|
|
31
|
+
"""
|
|
32
|
+
def default(self, obj: Any) -> Any:
|
|
33
|
+
try:
|
|
34
|
+
if isinstance(obj, (np.integer)):
|
|
35
|
+
return int(obj)
|
|
36
|
+
if isinstance(obj, float):
|
|
37
|
+
return round(obj, 2)
|
|
38
|
+
if isinstance(obj, (np.floating)):
|
|
39
|
+
float_obj = float(obj)
|
|
40
|
+
return round(float_obj, 2)
|
|
41
|
+
if isinstance(obj, (np.ndarray, pd.Series)):
|
|
42
|
+
return obj.tolist()
|
|
43
|
+
if isinstance(obj, (dt.datetime, dt.date)):
|
|
44
|
+
return obj.isoformat()
|
|
45
|
+
if isinstance(obj, (pd.DatetimeIndex)):
|
|
46
|
+
return obj.date.tolist()
|
|
47
|
+
if isinstance(obj, (pd.DataFrame)):
|
|
48
|
+
return obj.to_json()
|
|
49
|
+
|
|
50
|
+
except TypeError as e:
|
|
51
|
+
print(f"Error converting {type(obj)}: {e}")
|
|
52
|
+
|
|
53
|
+
return JSONEncoder.default(self, obj)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class UrlOpener:
|
|
57
|
+
"""
|
|
58
|
+
Extract data from Yahoo Finance URL.
|
|
59
|
+
|
|
60
|
+
A utility class that wraps the requests module to make HTTP requests
|
|
61
|
+
to Yahoo Finance and other financial data sources.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(self) -> None:
|
|
65
|
+
self._session = requests
|
|
66
|
+
|
|
67
|
+
def open(self, url: str, request_headers: Dict[str, str]) -> requests.models.Response:
|
|
68
|
+
"""
|
|
69
|
+
Extract data from Yahoo Finance URL.
|
|
70
|
+
|
|
71
|
+
Parameters
|
|
72
|
+
----------
|
|
73
|
+
url : str
|
|
74
|
+
The URL to extract data from.
|
|
75
|
+
request_headers : Dict[str, str]
|
|
76
|
+
HTTP headers to include in the request.
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
requests.models.Response
|
|
81
|
+
Response object of requests module.
|
|
82
|
+
|
|
83
|
+
Raises
|
|
84
|
+
------
|
|
85
|
+
requests.exceptions.RequestException
|
|
86
|
+
If there is an issue with the HTTP request
|
|
87
|
+
"""
|
|
88
|
+
print("User Agent: ", request_headers["User-Agent"])
|
|
89
|
+
response = self._session.get(
|
|
90
|
+
url=url, headers=request_headers, timeout=10)
|
|
91
|
+
|
|
92
|
+
return response
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def nan_to_none(obj: Any) -> Any:
|
|
96
|
+
"""
|
|
97
|
+
Recursively convert NaN values to None in nested data structures.
|
|
98
|
+
Handles both Python floats and NumPy floating types.
|
|
99
|
+
|
|
100
|
+
Parameters
|
|
101
|
+
----------
|
|
102
|
+
obj : Any
|
|
103
|
+
The object to process
|
|
104
|
+
|
|
105
|
+
Returns
|
|
106
|
+
-------
|
|
107
|
+
Any
|
|
108
|
+
The processed object with NaN values replaced by None
|
|
109
|
+
"""
|
|
110
|
+
# Handle dictionaries recursively
|
|
111
|
+
if isinstance(obj, dict):
|
|
112
|
+
return {k: nan_to_none(v) for k, v in obj.items()}
|
|
113
|
+
|
|
114
|
+
# Handle lists recursively
|
|
115
|
+
if isinstance(obj, list):
|
|
116
|
+
return [nan_to_none(v) for v in obj]
|
|
117
|
+
|
|
118
|
+
# Handle Python float NaN
|
|
119
|
+
if isinstance(obj, float):
|
|
120
|
+
if math.isnan(obj):
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
# Handle NumPy floating NaN
|
|
124
|
+
if isinstance(obj, np.floating):
|
|
125
|
+
if np.isnan(obj):
|
|
126
|
+
return None
|
|
127
|
+
|
|
128
|
+
# Return unchanged if not a NaN
|
|
129
|
+
return obj
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class NanConverter(JSONEncoder):
|
|
133
|
+
"""
|
|
134
|
+
Enhanced JSON encoder that handles NaN values in both Python and NumPy types.
|
|
135
|
+
|
|
136
|
+
This encoder applies the nan_to_none conversion before encoding JSON to
|
|
137
|
+
ensure all NaN values are properly handled.
|
|
138
|
+
"""
|
|
139
|
+
def encode(self, obj: Any, *args: Any, **kwargs: Any) -> str:
|
|
140
|
+
"""
|
|
141
|
+
Apply nan2None processing before encoding to JSON.
|
|
142
|
+
|
|
143
|
+
Parameters
|
|
144
|
+
----------
|
|
145
|
+
obj : Any
|
|
146
|
+
The object to encode
|
|
147
|
+
*args : Any
|
|
148
|
+
Additional positional arguments for the encoder
|
|
149
|
+
**kwargs : Any
|
|
150
|
+
Additional keyword arguments for the encoder
|
|
151
|
+
|
|
152
|
+
Returns
|
|
153
|
+
-------
|
|
154
|
+
str
|
|
155
|
+
JSON-encoded string with NaN values converted to null
|
|
156
|
+
"""
|
|
157
|
+
return super().encode(nan_to_none(obj), *args, **kwargs)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def round_floats(obj: Any) -> Any:
|
|
161
|
+
"""
|
|
162
|
+
Recursively round floating point values in nested data structures.
|
|
163
|
+
|
|
164
|
+
This function traverses complex nested data structures and rounds any
|
|
165
|
+
floating point values to 2 decimal places.
|
|
166
|
+
|
|
167
|
+
Parameters
|
|
168
|
+
----------
|
|
169
|
+
obj : Any
|
|
170
|
+
The object containing floating point values to round
|
|
171
|
+
|
|
172
|
+
Returns
|
|
173
|
+
-------
|
|
174
|
+
Any
|
|
175
|
+
The object with all floating point values rounded to 2 decimal places
|
|
176
|
+
"""
|
|
177
|
+
if isinstance(obj, float):
|
|
178
|
+
return round(obj, 2)
|
|
179
|
+
if isinstance(obj, dict):
|
|
180
|
+
return {k: round_floats(v) for k, v in obj.items()}
|
|
181
|
+
if isinstance(obj, (list, tuple)):
|
|
182
|
+
return [round_floats(x) for x in obj]
|
|
183
|
+
return obj
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class TimeoutError(Exception):
|
|
187
|
+
"""Exception raised when a function execution exceeds the time limit."""
|
|
188
|
+
pass
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def timeout(func: Callable[..., R]) -> Callable[..., Optional[R]]:
|
|
192
|
+
"""
|
|
193
|
+
Windows-friendly decorator that applies a timeout to the decorated function.
|
|
194
|
+
Uses TIMEOUT_SECONDS constant from vol_params.
|
|
195
|
+
|
|
196
|
+
Parameters
|
|
197
|
+
----------
|
|
198
|
+
func : Callable[..., R]
|
|
199
|
+
The function to apply timeout to
|
|
200
|
+
|
|
201
|
+
Returns
|
|
202
|
+
-------
|
|
203
|
+
Callable[..., Optional[R]]
|
|
204
|
+
Wrapped function that will return None if the execution exceeds the timeout
|
|
205
|
+
|
|
206
|
+
Raises
|
|
207
|
+
------
|
|
208
|
+
Exception
|
|
209
|
+
Re-raises any exception that occurred in the wrapped function
|
|
210
|
+
"""
|
|
211
|
+
@functools.wraps(func)
|
|
212
|
+
def wrapper(*args: Any, **kwargs: Any) -> Optional[R]:
|
|
213
|
+
result: List[Optional[R]] = [None]
|
|
214
|
+
exception: List[Optional[Exception]] = [None]
|
|
215
|
+
completed: List[bool] = [False]
|
|
216
|
+
|
|
217
|
+
def worker() -> None:
|
|
218
|
+
try:
|
|
219
|
+
result[0] = func(*args, **kwargs)
|
|
220
|
+
completed[0] = True
|
|
221
|
+
except Exception as e:
|
|
222
|
+
exception[0] = e
|
|
223
|
+
|
|
224
|
+
thread = threading.Thread(target=worker)
|
|
225
|
+
thread.daemon = True
|
|
226
|
+
thread.start()
|
|
227
|
+
|
|
228
|
+
# Wait until timeout or function completes
|
|
229
|
+
thread.join(TIMEOUT_SECONDS)
|
|
230
|
+
|
|
231
|
+
# If function raised an exception, re-raise it
|
|
232
|
+
if exception[0] is not None:
|
|
233
|
+
if isinstance(exception[0], Exception):
|
|
234
|
+
raise exception[0]
|
|
235
|
+
else:
|
|
236
|
+
# This should never happen, but type checking may flag it
|
|
237
|
+
raise RuntimeError(f"Unknown error in {func.__name__}")
|
|
238
|
+
|
|
239
|
+
# If thread is still running after timeout
|
|
240
|
+
if not completed[0]:
|
|
241
|
+
print(f"Function {func.__name__} timed out after {TIMEOUT_SECONDS} seconds")
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
return result[0]
|
|
245
|
+
return wrapper
|
volbatch/vol_params.py
ADDED
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
vol_params = {
|
|
2
|
+
'divs': False,
|
|
3
|
+
'skew_tenors': 24,
|
|
4
|
+
'save': False,
|
|
5
|
+
'interest_rate': 0.0454,
|
|
6
|
+
'timeout_seconds': 120,
|
|
7
|
+
'discount_type': 'smooth',
|
|
8
|
+
'tickerMap':{
|
|
9
|
+
'AAPL':
|
|
10
|
+
{
|
|
11
|
+
'ticker': 'AAPL',
|
|
12
|
+
'longName': 'Apple Inc.',
|
|
13
|
+
'divYield': 0.0042
|
|
14
|
+
},
|
|
15
|
+
'AI':
|
|
16
|
+
{
|
|
17
|
+
'ticker': 'AI',
|
|
18
|
+
'longName': 'C3.ai, Inc.',
|
|
19
|
+
'divYield': 0.0
|
|
20
|
+
},
|
|
21
|
+
'AMD':
|
|
22
|
+
{
|
|
23
|
+
'ticker': 'AMD',
|
|
24
|
+
'longName': 'Advanced Micro Devices, Inc.',
|
|
25
|
+
'divYield': 0.0
|
|
26
|
+
},
|
|
27
|
+
'AMZN':
|
|
28
|
+
{
|
|
29
|
+
'ticker': 'AMZN',
|
|
30
|
+
'longName': 'Amazon.com, Inc.',
|
|
31
|
+
'divYield': 0.0
|
|
32
|
+
},
|
|
33
|
+
'AVGO':
|
|
34
|
+
{
|
|
35
|
+
'ticker': 'AVGO',
|
|
36
|
+
'longName': 'Broadcom Inc.',
|
|
37
|
+
'divYield': 0.0139
|
|
38
|
+
},
|
|
39
|
+
'BA':
|
|
40
|
+
{
|
|
41
|
+
'ticker': 'BA',
|
|
42
|
+
'longName': 'The Boeing Company',
|
|
43
|
+
'divYield': 0.0
|
|
44
|
+
},
|
|
45
|
+
'BABA':
|
|
46
|
+
{
|
|
47
|
+
'ticker': 'BABA',
|
|
48
|
+
'longName': 'Alibaba Group Holding Limited',
|
|
49
|
+
'divYield': 0.0124
|
|
50
|
+
},
|
|
51
|
+
'BAC':
|
|
52
|
+
{
|
|
53
|
+
'ticker': 'BAC',
|
|
54
|
+
'longName': 'Bank of America Corporation',
|
|
55
|
+
'divYield': 0.0231
|
|
56
|
+
},
|
|
57
|
+
'BITO':
|
|
58
|
+
{
|
|
59
|
+
'ticker': 'BITO',
|
|
60
|
+
'longName': 'ProShares Bitcoin ETF',
|
|
61
|
+
'divYield': 0.6087
|
|
62
|
+
},
|
|
63
|
+
'C':
|
|
64
|
+
{
|
|
65
|
+
'ticker': 'C',
|
|
66
|
+
'longName': 'Citigroup Inc.',
|
|
67
|
+
'divYield': 0.0314
|
|
68
|
+
},
|
|
69
|
+
'CLSK':
|
|
70
|
+
{
|
|
71
|
+
'ticker': 'CLSK',
|
|
72
|
+
'longName': 'CleanSpark, Inc.',
|
|
73
|
+
'divYield': 0.0
|
|
74
|
+
},
|
|
75
|
+
'COIN':
|
|
76
|
+
{
|
|
77
|
+
'ticker': 'COIN',
|
|
78
|
+
'longName': 'Coinbase Global, Inc.',
|
|
79
|
+
'divYield': 0.0
|
|
80
|
+
},
|
|
81
|
+
'DIA':
|
|
82
|
+
{
|
|
83
|
+
'ticker': 'DIA',
|
|
84
|
+
'longName': 'SPDR Dow Jones Industrial Average ETF Trust',
|
|
85
|
+
'divYield': 0.0201
|
|
86
|
+
},
|
|
87
|
+
'DJT':
|
|
88
|
+
{
|
|
89
|
+
'ticker': 'DJT',
|
|
90
|
+
'longName': 'Trump Media & Technology Group Corp.',
|
|
91
|
+
'divYield': 0.0
|
|
92
|
+
},
|
|
93
|
+
'EEM':
|
|
94
|
+
{
|
|
95
|
+
'ticker': 'EEM',
|
|
96
|
+
'longName': 'iShares MSCI Emerging Markets ETF',
|
|
97
|
+
'divYield': 0.0248
|
|
98
|
+
},
|
|
99
|
+
'ET':
|
|
100
|
+
{
|
|
101
|
+
'ticker': 'ET',
|
|
102
|
+
'longName': 'Energy Transfer LP',
|
|
103
|
+
'divYield': 0.0665
|
|
104
|
+
},
|
|
105
|
+
'EWZ':
|
|
106
|
+
{
|
|
107
|
+
'ticker': 'EWZ',
|
|
108
|
+
'longName': 'iShares MSCI Brazil ETF',
|
|
109
|
+
'divYield': 0.0884
|
|
110
|
+
},
|
|
111
|
+
# 'F':
|
|
112
|
+
# {
|
|
113
|
+
# 'ticker': 'F',
|
|
114
|
+
# 'longName': 'Ford Motor Company',
|
|
115
|
+
# 'divYield': 0.0859
|
|
116
|
+
# },
|
|
117
|
+
'FXI':
|
|
118
|
+
{
|
|
119
|
+
'ticker': 'FXI',
|
|
120
|
+
'longName': 'iShares China Large-Cap ETF',
|
|
121
|
+
'divYield': 0.0187
|
|
122
|
+
},
|
|
123
|
+
'GDX':
|
|
124
|
+
{
|
|
125
|
+
'ticker': 'GDX',
|
|
126
|
+
'longName': 'VanEck Gold Miners ETF',
|
|
127
|
+
'divYield': 0.0112
|
|
128
|
+
},
|
|
129
|
+
'GLD':
|
|
130
|
+
{
|
|
131
|
+
'ticker': 'GLD',
|
|
132
|
+
'longName': 'SPDR Gold Shares',
|
|
133
|
+
'divYield': 0.0
|
|
134
|
+
},
|
|
135
|
+
'GME':
|
|
136
|
+
{
|
|
137
|
+
'ticker': 'GME',
|
|
138
|
+
'longName': 'GameStop Corp.',
|
|
139
|
+
'divYield': 0.0
|
|
140
|
+
},
|
|
141
|
+
'GOLD':
|
|
142
|
+
{
|
|
143
|
+
'ticker': 'GOLD',
|
|
144
|
+
'longName': 'Barrick Gold Corporation',
|
|
145
|
+
'divYield': 0.0226
|
|
146
|
+
},
|
|
147
|
+
'GOOGL':
|
|
148
|
+
{
|
|
149
|
+
'ticker': 'GOOGL',
|
|
150
|
+
'longName': 'Alphabet Inc.',
|
|
151
|
+
'divYield': 0.0042
|
|
152
|
+
},
|
|
153
|
+
'HOOD':
|
|
154
|
+
{
|
|
155
|
+
'ticker': 'HOOD',
|
|
156
|
+
'longName': 'Robinhood Markets, Inc.',
|
|
157
|
+
'divYield': 0.0
|
|
158
|
+
},
|
|
159
|
+
'HYG':
|
|
160
|
+
{
|
|
161
|
+
'ticker': 'HYG',
|
|
162
|
+
'longName': 'iShares iBoxx $ High Yield Corporate Bond ETF',
|
|
163
|
+
'divYield': 0.065
|
|
164
|
+
},
|
|
165
|
+
'INTC':
|
|
166
|
+
{
|
|
167
|
+
'ticker': 'INTC',
|
|
168
|
+
'longName': 'Intel Corporation',
|
|
169
|
+
'divYield': 0.0
|
|
170
|
+
},
|
|
171
|
+
'IWM':
|
|
172
|
+
{
|
|
173
|
+
'ticker': 'IWM',
|
|
174
|
+
'longName': 'iShares Russell 2000 ETF',
|
|
175
|
+
'divYield': 0.0117
|
|
176
|
+
},
|
|
177
|
+
'KRE':
|
|
178
|
+
{
|
|
179
|
+
'ticker': 'KRE',
|
|
180
|
+
'longName': 'SPDR S&P Regional Banking ETF',
|
|
181
|
+
'divYield': 0.0268
|
|
182
|
+
},
|
|
183
|
+
'MARA':
|
|
184
|
+
{
|
|
185
|
+
'ticker': 'MARA',
|
|
186
|
+
'longName': 'MARA Holdings, Inc.',
|
|
187
|
+
'divYield': 0.0
|
|
188
|
+
},
|
|
189
|
+
'META':
|
|
190
|
+
{
|
|
191
|
+
'ticker': 'META',
|
|
192
|
+
'longName': 'Meta Platforms, Inc.',
|
|
193
|
+
'divYield': 0.0032
|
|
194
|
+
},
|
|
195
|
+
'MSFT':
|
|
196
|
+
{
|
|
197
|
+
'ticker': 'MSFT',
|
|
198
|
+
'longName': 'Microsoft Corporation',
|
|
199
|
+
'divYield': 0.0079
|
|
200
|
+
},
|
|
201
|
+
'MSTR':
|
|
202
|
+
{
|
|
203
|
+
'ticker': 'MSTR',
|
|
204
|
+
'longName': 'MicroStrategy Incorporated',
|
|
205
|
+
'divYield': 0.0
|
|
206
|
+
},
|
|
207
|
+
'MU':
|
|
208
|
+
{
|
|
209
|
+
'ticker': 'MU',
|
|
210
|
+
'longName': 'Micron Technology, Inc.',
|
|
211
|
+
'divYield': 0.0071
|
|
212
|
+
},
|
|
213
|
+
# 'NDX':
|
|
214
|
+
# {
|
|
215
|
+
# 'ticker': '^NDX',
|
|
216
|
+
# 'longName': 'Nasdaq 100',
|
|
217
|
+
# 'divYield': 0.0098
|
|
218
|
+
# },
|
|
219
|
+
'NFLX':
|
|
220
|
+
{
|
|
221
|
+
'ticker': 'NFLX',
|
|
222
|
+
'longName': 'Netflix, Inc.',
|
|
223
|
+
'divYield': 0.0
|
|
224
|
+
},
|
|
225
|
+
'NIO':
|
|
226
|
+
{
|
|
227
|
+
'ticker': 'NIO',
|
|
228
|
+
'longName': 'NIO Inc.',
|
|
229
|
+
'divYield': 0.0
|
|
230
|
+
},
|
|
231
|
+
'NVDA':
|
|
232
|
+
{
|
|
233
|
+
'ticker': 'NVDA',
|
|
234
|
+
'longName': 'NVIDIA Corporation',
|
|
235
|
+
'divYield': 0.0003
|
|
236
|
+
},
|
|
237
|
+
'PFE':
|
|
238
|
+
{
|
|
239
|
+
'ticker': 'PFE',
|
|
240
|
+
'longName': 'Pfizer Inc.',
|
|
241
|
+
'divYield': 0.0644
|
|
242
|
+
},
|
|
243
|
+
'PLTR':
|
|
244
|
+
{
|
|
245
|
+
'ticker': 'PLTR',
|
|
246
|
+
'longName': 'Palantir Technologies Inc.',
|
|
247
|
+
'divYield': 0.0
|
|
248
|
+
},
|
|
249
|
+
'QQQ':
|
|
250
|
+
{
|
|
251
|
+
'ticker': 'QQQ',
|
|
252
|
+
'longName': 'Invesco QQQ Trust',
|
|
253
|
+
'divYield': 0.0056
|
|
254
|
+
},
|
|
255
|
+
'SLV':
|
|
256
|
+
{
|
|
257
|
+
'ticker': 'SLV',
|
|
258
|
+
'longName': 'iShares Silver Trust',
|
|
259
|
+
'divYield': 0.0
|
|
260
|
+
},
|
|
261
|
+
'SMCI':
|
|
262
|
+
{
|
|
263
|
+
'ticker': 'SMCI',
|
|
264
|
+
'longName': 'Super Micro Computer, Inc.',
|
|
265
|
+
'divYield': 0.0
|
|
266
|
+
},
|
|
267
|
+
'SNOW':
|
|
268
|
+
{
|
|
269
|
+
'ticker': 'SNOW',
|
|
270
|
+
'longName': 'Snowflake Inc.',
|
|
271
|
+
'divYield': 0.0
|
|
272
|
+
},
|
|
273
|
+
'SOFI':
|
|
274
|
+
{
|
|
275
|
+
'ticker': 'SOFI',
|
|
276
|
+
'longName': 'SoFi Technologies, Inc.',
|
|
277
|
+
'divYield': 0.0
|
|
278
|
+
},
|
|
279
|
+
'SOUN':
|
|
280
|
+
{
|
|
281
|
+
'ticker': 'SOUN',
|
|
282
|
+
'longName': 'SoundHound AI, Inc.',
|
|
283
|
+
'divYield': 0.0
|
|
284
|
+
},
|
|
285
|
+
'SOXL':
|
|
286
|
+
{
|
|
287
|
+
'ticker': 'SOXL',
|
|
288
|
+
'longName': 'Direxion Daily Semiconductor Bull 3x Shares',
|
|
289
|
+
'divYield': 0.0114
|
|
290
|
+
},
|
|
291
|
+
'SPX':
|
|
292
|
+
{
|
|
293
|
+
'ticker': '^SPX',
|
|
294
|
+
'longName': 'S&P 500 Index',
|
|
295
|
+
'divYield': 0.0122
|
|
296
|
+
},
|
|
297
|
+
'SPY':
|
|
298
|
+
{
|
|
299
|
+
'ticker': 'SPY',
|
|
300
|
+
'longName': 'SPDR S&P 500 ETF Trust',
|
|
301
|
+
'divYield': 0.0122
|
|
302
|
+
},
|
|
303
|
+
'TGT':
|
|
304
|
+
{
|
|
305
|
+
'ticker': 'TGT',
|
|
306
|
+
'longName': 'Target Corporation',
|
|
307
|
+
'divYield': 0.0316
|
|
308
|
+
},
|
|
309
|
+
'T':
|
|
310
|
+
{
|
|
311
|
+
'ticker': 'T',
|
|
312
|
+
'longName': 'AT&T Inc.',
|
|
313
|
+
'divYield': 0.0417
|
|
314
|
+
},
|
|
315
|
+
'TLT':
|
|
316
|
+
{
|
|
317
|
+
'ticker': 'TLT',
|
|
318
|
+
'longName': 'iShares 20+ Year Treasury Bond ETF',
|
|
319
|
+
'divYield': 0.0439
|
|
320
|
+
},
|
|
321
|
+
'TQQQ':
|
|
322
|
+
{
|
|
323
|
+
'ticker': 'TQQQ',
|
|
324
|
+
'longName': 'ProShares UltraPro QQQ',
|
|
325
|
+
'divYield': 0.0131
|
|
326
|
+
},
|
|
327
|
+
'TSLA':
|
|
328
|
+
{
|
|
329
|
+
'ticker': 'TSLA',
|
|
330
|
+
'longName': 'Tesla, Inc.',
|
|
331
|
+
'divYield': 0.0
|
|
332
|
+
},
|
|
333
|
+
'TSLL':
|
|
334
|
+
{
|
|
335
|
+
'ticker': 'TSLL',
|
|
336
|
+
'longName': 'Direxion Daily TSLA Bull 2X Shares',
|
|
337
|
+
'divYield': 0.0263
|
|
338
|
+
},
|
|
339
|
+
'UBER':
|
|
340
|
+
{
|
|
341
|
+
'ticker': 'UBER',
|
|
342
|
+
'longName': 'Uber Technologies, Inc.',
|
|
343
|
+
'divYield': 0.0
|
|
344
|
+
},
|
|
345
|
+
'UVXY':
|
|
346
|
+
{
|
|
347
|
+
'ticker': 'UVXY',
|
|
348
|
+
'longName': 'ProShares Ultra VIX Short-Term Futures ETF',
|
|
349
|
+
'divYield': 0.0
|
|
350
|
+
},
|
|
351
|
+
'VALE':
|
|
352
|
+
{
|
|
353
|
+
'ticker': 'VALE',
|
|
354
|
+
'longName': 'Vale S.A.',
|
|
355
|
+
'divYield': 0.1518
|
|
356
|
+
},
|
|
357
|
+
'VZ':
|
|
358
|
+
{
|
|
359
|
+
'ticker': 'VZ',
|
|
360
|
+
'longName': 'Verizon Communications Inc.',
|
|
361
|
+
'divYield': 0.063
|
|
362
|
+
},
|
|
363
|
+
'WMT':
|
|
364
|
+
{
|
|
365
|
+
'ticker': 'WMT',
|
|
366
|
+
'longName': 'Walmart Inc.',
|
|
367
|
+
'divYield': 0.0089
|
|
368
|
+
},
|
|
369
|
+
# 'WOLF':
|
|
370
|
+
# {
|
|
371
|
+
# 'ticker': 'WOLF',
|
|
372
|
+
# 'longName': 'Wolfspeed, Inc.',
|
|
373
|
+
# 'divYield': 0.0
|
|
374
|
+
# },
|
|
375
|
+
'XBI':
|
|
376
|
+
{
|
|
377
|
+
'ticker': 'XBI',
|
|
378
|
+
'longName': 'SPDR S&P BIOTECH ETF',
|
|
379
|
+
'divYield': 0.0015
|
|
380
|
+
},
|
|
381
|
+
'XLB':
|
|
382
|
+
{
|
|
383
|
+
'ticker': 'XLB',
|
|
384
|
+
'longName': 'Materials Select Sector SPDR Fund',
|
|
385
|
+
'divYield': 0.0194
|
|
386
|
+
},
|
|
387
|
+
'XLC':
|
|
388
|
+
{
|
|
389
|
+
'ticker': 'XLC',
|
|
390
|
+
'longName': 'Communication Services Select Sector SPDR Fund',
|
|
391
|
+
'divYield': 0.01
|
|
392
|
+
},
|
|
393
|
+
'XLE':
|
|
394
|
+
{
|
|
395
|
+
'ticker': 'XLE',
|
|
396
|
+
'longName': 'Energy Select Sector SPDR Fund',
|
|
397
|
+
'divYield': 0.0325
|
|
398
|
+
},
|
|
399
|
+
'XLF':
|
|
400
|
+
{
|
|
401
|
+
'ticker': 'XLF',
|
|
402
|
+
'longName': 'Financial Select Sector SPDR Fund',
|
|
403
|
+
'divYield': 0.0145
|
|
404
|
+
},
|
|
405
|
+
'XLI':
|
|
406
|
+
{
|
|
407
|
+
'ticker': 'XLI',
|
|
408
|
+
'longName': 'Industrial Select Sector SPDR Fund',
|
|
409
|
+
'divYield': 0.0145
|
|
410
|
+
},
|
|
411
|
+
'XLK':
|
|
412
|
+
{
|
|
413
|
+
'ticker': 'XLK',
|
|
414
|
+
'longName': 'Technology Select Sector SPDR Fund',
|
|
415
|
+
'divYield': 0.0067
|
|
416
|
+
},
|
|
417
|
+
'XLP':
|
|
418
|
+
{
|
|
419
|
+
'ticker': 'XLP',
|
|
420
|
+
'longName': 'Consumer Staples Select Sector SPDR Fund',
|
|
421
|
+
'divYield': 0.0285
|
|
422
|
+
},
|
|
423
|
+
'XLRE':
|
|
424
|
+
{
|
|
425
|
+
'ticker': 'XLRE',
|
|
426
|
+
'longName': 'Real Estate Select Sector SPDR Fund',
|
|
427
|
+
'divYield': 0.0356
|
|
428
|
+
},
|
|
429
|
+
'XLU':
|
|
430
|
+
{
|
|
431
|
+
'ticker': 'XLU',
|
|
432
|
+
'longName': 'Utilities Select Sector SPDR Fund',
|
|
433
|
+
'divYield': 0.0297
|
|
434
|
+
},
|
|
435
|
+
'XLV':
|
|
436
|
+
{
|
|
437
|
+
'ticker': 'XLV',
|
|
438
|
+
'longName': 'Health Care Select Sector SPDR Fund',
|
|
439
|
+
'divYield': 0.0164
|
|
440
|
+
},
|
|
441
|
+
'XLY':
|
|
442
|
+
{
|
|
443
|
+
'ticker': 'XLY',
|
|
444
|
+
'longName': 'Consumer Discretionary Select Sector SPDR Fund',
|
|
445
|
+
'divYield': 0.0073
|
|
446
|
+
},
|
|
447
|
+
'XOM':
|
|
448
|
+
{
|
|
449
|
+
'ticker': 'XOM',
|
|
450
|
+
'longName': 'Exxon Mobil Corporation',
|
|
451
|
+
'divYield': 0.038
|
|
452
|
+
}
|
|
453
|
+
},
|
|
454
|
+
'USER_AGENTS': [
|
|
455
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 "
|
|
456
|
+
"Safari/537.36",
|
|
457
|
+
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
|
|
458
|
+
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
|
|
459
|
+
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 '
|
|
460
|
+
'Safari/537.36'
|
|
461
|
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 "
|
|
462
|
+
"Safari/537.36",
|
|
463
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 "
|
|
464
|
+
"Safari/537.36",
|
|
465
|
+
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
|
|
466
|
+
],
|
|
467
|
+
'request_headers': {
|
|
468
|
+
"accept": "*/*",
|
|
469
|
+
"accept-encoding": "gzip, deflate, br",
|
|
470
|
+
"accept-language": "en-US,en;q=0.9",
|
|
471
|
+
"origin": "https://finance.yahoo.com",
|
|
472
|
+
"referer": "https://finance.yahoo.com",
|
|
473
|
+
"sec-fetch-dest": "empty",
|
|
474
|
+
"sec-fetch-mode": "cors",
|
|
475
|
+
"sec-fetch-site": "same-site",
|
|
476
|
+
}
|
|
477
|
+
}
|
volbatch/volbatch.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Volatility surface calculation and batch processing module.
|
|
3
|
+
|
|
4
|
+
This module provides functionality for calculating volatility surfaces
|
|
5
|
+
for financial instruments, processing multiple tickers in batch mode,
|
|
6
|
+
integrating dividend yields, and generating skew data for analysis.
|
|
7
|
+
Results can be saved as structured JSON files for further analysis.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import random
|
|
12
|
+
from time import sleep
|
|
13
|
+
from typing import Dict, Any, Optional
|
|
14
|
+
|
|
15
|
+
from volbatch.data import VolBatchData
|
|
16
|
+
from volbatch.transform import VolBatchTransform
|
|
17
|
+
from volbatch.utils import NanConverter
|
|
18
|
+
from volbatch.vol_params import vol_params
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class VolBatch(VolBatchData, VolBatchTransform):
|
|
22
|
+
"""
|
|
23
|
+
Batch processor for volatility surface calculations across multiple securities.
|
|
24
|
+
"""
|
|
25
|
+
def __init__(self, **kwargs: Any) -> None:
|
|
26
|
+
"""
|
|
27
|
+
Initialize the VolBatch class with parameters for volatility calculation.
|
|
28
|
+
"""
|
|
29
|
+
self.params: Dict[str, Any] = vol_params.copy()
|
|
30
|
+
self.params.update(kwargs)
|
|
31
|
+
self.voldata = {}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def process_batch(self) -> None:
|
|
35
|
+
"""
|
|
36
|
+
Process a batch of tickers and save the results to JSON files.
|
|
37
|
+
"""
|
|
38
|
+
for key, value in self.params['tickerMap'].items():
|
|
39
|
+
print(f"Processing ticker: {key}")
|
|
40
|
+
try:
|
|
41
|
+
if self.params['divs']:
|
|
42
|
+
# Use the static method but store the result back to self.params
|
|
43
|
+
self.params = self.get_div_yields(self.params)
|
|
44
|
+
vol_surface = self.get_vol_data_with_divs(
|
|
45
|
+
ticker=value['ticker'],
|
|
46
|
+
div_yield=self.params['div_map'][key],
|
|
47
|
+
interest_rate=self.params['interest_rate'],
|
|
48
|
+
start_date=self.params['start_date'],
|
|
49
|
+
skew_tenors=self.params['skew_tenors']
|
|
50
|
+
)
|
|
51
|
+
else:
|
|
52
|
+
vol_surface = self.get_vol_data(
|
|
53
|
+
ticker=value['ticker'],
|
|
54
|
+
start_date=self.params['start_date'],
|
|
55
|
+
discount_type=self.params['discount_type'],
|
|
56
|
+
skew_tenors=self.params['skew_tenors']
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
if vol_surface is None:
|
|
60
|
+
print(f"Processing for {key} timed out or failed, skipping to next ticker")
|
|
61
|
+
continue
|
|
62
|
+
|
|
63
|
+
jsonstring = json.dumps(vol_surface, cls=NanConverter)
|
|
64
|
+
voldata = json.loads(jsonstring)
|
|
65
|
+
filename = key + '.json'
|
|
66
|
+
|
|
67
|
+
if self.params['save']:
|
|
68
|
+
with open(filename, "w") as fp:
|
|
69
|
+
json.dump(voldata, fp, cls=NanConverter)
|
|
70
|
+
|
|
71
|
+
print(f"Successfully processed ticker: {key}")
|
|
72
|
+
|
|
73
|
+
except Exception as e:
|
|
74
|
+
print(f"Error processing ticker {key}: {str(e)}")
|
|
75
|
+
|
|
76
|
+
# Random pause between tickers to avoid rate limiting
|
|
77
|
+
sleep_time = random.randint(6, 15)
|
|
78
|
+
print(f"Pausing for {sleep_time} seconds before next ticker")
|
|
79
|
+
sleep(sleep_time)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def process_single_ticker(self) -> None:
|
|
83
|
+
"""
|
|
84
|
+
Process a single ticker specified in self.params['ticker'].
|
|
85
|
+
"""
|
|
86
|
+
raw_ticker = self.params['ticker']
|
|
87
|
+
clean_ticker = raw_ticker.replace('^', '')
|
|
88
|
+
try:
|
|
89
|
+
if self.params['divs']:
|
|
90
|
+
# Use the static method but store the result back to self.params
|
|
91
|
+
self.params = self.get_div_yields(self.params)
|
|
92
|
+
vol_surface = self.get_vol_data_with_divs(
|
|
93
|
+
ticker=self.params['ticker'],
|
|
94
|
+
div_yield=self.params['div_map'][clean_ticker],
|
|
95
|
+
interest_rate=self.params['interest_rate'],
|
|
96
|
+
start_date=self.params['start_date'],
|
|
97
|
+
skew_tenors=self.params['skew_tenors']
|
|
98
|
+
)
|
|
99
|
+
else:
|
|
100
|
+
vol_surface = self.get_vol_data(
|
|
101
|
+
ticker=self.params['ticker'],
|
|
102
|
+
start_date=self.params['start_date'],
|
|
103
|
+
discount_type=self.params['discount_type'],
|
|
104
|
+
skew_tenors=self.params['skew_tenors']
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
if vol_surface is None:
|
|
108
|
+
print(f"Processing for {self.params['ticker']} timed out or failed")
|
|
109
|
+
return
|
|
110
|
+
|
|
111
|
+
jsonstring = json.dumps(vol_surface, cls=NanConverter)
|
|
112
|
+
voldata = json.loads(jsonstring)
|
|
113
|
+
self.voldata = voldata
|
|
114
|
+
|
|
115
|
+
filename = clean_ticker + '.json'
|
|
116
|
+
if self.params['save']:
|
|
117
|
+
self.save_vol_data(filename)
|
|
118
|
+
|
|
119
|
+
except Exception as e:
|
|
120
|
+
print(f"Error processing ticker {self.params['ticker']}: {str(e)}")
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def save_vol_data(self, filename: Optional[str] = None) -> None:
|
|
124
|
+
"""
|
|
125
|
+
Save volatility data to a JSON file.
|
|
126
|
+
"""
|
|
127
|
+
if filename is None:
|
|
128
|
+
filename = self.params['ticker'] + '.json'
|
|
129
|
+
|
|
130
|
+
assert filename is not None # Type guard for static type checkers
|
|
131
|
+
|
|
132
|
+
if hasattr(self, 'voldata'):
|
|
133
|
+
with open(filename, "w") as fp:
|
|
134
|
+
json.dump(self.voldata, fp, cls=NanConverter)
|
|
135
|
+
print("Data saved as", filename)
|
|
136
|
+
else:
|
|
137
|
+
print("No vol data to save")
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: volbatch
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Generate volatility surface data from option prices and output the results in JSON format.
|
|
5
|
+
Home-page: https://github.com/GBERESEARCH/volbatch
|
|
6
|
+
Author: GBERESEARCH
|
|
7
|
+
Author-email: gberesearch@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: numpy>=2.2.3
|
|
12
|
+
Requires-Dist: pandas>=2.2.3
|
|
13
|
+
Requires-Dist: requests>=2.32.3
|
|
14
|
+
Requires-Dist: volvisdata>=1.0.9
|
|
15
|
+
Requires-Dist: voldiscount>=0.0.2
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
## Volatility Surface Generator
|
|
19
|
+
|
|
20
|
+
### Python application to generate volatility surface data from option prices and output the results in JSON format.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
volbatch/__init__.py,sha256=ugyuFliEqtAwQmH4sTlc16YXKYbFWDmfyk87fErB8-8,21
|
|
2
|
+
volbatch/data.py,sha256=8C9YZFkzUlCCZF4GnmetHR9aOzgBYWZvUPWaFlmWnjA,6253
|
|
3
|
+
volbatch/transform.py,sha256=eacMre-RwGSsjpUTwp1BTkSR1BA8tcHyajdo_grjr-k,3898
|
|
4
|
+
volbatch/utils.py,sha256=j_JYpVNt6L_MlvQg-xmpKqFiKELxtBaawC2QOkfdaf8,7330
|
|
5
|
+
volbatch/vol_params.py,sha256=mrI_i1jlj1dILoj99YLw3z_03Hz2XT0Jn-3TVI_666s,13472
|
|
6
|
+
volbatch/volbatch.py,sha256=F-Qe4uYIskvFKchQ8fE3-D28mLa9J3yNb0WbPzvDDHc,5411
|
|
7
|
+
volbatch-0.0.1.dist-info/licenses/LICENSE,sha256=lk8g9lHsRWXnmOXouRFZX1xTi0vlAicp8wS824c_esE,1089
|
|
8
|
+
volbatch-0.0.1.dist-info/METADATA,sha256=AEcwPhBfoYajodfiCvYvDU3lDi1YZ2LMF0yrmVgi6Aw,684
|
|
9
|
+
volbatch-0.0.1.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
|
10
|
+
volbatch-0.0.1.dist-info/top_level.txt,sha256=3Fu2bLmzFHpx11UCmkcGzI5Nc4Awp24D2V7vijheXgo,9
|
|
11
|
+
volbatch-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 GBERESEARCH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
volbatch
|