greeks-package 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.

Potentially problematic release.


This version of greeks-package might be problematic. Click here for more details.

Greeks/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ from .download_options import download_options
2
+ from .greeks import (
3
+ vanna, volga, charm, veta, color, speed, ultima, zomma,
4
+ first_order, second_order, third_order, greeks
5
+ )
6
+ from .black_scholes_utils import compute_d1, compute_d2, compute_d1_d2
7
+
8
+ __all__ = [
9
+ "download_options",
10
+ "vanna", "volga", "charm", "veta", "color", "speed", "ultima", "zomma",
11
+ "first_order", "second_order", "third_order", "greeks",
12
+ "compute_d1", "compute_d2", "compute_d1_d2"
13
+ ]
Greeks/main.py ADDED
@@ -0,0 +1,780 @@
1
+ from py_vollib.black_scholes.greeks.analytical import delta, gamma, vega, theta, rho
2
+ import pandas as pd
3
+ import yfinance as yf
4
+ import numpy as np
5
+ from datetime import datetime, timedelta
6
+ from scipy.stats import norm
7
+ import warnings
8
+ import yfinance as yf
9
+ import pandas as pd
10
+ from datetime import datetime
11
+
12
+ # Suppress all warnings (optional, but not recommended for debugging)
13
+ warnings.simplefilter(action='ignore', category=FutureWarning)
14
+
15
+ def download_options(
16
+ ticker_symbol,
17
+ opt_type='c',
18
+ max_days=60,
19
+ lower_moneyness=0.95,
20
+ upper_moneyness=1.05,
21
+ price=False # New optional parameter
22
+ ):
23
+ """
24
+ Downloads and filters option chains for a given ticker according to:
25
+ 1. Option type (calls or puts)
26
+ 2. Maximum days to expiration
27
+ 3. Moneyness bounds
28
+ 4. Optionally includes the stock price in each row (useful for ITM/OTM visualization).
29
+
30
+ Parameters:
31
+ ticker_symbol (str): The stock ticker.
32
+ opt_type (str, optional): 'c' for calls, 'p' for puts (default: 'c').
33
+ max_days (int, optional): Max days until expiration (default: 60).
34
+ lower_moneyness (float, optional): Lower bound for moneyness (default: 0.95).
35
+ upper_moneyness (float, optional): Upper bound for moneyness (default: 1.05).
36
+ price (bool, optional): If True, adds a 'Stock Price' column with the current stock price.
37
+
38
+ Returns:
39
+ pd.DataFrame: Filtered options chain.
40
+ """
41
+
42
+ # Retrieve the ticker data from yfinance
43
+ ticker = yf.Ticker(ticker_symbol)
44
+
45
+ # Grab the current underlying price
46
+ underlying_price = ticker.history(period="1d")['Close'].iloc[-1]
47
+
48
+ # Calculate the strike range using the specified moneyness
49
+ lower_strike = underlying_price * lower_moneyness
50
+ upper_strike = underlying_price * upper_moneyness
51
+
52
+ # Prepare a DataFrame to hold all filtered data
53
+ relevant_columns = [
54
+ 'contractSymbol',
55
+ 'inTheMoney',
56
+ 'strike',
57
+ 'lastPrice',
58
+ 'bid',
59
+ 'ask',
60
+ 'volume',
61
+ 'openInterest',
62
+ 'impliedVolatility'
63
+ ]
64
+ filtered_options = pd.DataFrame(columns=relevant_columns + ['expiry'])
65
+
66
+ # Loop through each available expiration date, filtering by max_days
67
+ for expiry_date_str in ticker.options:
68
+ expiry_date = pd.to_datetime(expiry_date_str)
69
+ days_to_expiry = (expiry_date - datetime.now()).days
70
+
71
+ if days_to_expiry <= max_days:
72
+ # Retrieve calls or puts for the given expiration
73
+ option_chain = ticker.option_chain(expiry_date_str)
74
+ if opt_type.lower() == 'c':
75
+ data = option_chain.calls
76
+ elif opt_type.lower() == 'p':
77
+ data = option_chain.puts
78
+ else:
79
+ continue
80
+
81
+ # Filter by strike based on moneyness
82
+ data = data[(data['strike'] >= lower_strike) & (data['strike'] <= upper_strike)].copy()
83
+
84
+ # Attach an expiry column
85
+ data['expiry'] = expiry_date
86
+
87
+ # Concatenate only if data is non-empty
88
+ if not data.empty:
89
+ data = data[relevant_columns + ['expiry']]
90
+ filtered_options = pd.concat([filtered_options, data], ignore_index=True)
91
+
92
+ # Calculate Days to Expiry for each row
93
+ filtered_options['Days to Expiry'] = (
94
+ pd.to_datetime(filtered_options['expiry']) - datetime.now()
95
+ ).dt.days
96
+
97
+ # Calculate a Mid-Point price from bid and ask
98
+ filtered_options['Mid-Point Price'] = round((filtered_options['bid'] + filtered_options['ask']) / 2, 4)
99
+
100
+ filtered_options['impliedVolatility'] = filtered_options['impliedVolatility'].round(2)
101
+
102
+ # If include_stock_price is True, add a 'Stock Price' column
103
+ if price:
104
+ filtered_options['Stock Price'] = round(underlying_price, 4)
105
+
106
+ return filtered_options
107
+
108
+ filtered_options = download_options('AAPL', opt_type='c', max_days=60, lower_moneyness=0.95, upper_moneyness=1.05, price = True)
109
+ #D1 & D2
110
+ def compute_d1(S, K, t, r, sigma, epsilon=1e-9):
111
+ t = max(t, epsilon) # This line and the following need to be indented
112
+ return (np.log(S / K) + (r + 0.5 * sigma ** 2) * t) / (sigma * np.sqrt(t))
113
+
114
+ def compute_d2(S, K, t, r, sigma, epsilon=1e-9):
115
+ return compute_d1(S, K, t, r, sigma, epsilon) - sigma * np.sqrt(t)
116
+
117
+ def compute_d1_d2(S, K, t, r, sigma, epsilon=1e-9):
118
+ t = max(t, epsilon)
119
+ d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * t) / (sigma * np.sqrt(t))
120
+ return d1, d1 - sigma * np.sqrt(t)
121
+
122
+ import numpy as np
123
+ import yfinance as yf
124
+ import pandas as pd
125
+ from scipy.stats import norm
126
+
127
+ def vanna(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
128
+ """
129
+ Computes Vanna (sensitivity of Vega to volatility) for a single row of an options DataFrame.
130
+
131
+ Vanna measures the rate of change of Vega with respect to changes in the underlying price.
132
+ It is important in managing risk when trading volatility-sensitive strategies.
133
+
134
+ Parameters:
135
+ row (pd.Series): A row from the options DataFrame containing:
136
+ - 'strike' (float): Strike price of the option.
137
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
138
+ - 'Days to Expiry' (int): Number of days until expiration.
139
+ ticker (str): Ticker symbol for the underlying stock.
140
+ r (float, optional): Risk-free interest rate (default 0.05).
141
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
142
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
143
+
144
+ Returns:
145
+ pd.Series: Contains Vanna, d1, and d2 values.
146
+
147
+ Formula:
148
+ Vanna = e^(-rT) * N'(d1) * (d2 / sigma)
149
+
150
+ Notes:
151
+ - This function retrieves the latest stock price using Yahoo Finance.
152
+ - Uses the Black-Scholes model assumptions.
153
+ - Assumes continuous compounding for risk-free rate.
154
+ """
155
+ # Fetch latest stock price
156
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
157
+
158
+ # Extract option details
159
+ K = row['strike'] # Strike price
160
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
161
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
162
+
163
+ # Validate inputs
164
+ if pd.isna(S) or pd.isna(K) or pd.isna(sigma) or S <= 0 or sigma <= 0:
165
+ return pd.Series({'Vanna': float('nan'), 'd1': float('nan'), 'd2': float('nan')})
166
+
167
+ # Compute d1 and d2
168
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
169
+
170
+ # Compute normal PDF of d1
171
+ N_prime_d1 = norm.pdf(d1)
172
+
173
+ # Compute Vanna using the correct formula
174
+ vanna_val = np.exp(-r * T) * N_prime_d1 * (d2 / sigma)
175
+
176
+ return round(vanna_val, 4)
177
+
178
+ import numpy as np
179
+ import yfinance as yf
180
+ import pandas as pd
181
+ from scipy.stats import norm
182
+
183
+ def volga(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
184
+ """
185
+ Computes Volga (sensitivity of Vega to volatility) for a single row of an options DataFrame.
186
+
187
+ Volga measures how Vega changes with respect to volatility. It helps quantify how sensitive
188
+ an option's price is to second-order volatility effects.
189
+
190
+ Parameters:
191
+ row (pd.Series): A row from the options DataFrame containing:
192
+ - 'strike' (float): Strike price of the option.
193
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
194
+ - 'Days to Expiry' (int): Number of days until expiration.
195
+ ticker (str): Ticker symbol for the underlying stock.
196
+ r (float, optional): Risk-free interest rate (default 0.05).
197
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
198
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
199
+
200
+ Returns:
201
+ float: Computed Volga value rounded to four decimal places.
202
+
203
+ Formula:
204
+ Volga = Vega * (d1 * d2) / sigma
205
+
206
+ Notes:
207
+ - This function retrieves the latest stock price using Yahoo Finance.
208
+ - Uses the Black-Scholes model assumptions.
209
+ - Assumes continuous compounding for risk-free rate.
210
+ """
211
+ # Fetch latest stock price
212
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
213
+
214
+ # Extract option details
215
+ K = row['strike'] # Strike price
216
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
217
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
218
+
219
+ # Compute d1 and d2
220
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
221
+
222
+ # Compute Vega using py_vollib or a custom implementation
223
+ vega_val = vega(option_type, S, K, T, r, sigma)
224
+
225
+ # Compute Volga using the refined formula
226
+ volga_val = vega_val * (d1 * d2) / sigma
227
+
228
+ return round(volga_val, 4)
229
+
230
+ import numpy as np
231
+ import yfinance as yf
232
+ import pandas as pd
233
+ from scipy.stats import norm
234
+
235
+ def charm(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
236
+ """
237
+ Computes Charm (Delta decay) for a single row of an options DataFrame.
238
+
239
+ Charm measures how Delta changes with respect to time, representing the rate at which
240
+ Delta decays as expiration approaches. This is crucial for managing directional risk in options trading.
241
+
242
+ Parameters:
243
+ row (pd.Series): A row from the options DataFrame containing:
244
+ - 'strike' (float): Strike price of the option.
245
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
246
+ - 'Days to Expiry' (int): Number of days until expiration.
247
+ ticker (str): Ticker symbol for the underlying stock.
248
+ r (float, optional): Risk-free interest rate (default 0.05).
249
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
250
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
251
+
252
+ Returns:
253
+ float: Computed Charm value rounded to four decimal places.
254
+
255
+ Formula:
256
+ Charm = -N'(d1) * (2 * r * T - d2 * sigma * sqrt(T)) / (2 * T * sigma * sqrt(T))
257
+
258
+ Notes:
259
+ - This function retrieves the latest stock price using Yahoo Finance.
260
+ - Uses the Black-Scholes model assumptions.
261
+ - Assumes continuous compounding for risk-free rate.
262
+ """
263
+ # Fetch latest stock price
264
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
265
+
266
+ # Extract option details
267
+ K = row['strike'] # Strike price
268
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
269
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
270
+
271
+ # Compute d1 and d2
272
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
273
+
274
+ # Compute normal PDF of d1
275
+ N_prime_d1 = norm.pdf(d1) # Equivalent to (1 / sqrt(2π)) * exp(-0.5 * d1^2)
276
+
277
+ # Compute Charm using the correct formula
278
+ charm_value = -N_prime_d1 * (2 * r * T - d2 * sigma * np.sqrt(T)) / (2 * T)
279
+
280
+ return round(charm_value, 4)
281
+
282
+ import numpy as np
283
+ import yfinance as yf
284
+ import pandas as pd
285
+ from scipy.stats import norm
286
+
287
+ def veta(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
288
+ """
289
+ Computes Veta (sensitivity of Vega to time decay) for a single row of an options DataFrame.
290
+
291
+ Veta measures the rate at which Vega changes as time passes, indicating how an option's sensitivity
292
+ to volatility changes with time.
293
+
294
+ Parameters:
295
+ row (pd.Series): A row from the options DataFrame containing:
296
+ - 'strike' (float): Strike price of the option.
297
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
298
+ - 'Days to Expiry' (int): Number of days until expiration.
299
+ ticker (str): Ticker symbol for the underlying stock.
300
+ r (float, optional): Risk-free interest rate (default 0.05).
301
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
302
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
303
+
304
+ Returns:
305
+ float: Computed Veta value rounded to four decimal places.
306
+
307
+ Formula:
308
+ Veta = vega_val * np.exp(-r * T) * norm.pdf(d1) * np.sqrt(T) * (r - d1 / (2 * T)) / sigma
309
+
310
+ Notes:
311
+ - This function retrieves the latest stock price using Yahoo Finance.
312
+ - Uses the Black-Scholes model assumptions.
313
+ - Assumes continuous compounding for risk-free rate.
314
+ """
315
+ # Fetch latest stock price
316
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
317
+ K = row['strike']
318
+ T = max(row['Days to Expiry'] / 365, epsilon)
319
+ sigma = max(row['impliedVolatility'], 0.01)
320
+
321
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
322
+ vega_val = vega(option_type, S, K, T, r, sigma)
323
+
324
+ # More detailed Veta calculation incorporating interest rate changes
325
+ interest_rate_term = (r - d1 / (2 * T)) / sigma
326
+ veta_val = vega_val * np.exp(-r * T) * norm.pdf(d1) * np.sqrt(T) * interest_rate_term
327
+
328
+ return round(veta_val, 4)
329
+
330
+ """**THIRD DERIVATIVES**"""
331
+
332
+ import numpy as np
333
+ import yfinance as yf
334
+ import pandas as pd
335
+ from scipy.stats import norm
336
+
337
+ def color(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
338
+ """
339
+ Computes Color (Gamma decay) for a single row of an options DataFrame.
340
+
341
+ Color measures how Gamma changes as time passes, indicating how the convexity of an option’s
342
+ Delta shifts with time. It is crucial for managing second-order sensitivity to underlying price changes.
343
+
344
+ Parameters:
345
+ row (pd.Series): A row from the options DataFrame containing:
346
+ - 'strike' (float): Strike price of the option.
347
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
348
+ - 'Days to Expiry' (int): Number of days until expiration.
349
+ ticker (str): Ticker symbol for the underlying stock.
350
+ r (float, optional): Risk-free interest rate (default 0.05).
351
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
352
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
353
+
354
+ Returns:
355
+ float: Computed Color value rounded to four decimal places.
356
+
357
+ Formula:
358
+ Color = (N'(d1) / (2 * S * T * sigma * sqrt(T))) * (2 * r * T + 1 - d1 * d2)
359
+
360
+ Notes:
361
+ - This function retrieves the latest stock price using Yahoo Finance.
362
+ - Uses the Black-Scholes model assumptions.
363
+ - Assumes continuous compounding for risk-free rate.
364
+ """
365
+ # Fetch latest stock price
366
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
367
+
368
+ # Extract option details
369
+ K = row['strike'] # Strike price
370
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
371
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
372
+
373
+ # Compute d1 and d2
374
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
375
+
376
+ # Compute normal PDF of d1
377
+ N_prime_d1 = norm.pdf(d1) # Equivalent to (1 / sqrt(2π)) * exp(-0.5 * d1^2)
378
+
379
+ # Compute Color using refined formula
380
+ color_value = (N_prime_d1 / (2 * S * T * sigma * np.sqrt(T))) * (2 * r * T + 1 - d1 * d2)
381
+
382
+ return round(color_value, 4)
383
+
384
+ import numpy as np
385
+ import yfinance as yf
386
+ import pandas as pd
387
+ from scipy.stats import norm
388
+
389
+ def speed(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
390
+ """
391
+ Computes Speed (rate of change of Gamma) for a single row of an options DataFrame.
392
+
393
+ Speed measures how rapidly Gamma changes as the underlying price moves, representing
394
+ the third derivative of the option price with respect to the stock price. It helps
395
+ assess how stable or unstable an option's Delta and Gamma are.
396
+
397
+ Parameters:
398
+ row (pd.Series): A row from the options DataFrame containing:
399
+ - 'strike' (float): Strike price of the option.
400
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
401
+ - 'Days to Expiry' (int): Number of days until expiration.
402
+ ticker (str): Ticker symbol for the underlying stock.
403
+ r (float, optional): Risk-free interest rate (default 0.05).
404
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
405
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
406
+
407
+ Returns:
408
+ float: Computed Speed value rounded to four decimal places.
409
+
410
+ Formula:
411
+ Speed = (N'(d1) / (S^2 * sigma * sqrt(T))) * (d1 / (sigma * sqrt(T)) - 1)
412
+
413
+ Notes:
414
+ - This function retrieves the latest stock price using Yahoo Finance.
415
+ - Uses the Black-Scholes model assumptions.
416
+ - Assumes continuous compounding for risk-free rate.
417
+ """
418
+ # Fetch latest stock price
419
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
420
+
421
+ # Extract option details
422
+ K = row['strike'] # Strike price
423
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
424
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
425
+
426
+ # Compute d1 and d2
427
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
428
+
429
+ # Compute normal PDF of d1
430
+ N_prime_d1 = norm.pdf(d1) # Equivalent to (1 / sqrt(2π)) * exp(-0.5 * d1^2)
431
+
432
+ # Compute Speed using the correct formula
433
+ speed_value = (N_prime_d1 / (S ** 2 * sigma * np.sqrt(T))) * ((d1 / (sigma * np.sqrt(T))) - 1)
434
+
435
+ return round(speed_value, 4)
436
+
437
+ import numpy as np
438
+ import yfinance as yf
439
+ import pandas as pd
440
+ from scipy.stats import norm
441
+
442
+ def ultima(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
443
+ """
444
+ Computes Ultima (sensitivity of Vanna to volatility) for a single row of an options DataFrame.
445
+
446
+ Ultima measures the rate of change of Vanna with respect to changes in implied volatility.
447
+ It helps quantify how much the convexity of Vega changes as volatility shifts.
448
+
449
+ Parameters:
450
+ row (pd.Series): A row from the options DataFrame containing:
451
+ - 'strike' (float): Strike price of the option.
452
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
453
+ - 'Days to Expiry' (int): Number of days until expiration.
454
+ ticker (str): Ticker symbol for the underlying stock.
455
+ r (float, optional): Risk-free interest rate (default 0.05).
456
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
457
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
458
+
459
+ Returns:
460
+ float: Computed Ultima value rounded to four decimal places.
461
+
462
+ Formula:
463
+ Ultima = (Vega * (d1 * d2 - 1) * d1 * d2) / sigma
464
+
465
+ Notes:
466
+ - This function retrieves the latest stock price using Yahoo Finance.
467
+ - Uses the Black-Scholes model assumptions.
468
+ - Assumes continuous compounding for risk-free rate.
469
+ """
470
+ # Fetch latest stock price
471
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
472
+
473
+ # Extract option details
474
+ K = row['strike'] # Strike price
475
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
476
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
477
+
478
+ # Compute d1 and d2
479
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
480
+
481
+ # Compute Vega using py_vollib
482
+ vega_val = vega(option_type, S, K, T, r, sigma)
483
+
484
+ # Compute Ultima using refined formula
485
+ ultima_value = (vega_val * (d1 * d2 - 1) * d1 * d2) / sigma
486
+
487
+ return round(ultima_value, 4)
488
+
489
+ import numpy as np
490
+ import yfinance as yf
491
+ import pandas as pd
492
+ from scipy.stats import norm
493
+
494
+ def zomma(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> float:
495
+ """
496
+ Computes Zomma (sensitivity of Gamma to volatility) for a single row of an options DataFrame.
497
+
498
+ Zomma measures the rate of change of Gamma with respect to changes in implied volatility.
499
+ It helps quantify how much Gamma fluctuates when volatility changes.
500
+
501
+ Parameters:
502
+ row (pd.Series): A row from the options DataFrame containing:
503
+ - 'strike' (float): Strike price of the option.
504
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
505
+ - 'Days to Expiry' (int): Number of days until expiration.
506
+ ticker (str): Ticker symbol for the underlying stock.
507
+ r (float, optional): Risk-free interest rate (default 0.05).
508
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
509
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
510
+
511
+ Returns:
512
+ float: Computed Zomma value rounded to four decimal places.
513
+
514
+ Formula:
515
+ Zomma = (Gamma * (d1 * d2 - 1)) / sigma
516
+
517
+ Notes:
518
+ - This function retrieves the latest stock price using Yahoo Finance.
519
+ - Uses the Black-Scholes model assumptions.
520
+ - Assumes continuous compounding for risk-free rate.
521
+ """
522
+ # Fetch latest stock price
523
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
524
+
525
+ # Extract option details
526
+ K = row['strike'] # Strike price
527
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
528
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
529
+
530
+ # Compute d1 and d2
531
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
532
+
533
+ # Compute Gamma using py_vollib
534
+ gamma_val = gamma(option_type, S, K, T, r, sigma)
535
+
536
+ # Compute Zomma using refined formula
537
+ zomma_value = (gamma_val * (d1 * d2 - 1)) / sigma
538
+
539
+ return round(zomma_value, 4)
540
+
541
+ """Primary Functions"""
542
+
543
+ def first_order(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> pd.Series:
544
+ """
545
+ Computes all first-order Greeks (Delta, Vega, Theta, Rho)
546
+ for a single row of an options DataFrame.
547
+
548
+ This function calculates and returns the relevant first-order Greeks in a single call.
549
+
550
+ Parameters:
551
+ row (pd.Series): A row from the options DataFrame containing:
552
+ - 'strike' (float): Strike price of the option.
553
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
554
+ - 'Days to Expiry' (int): Number of days until expiration.
555
+ ticker (str): Ticker symbol for the underlying stock.
556
+ r (float, optional): Risk-free interest rate (default 0.05).
557
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
558
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
559
+
560
+ Returns:
561
+ pd.Series: A Pandas Series containing all first-order Greeks.
562
+
563
+ Notes:
564
+ - This function retrieves the latest stock price using Yahoo Finance.
565
+ - Uses the Black-Scholes model assumptions.
566
+ - Assumes continuous compounding for risk-free rate.
567
+ """
568
+
569
+ # Fetch latest stock price
570
+ try:
571
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
572
+ except:
573
+ return pd.Series({'Error': 'Stock price retrieval failed'})
574
+
575
+ # Extract option details
576
+ K = row['strike']
577
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
578
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
579
+
580
+ # Validate inputs
581
+ if pd.isna(S) or pd.isna(K) or pd.isna(sigma) or S <= 0 or sigma <= 0:
582
+ return pd.Series({'Delta': float('nan'), 'Vega': float('nan'), 'Theta': float('nan'), 'Rho': float('nan')})
583
+
584
+ # Compute first-order Greeks using py_vollib
585
+ greek_values = {
586
+ 'Delta': delta(option_type, S, K, T, r, sigma),
587
+ 'Vega': vega(option_type, S, K, T, r, sigma),
588
+ 'Theta': theta(option_type, S, K, T, r, sigma),
589
+ 'Rho': rho(option_type, S, K, T, r, sigma)
590
+ }
591
+
592
+ return pd.Series({key: round(value, 4) for key, value in greek_values.items()})
593
+
594
+ def second_order(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> pd.Series:
595
+ """
596
+ Computes all second-order Greeks (Vanna, Volga, Veta, Charm, Gamma)
597
+ for a single row of an options DataFrame.
598
+
599
+ This function calculates and returns the relevant second-order Greeks in a single call.
600
+
601
+ Parameters:
602
+ row (pd.Series): A row from the options DataFrame containing:
603
+ - 'strike' (float): Strike price of the option.
604
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
605
+ - 'Days to Expiry' (int): Number of days until expiration.
606
+ ticker (str): Ticker symbol for the underlying stock.
607
+ r (float, optional): Risk-free interest rate (default 0.05).
608
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
609
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
610
+
611
+ Returns:
612
+ pd.Series: A Pandas Series containing all second-order Greeks.
613
+
614
+ Notes:
615
+ - This function retrieves the latest stock price using Yahoo Finance.
616
+ - Uses the Black-Scholes model assumptions.
617
+ - Assumes continuous compounding for risk-free rate.
618
+ """
619
+ # Fetch latest stock price
620
+ try:
621
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
622
+ except:
623
+ return pd.Series({'Error': 'Stock price retrieval failed'})
624
+
625
+ # Extract option details
626
+ K = row['strike']
627
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
628
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
629
+
630
+ # Validate inputs
631
+ if pd.isna(S) or pd.isna(K) or pd.isna(sigma) or S <= 0 or sigma <= 0:
632
+ return pd.Series({'Vanna': float('nan'), 'Volga': float('nan'), 'Veta': float('nan'),
633
+ 'Charm': float('nan'), 'Gamma': float('nan')})
634
+
635
+ # Compute d1 and d2 once
636
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
637
+
638
+ # Compute all second-order Greeks
639
+ greek_values = {
640
+ 'Vanna': vanna(row, ticker, r, option_type),
641
+ 'Volga': volga(row, ticker, r, option_type),
642
+ 'Veta': veta(row, ticker, r, option_type),
643
+ 'Charm': charm(row, ticker, r, option_type),
644
+ 'Gamma': gamma(option_type, S, K, T, r, sigma) # Gamma from py_vollib
645
+ }
646
+
647
+ return pd.Series({key: round(value, 4) for key, value in greek_values.items()})
648
+
649
+ def third_order(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> pd.Series:
650
+ """
651
+ Computes all third-order Greeks (Color, Speed, Ultima, Zomma)
652
+ for a single row of an options DataFrame.
653
+
654
+ This function calculates and returns all relevant third-order Greeks in a single call.
655
+
656
+ Parameters:
657
+ row (pd.Series): A row from the options DataFrame containing:
658
+ - 'strike' (float): Strike price of the option.
659
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
660
+ - 'Days to Expiry' (int): Number of days until expiration.
661
+ ticker (str): Ticker symbol for the underlying stock.
662
+ r (float, optional): Risk-free interest rate (default 0.05).
663
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
664
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
665
+
666
+ Returns:
667
+ pd.Series: A Pandas Series containing all third-order Greeks.
668
+
669
+ Notes:
670
+ - This function retrieves the latest stock price using Yahoo Finance.
671
+ - Uses the Black-Scholes model assumptions.
672
+ - Assumes continuous compounding for risk-free rate.
673
+ """
674
+ # Fetch latest stock price
675
+ try:
676
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
677
+ except:
678
+ return pd.Series({'Error': 'Stock price retrieval failed'})
679
+
680
+ # Extract option details
681
+ K = row['strike']
682
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
683
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
684
+
685
+ # Validate inputs
686
+ if pd.isna(S) or pd.isna(K) or pd.isna(sigma) or S <= 0 or sigma <= 0:
687
+ return pd.Series({'Color': float('nan'), 'Speed': float('nan'), 'Ultima': float('nan'), 'Zomma': float('nan')})
688
+
689
+ # Compute d1 and d2 once
690
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
691
+
692
+ # Compute all third-order Greeks
693
+ greek_values = {
694
+ 'Color': color(row, ticker, r, option_type),
695
+ 'Speed': speed(row, ticker, r, option_type),
696
+ 'Ultima': ultima(row, ticker, r, option_type),
697
+ 'Zomma': zomma(row, ticker, r, option_type)
698
+ }
699
+
700
+ return pd.Series({key: round(value, 4) for key, value in greek_values.items()})
701
+
702
+ def greeks(row: pd.Series, ticker: str, r: float = 0.05, option_type: str = 'c', epsilon: float = 1e-9) -> pd.Series:
703
+ """
704
+ Computes all Greeks (First-order, Second-order, and Third-order)
705
+ for a single row of an options DataFrame.
706
+
707
+ This function calculates and returns all relevant Greeks in a single call.
708
+
709
+ Parameters:
710
+ row (pd.Series): A row from the options DataFrame containing:
711
+ - 'strike' (float): Strike price of the option.
712
+ - 'impliedVolatility' (float): Annualized implied volatility (decimal).
713
+ - 'Days to Expiry' (int): Number of days until expiration.
714
+ ticker (str): Ticker symbol for the underlying stock.
715
+ r (float, optional): Risk-free interest rate (default 0.05).
716
+ option_type (str, optional): Option type, either call ('c') or put ('p') (default 'c').
717
+ epsilon (float, optional): Small value to avoid division by zero errors (default 1e-9).
718
+
719
+ Returns:
720
+ pd.Series: A Pandas Series containing all Greeks.
721
+
722
+ Notes:
723
+ - This function retrieves the latest stock price using Yahoo Finance.
724
+ - Uses the Black-Scholes model assumptions.
725
+ - Assumes continuous compounding for risk-free rate.
726
+ """
727
+ # Fetch latest stock price
728
+ try:
729
+ S = yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1]
730
+ except:
731
+ return pd.Series({'Error': 'Stock price retrieval failed'})
732
+
733
+ # Extract option details
734
+ K = row['strike']
735
+ T = max(row['Days to Expiry'] / 365, epsilon) # Ensure T > 0
736
+ sigma = max(row['impliedVolatility'], 0.01) # Prevent division by zero
737
+
738
+ # Validate inputs
739
+ if pd.isna(S) or pd.isna(K) or pd.isna(sigma) or S <= 0 or sigma <= 0:
740
+ return pd.Series({
741
+ 'Delta': float('nan'), 'Vega': float('nan'), 'Theta': float('nan'), 'Rho': float('nan'),
742
+ 'Gamma': float('nan'), 'Vanna': float('nan'), 'Volga': float('nan'), 'Veta': float('nan'), 'Charm': float('nan'),
743
+ 'Color': float('nan'), 'Speed': float('nan'), 'Ultima': float('nan'), 'Zomma': float('nan')
744
+ })
745
+
746
+ # Compute d1 and d2 once
747
+ d1, d2 = compute_d1_d2(S, K, T, r, sigma)
748
+
749
+ # Compute First-Order Greeks using py_vollib
750
+ first_order_values = {
751
+ 'Delta': delta(option_type, S, K, T, r, sigma),
752
+ 'Vega': vega(option_type, S, K, T, r, sigma),
753
+ 'Theta': theta(option_type, S, K, T, r, sigma),
754
+ 'Rho': rho(option_type, S, K, T, r, sigma),
755
+ }
756
+
757
+ # Compute Second-Order Greeks
758
+ second_order_values = {
759
+ 'Gamma': gamma(option_type, S, K, T, r, sigma),
760
+ 'Vanna': vanna(row, ticker, r, option_type),
761
+ 'Volga': volga(row, ticker, r, option_type),
762
+ 'Veta': veta(row, ticker, r, option_type),
763
+ 'Charm': charm(row, ticker, r, option_type),
764
+ }
765
+
766
+ # Compute Third-Order Greeks
767
+ third_order_values = {
768
+ 'Color': color(row, ticker, r, option_type),
769
+ 'Speed': speed(row, ticker, r, option_type),
770
+ 'Ultima': ultima(row, ticker, r, option_type),
771
+ 'Zomma': zomma(row, ticker, r, option_type),
772
+ }
773
+
774
+ # Combine all Greeks into a single dictionary
775
+ all_greeks = {**first_order_values, **second_order_values, **third_order_values}
776
+
777
+ # Ensure no NoneType values exist (convert None to NaN)
778
+ all_greeks = {key: (round(value, 4) if value is not None else float('nan')) for key, value in all_greeks.items()}
779
+
780
+ return pd.Series(all_greeks)
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.1
2
+ Name: greeks-package
3
+ Version: 0.1
4
+ Requires-Dist: yfinance
5
+ Requires-Dist: numpy
6
+ Requires-Dist: pandas
7
+ Requires-Dist: scipy
8
+ Requires-Dist: py-vollib
9
+
@@ -0,0 +1,6 @@
1
+ Greeks/__init__.py,sha256=Q-nGj1QJMf3NlP41QGlY_GhT8if6OrndONmswmqtmAs,489
2
+ Greeks/main.py,sha256=_evaMXPYQ5jE13l7YvV65gwLuVhjGST9ChGlbT60Y_c,31941
3
+ greeks_package-0.1.dist-info/METADATA,sha256=2lZc27bmYzNZqzB8IRD9yJyDJs1f6_tlT36vn62XkzM,179
4
+ greeks_package-0.1.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
5
+ greeks_package-0.1.dist-info/top_level.txt,sha256=sS0u6-moWVYttdpAIqv2n_ynut0YB5jRfoQtwbJPr58,7
6
+ greeks_package-0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.45.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ Greeks