-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gex.py
475 lines (390 loc) · 14.8 KB
/
Gex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# coding: utf-8
"""
Ernest Orlowski
"""
import datetime
import holidays
import numpy as np
import pandas as pd
import requests
import matplotlib.pyplot as plt
from .PyVol import (
blackDelta,
blackGamma,
blackIV,
blackScholesDelta,
blackScholesGamma,
blackScholesIV,
blackTheta,
blackVega,
)
plt.style.use("ggplot")
def TRTH_GEX(raw):
"""
Inputs:
'raw': raw pd DataFrame output from TRTH with 'RIC', 'Trade Date', 'OI', & 'IV' fields
Returns:
pd DataFrame of est. dealer gamma exposure by day
"""
letterToMonth = {
**dict.fromkeys(["a", "m"], 1),
**dict.fromkeys(["b", "n"], 2),
**dict.fromkeys(["c", "o"], 3),
**dict.fromkeys(["d", "p"], 4),
**dict.fromkeys(["e", "q"], 5),
**dict.fromkeys(["f", "r"], 6),
**dict.fromkeys(["g", "s"], 7),
**dict.fromkeys(["h", "t"], 8),
**dict.fromkeys(["i", "u"], 9),
**dict.fromkeys(["j", "v"], 10),
**dict.fromkeys(["k", "w"], 11),
**dict.fromkeys(["l", "x"], 12),
}
letterToFlag = {
**dict.fromkeys(list("abcdefghijkl"), "c"),
**dict.fromkeys(list("mnopqrstuvwx"), "p"),
}
df = raw.copy(deep=True)
df.set_index("Trade Date", drop=True, inplace=True)
df.index = pd.to_datetime(df.index, infer_datetime_format=True)
underlying = sorted(set(df["RIC"]))[0]
divisor = 10 if underlying in [".SPX", "SPXW"] else 100
df["F"] = df[df["RIC"] == underlying]["Last"]
df = df[df["RIC"] != underlying]
# remove options with minimal OI or w/ no bids
df = df[(df["Open Interest"] > 10) & (df["Bid"] > 0.5)].copy(deep=True)
df["Mid"] = np.mean(df[["Bid", "Ask"]], axis=1)
df["TRTH Tag"] = df["RIC"].str[-12]
df = df[df["TRTH Tag"].notnull()]
df["TRTH Tag"] = df["TRTH Tag"].str.lower()
df = df[df["TRTH Tag"].isin(list("abcdefghijklmnopqrstuvwx"))]
df["Month"] = df["TRTH Tag"].apply(lambda x: letterToMonth[x])
# retrieve day and year from TRTH RIC tag
df["Day"] = pd.to_numeric(df["RIC"].str[-11:-9], downcast="signed")
df["Year"] = pd.to_numeric(df["RIC"].str[-9:-7], downcast="signed") + 2000
df["Expiry"] = pd.to_datetime(
dict(year=df.Year, month=df.Month, day=df.Day), infer_datetime_format=True
)
us_holidays = holidays.UnitedStates(years=list(range(2000, 2030)))
us_hlist = list(us_holidays.keys())
A = [d.date() for d in df["Expiry"]]
B = [d.date() for d in df.index]
df["BDTE"] = np.busday_count(B, A, weekmask="1111100", holidays=us_hlist)
df = df[df["BDTE"] >= 1].copy(deep=True)
df["Flag"] = df["TRTH Tag"].apply(lambda x: letterToFlag[x])
# Retrieve strike price from TRTH RIC tag
df["Strike"] = pd.to_numeric(df["RIC"].str[-7:-2]) / divisor
if underlying in [".SPX", "SPXW"]:
df["IV"] = df.apply(blackIV, axis=1)
df["Delta"] = df.apply(blackDelta, axis=1)
df["Gamma"] = df.apply(blackGamma, axis=1)
else:
df["IV"] = df.apply(blackScholesIV, axis=1)
df["Delta"] = df.apply(blackScholesDelta, axis=1)
df["Gamma"] = df.apply(blackScholesGamma, axis=1)
df = df[(df["IV"] > 0.01) & (df["Iv"] < 2.0) & (np.abs(df["Delta"]) < 0.95)].copy(
deep=True
)
df["GEX"] = 10 ** -6 * (
-100 * (df["Flag"] == "p") * df["Open Interest"] * df["Gamma"] * df["F"]
+ 100 * (df["Flag"] == "c") * df["Open Interest"] * df["Gamma"] * df["F"]
)
if underlying in ["SPY", "GLD", "TLT"]:
df["GEX"] /= 10
df1 = df.pivot_table(values="GEX", index=df.index, aggfunc=np.sum)
del df1.index.name
return df1
def CBOE_GEX(filename, sens=True, plot=True, occ=False):
"""
Calculates dealer gamma exposure from latest CBOE option open interest data at http://www.cboe.com/delayedquote/quote-table-download
Parameters:
filename: string referencing path to local drive. Should be something like 'quotedata.dat'
sens: boolean; returns sensitivity if true, spot value if false
plot: boolean; returns plot if True, pandas series if False
occ: boolean; use Options Clearing Corporation open interest data if True, pull from CBOE file if False
"""
# Extract top rows of dataframe for latest spot price and date
raw = pd.read_table("SPX.dat")
spotF = float(raw.columns[0].split(",")[-2])
ticker = raw.columns[0].split(",")[0][1:4]
rf = 0.02
pltDate = raw.loc[0][0].split(",")[0][:11]
pltTime = raw.loc[0][0].split(",")[0][-8:]
dtDate = datetime.datetime.strptime(pltDate, "%b %d %Y").date()
# Extract dataframe for analysis
raw = pd.read_table("SPX.dat", sep=",", header=2)
c = raw.loc[:, :"Strike"].copy(deep=True)
c.columns = c.columns.str.replace("Calls", "ID")
p = (raw.loc[:, "Strike":].join(raw.loc[:, "Expiration Date"])).copy(deep=True)
p.columns = p.columns.str.replace("Puts", "ID")
p.columns = p.columns.str.replace(".1", "")
p = p[c.columns]
c["Flag"] = "c"
p["Flag"] = "p"
c["Expiry"] = pd.to_datetime(c["Expiration Date"], infer_datetime_format=True)
p["Expiry"] = pd.to_datetime(p["Expiration Date"], infer_datetime_format=True)
# Use requests to extract symbol data
if occ:
def getOCC(symbol):
url = "https://www.theocc.com/webapps/series-search"
s = requests.Session()
r = s.post(url, data={"symbolType": "U", "symbolId": symbol})
df = pd.read_html(r.content)[0]
df.columns = df.columns.droplevel()
df1 = df[df["Product Symbol"].isin(["SPX", "SPXW"])].copy(deep=True)
df1.reset_index(drop=True, inplace=True)
df1.rename(
columns={"Integer": "Strike", "Product Symbol": "Symbol"}, inplace=True
)
months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
]
monthNums = list(range(1, 13))
monthToNum = dict(zip(months, monthNums))
df1["Month"] = df1["Month"].apply(lambda x: monthToNum[x])
df1["Expiry"] = pd.to_datetime(
dict(year=df1.Year, month=df1.Month, day=df1.Day),
infer_datetime_format=True,
)
return df1
print("Getting OI data from OCC...")
df1 = getOCC("SPX")
def idToSymbol(strng):
if strng[3] == "W":
return strng[:4]
else:
return strng[:3]
c["Symbol"] = c["ID"].apply(idToSymbol)
p["Symbol"] = p["ID"].apply(idToSymbol)
c1 = pd.merg(
c,
df1.loc[:, ["Symbol", "Expiry", "Strike", "Call"]],
how="left",
on=["Symbol", "Expiry", "Strike"],
)
p1 = pd.merge(
p,
df1.loc[:, ["Symbol", "Expiry", "Strike", "Put"]],
how="left",
on=["Symbol", "Expiry", "Strike"],
)
c1.drop(["Open Int"], axis=1, inplace=True)
p1.drop(["Open Int"], axis=1, inplace=True)
c1.rename(columns={"Call": "Open Int"}, inplace=True)
p1.rename(columns={"Put": "Open Int"}, inplace=True)
df = c1.append(p1, ignore_index=True)
else:
df = c.append(p, ignore_index=True)
df = df[(df["ID"].str[-3] != "-") & (df["ID"].str[-4] != "-")].copy(deep=True)
for item in [
"Bid",
"Ask",
"Last Sale",
"IV",
"Delta",
"Gamma",
"Open Int",
"Strike",
]:
df[item] = pd.to_numeric(df[item], errors="coerce")
us_holidays = holidays.UnitedStates(years=list(range(2000, 2030)))
us_hlist = list(us_holidays.keys())
A = [d.date() for d in df["Expiry"]]
df["BDTE"] = np.busday_count(dtDate, A, weekmask="1111100", holidays=us_hlist)
df = df.loc[(df["Open Int"] > 10) & (df["Bid"] > 0.05) & (df["BDTE"] >= 1)].copy(
deep=True
)
print("Calculating Greeks...")
df["IV"] = df.apply(lambda x: blackIV(x, F=spotF, rf=rf), axis=1)
df = df[(df["IV"] > 0.01) & (df["IV"] < 2.0)].copy(deep=True)
df["Delta"] = df.apply(lambda x: blackDelta(x, F=spotF, rf=rf), axis=1)
df = df[np.abs(df["Delta"]) < 0.95].copy(deep=True)
if sens:
increment = 10 if ticker in ["SPX", "NDX"] else 1
nPoints = 20
Fs = list(
(
np.linspace(
start=spotF,
stop=spotF + increment * nPoints,
num=nPoints,
endpoint=False,
)
- increment * nPoints // 2
).astype(int)
)
for F in Fs:
df[str(F) + "_g"] = df.apply(lambda x: blackGamma(x, F=F, rf=rf), axis=1)
for F in Fs:
df[str(F) + "_GEX"] = 10 ** -6 * (
100 * F * (df["Flag"] == "c") * df[str(F) + "_g"] * df["Open Int"]
- 100 * F * (df["Flag"] == "p") * df[str(F) + "_g"] * df["Open Int"]
)
GEXs = [
(0.1 if ticker not in ["SPX", "NDX"] else 1)
* np.sum(df[str(F) + "_GEX"], axis=0)
for F in Fs
]
s = pd.Series(dict(zip(Fs, GEXs))).astype(int)
if plot:
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
ax.plot(s, color="xkcd:red")
fig.suptitle(
ticker
+ " Dealer Gamma Exposure per Index Point (=0.1 ETF pt) as of "
+ pltDate
+ " "
+ pltTime,
fontsize=12,
weight="bold",
)
ax.set_ylabel("Dealer Gamma in $mm")
ax.yaxis.set_major_formatter(plt.FuncFormatter("{:,.0f}".format))
ax.axvline(x=spotF, color="xkcd:deep blue", linestyle=":")
zeroGEX = int(np.interp(x=0, xp=s.values, fp=s.index))
ax.axvline(x=zeroGEX, color="xkcd:black", linestyle="--")
ax.legend(labels=["SPX", "Last", "Zero GEX: " + str(zeroGEX)])
plt.xticks(rotation=30)
plt.show()
else:
return s
else:
df["Gamma"] = df.apply(lambda x: blackGamma(x, F=spotF, rf=rf), axis=1)
gams = 10 ** -6 * (
100 * spotF * (df["Flag"] == "c") * df["Gamma"] * df["Open Int"]
- 100 * spotF * (df["Flag"] == "p") * df["Gamma"] * df["Open Int"]
)
gam = (1 if ticker in ["SPX", "NDX"] else 0.1) * np.sum(gams, axis=0)
return gam
def CBOE_Greeks(filename, low, high, incr, expiry, field):
"""
Parameters:
filename: string referencing path to local drive. Should be something like 'quotedata.dat'
low, high, incr: integers describing low and high end of plot range, with increment
expiry: target option expiry in YYYY-MM-DD format
field: 'IV', 'Delta', 'Gamma', 'Vega', 'Gamma/Theta', 'Vega/Theta', or 'Theta/Mid'
Returns:
Plot of option Greeks by strike
"""
fields = [
"IV",
"Delta",
"Gamma",
"Vega",
"Theta",
"Gamma/Theta",
"Vega/Theta",
"Theta/Mid",
]
fltDigs = ["{:,." + str(x) + "f}" for x in [3, 2, 4, 2, 2, 4, 2, 4]]
fltDigDict = dict(zip(fields, fltDigs))
raw = pd.read_table("SPX.dat")
spotF = float(raw.columns[0].split(",")[1])
rf = 0.2
pltDate = raw.loc[0][0][:11]
pltTime = raw.loc[0][0][14:22]
dtDate = datetime.datetime.strptime(pltDate, "%b %d %Y").date()
# extract dataframe for analysis
raw = pd.read_table("SPX.dat", sep=",", header=2)
c = raw.loc[:, :"Strike"].copy(deep=True)
c.columns = c.columns.str.replace("Calls", "ID")
p = raw.loc[
:,
[
"Expiration Date",
"Strike",
"Puts",
"Last Sale.1",
"Net.1",
"Bid.1",
"Ask.1",
"Vol.1",
"IV.1",
"Delta.1",
"Gamma.1",
"Open Int.1",
],
].copy(deep=True)
p.columns = p.columns.str.replace("Puts", "ID")
p.columns = p.columns.str.replace(".1", "")
c["Flag"] = "c"
p["Flag"] = "p"
df = c.append(p, ignore_index=True, sort=True)
df = df[(df["ID"].str[-3] != "-") & (df["ID"].str[-4] != "-")].copy(deep=True)
for item in ["Bid", "Ask", "Last Sale"]:
df[item] = pd.to_numeric(df[item], errors="coerce")
df["Expiry"] = pd.to_datetime(df["Expiration Date"], infer_datetime_format=True)
us_holidays = holidays.UnitedStates(years=list(range(2000, 2030)))
us_hlist = list(us_holidays.keys())
A = [d.date() for d in df["Expiry"]]
df["BDTE"] = np.busday_count(dtDate, A, weekmask="1111100", holidays=us_hlist)
df = df.loc[(df["Open Int"] > 10) & (df["Bid"] > 0.05) & (df["BDTE"] >= 1)].copy(
deep=True
)
df["Mid"] = np.mean(df[["Bid", "Ask"]], axis=1)
df["IV"] = df.apply(lambda x: blackIV(x, F=spotF, rf=rf), axis=1)
df["Delta"] = df.apply(lambda x: blackDelta(x, F=spotF, rf=rf), axis=1)
df = df[np.abs(df["Delta"]) < 0.9].copy(deep=True)
if field in ["Gamma", "Gamma/Theta"]:
df["Gamma"] = df.apply(lambda x: blackGamma(x, F=spotF, rf=rf), axis=1)
if field in ["Vega", "Vega/Theta"]:
df["Vega"] = df.apply(lambda x: blackVega(x, F=spotF, rf=rf), axis=1)
if field in ["Theta", "Gamma/Theta", "Vega/Theta", "Theta/Mid"]:
df["Theta"] = df.apply(lambda x: blackTheta(x, F=spotF, rf=rf), axis=1)
if field == "Gamma/Theta":
df["Gamma/Theta"] = -df["Gamma"] / df["Theta"]
if field == "Vega/Theta":
df["Vega/Theta"] = -df["Vega"] / df["Theta"]
if field == "Theta/Mid":
df["Theta/Mid"] = df["Theta"] / df["Mid"]
pGreeks = (
df[
(df["Expiry"] == expiry)
& (df["Strike"].isin(range(low, high, incr)))
& (df["Flag"] == "p")
]
.groupby("Strike", axis=0)
.mean()[field]
)
cGreeks = (
df[
(df["Expiry"] == expiry)
& (df["Strike"].isin(range(low, high, incr)))
& (df["Flag"] == "c")
]
.groupby("Strike", axis=0)
.mean()[field]
)
fig, ax = plt.subplots(1, 1, figsize=(8, 5))
ax.plot(pGreeks, color="xkcd:red")
ax.plot(cGreeks, color="xkcd:dark green")
fig.suptitle(
"SPX "
+ expiry
+ " Expiry\n"
+ field
+ " by Strike as of "
+ pltDate
+ " "
+ pltTime,
fontsize=12,
weight="bold",
)
ax.set_ylabel(field)
ax.yaxis.set_major_formatter(plt.FuncFormatter(fltDigDict[field].format))
ax.axvline(x=spotF, color="xkcd:deep blue", linestyle=":")
ax.legend(labels=["Puts", "Calls", "Last"])
plt.xticks(rotation=30)
plt.show()