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
|
"""Tradier options model"""
__docformat__ = "numpy"
import logging
from typing import List, Optional
import pandas as pd
import requests
from openbb_terminal import config_terminal as cfg
from openbb_terminal.decorators import check_api_key, log_start_end
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
option_columns = [
"symbol",
"bid",
"ask",
"strike",
"bidsize",
"asksize",
"volume",
"open_interest",
"option_type",
]
greek_columns = ["delta", "gamma", "theta", "vega", "ask_iv", "bid_iv", "mid_iv"]
df_columns = option_columns + greek_columns
default_columns = [
"mid_iv",
"vega",
"delta",
"gamma",
"theta",
"volume",
"open_interest",
"bid",
"ask",
]
@log_start_end(log=logger)
@check_api_key(["API_TRADIER_TOKEN"])
def get_historical_options(
symbol: str,
expiry: str,
strike: float = 0,
put: bool = False,
chain_id: Optional[str] = None,
) -> pd.DataFrame:
"""
Gets historical option pricing. This inputs either ticker, expiration, strike or the OCC chain ID and processes
the request to tradier for historical premiums.
Parameters
----------
symbol: str
Stock ticker symbol
expiry: str
Option expiration date
strike: int
Option strike price
put: bool
Is this a put option?
chain_id: Optional[str]
OCC chain ID
Returns
-------
df_hist: pd.DataFrame
Dataframe of historical option prices
"""
if not chain_id:
op_type = ["call", "put"][put]
chain = get_option_chains(symbol, expiry)
try:
symbol = chain[(chain.strike == strike) & (chain.option_type == op_type)][
"symbol"
].values[0]
except IndexError:
error = f"Strike: {strike}, Option type: {op_type} not not found"
logging.exception(error)
console.print(f"{error}\n")
return pd.DataFrame()
else:
symbol = chain_id
response = requests.get(
"https://sandbox.tradier.com/v1/markets/history",
params={"symbol": {symbol}, "interval": "daily"},
headers={
"Authorization": f"Bearer {cfg.API_TRADIER_TOKEN}",
"Accept": "application/json",
},
)
if response.status_code != 200:
console.print("Error with request")
return pd.DataFrame()
data = response.json()["history"]
if not data:
console.print("No historical data available")
return pd.DataFrame()
df_hist = pd.DataFrame(data["day"])
df_hist = df_hist.set_index("date")
df_hist.index = pd.DatetimeIndex(df_hist.index)
return df_hist
# pylint: disable=no-else-return
option_cols = [
"strike",
"bid",
"ask",
"volume",
"open_interest",
"mid_iv",
]
option_col_map = {"open_interest": "openinterest", "mid_iv": "iv"}
@log_start_end(log=logger)
@check_api_key(["API_TRADIER_TOKEN"])
def get_full_option_chain(symbol: str) -> pd.DataFrame:
"""Get available expiration dates for given ticker
Parameters
----------
symbol: str
Ticker symbol to get expirations for
Returns
-------
pd.DataFrame
Dataframe of all option chains
"""
expirations = option_expirations(symbol)
options_dfs: pd.DataFrame = []
for expiry in expirations:
options_dfs.append(get_option_chains(symbol, expiry))
options_df = pd.concat(options_dfs)
options_df.set_index(keys="symbol", inplace=True)
option_df_index = pd.Series(options_df.index).str.extractall(
r"^(?P<Ticker>\D*)(?P<Expiration>\d*)(?P<Type>\D*)(?P<Strike>\d*)"
)
option_df_index.reset_index(inplace=True)
option_df_index = pd.DataFrame(
option_df_index, columns=["Ticker", "Expiration", "Strike", "Type"]
)
option_df_index["Strike"] = options_df["strike"].values
option_df_index["Type"] = options_df["option_type"].values
option_df_index["Expiration"] = pd.DatetimeIndex(
data=option_df_index["Expiration"], yearfirst=True
).strftime("%Y-%m-%d")
option_df_index["Type"] = pd.DataFrame(option_df_index["Type"]).replace(
to_replace=["put", "call"], value=["Put", "Call"]
)
options_df_columns = list(options_df.columns)
option_df_index.set_index(
keys=["Ticker", "Expiration", "Strike", "Type"], inplace=True
)
options_df = pd.DataFrame(
data=options_df.values, index=option_df_index.index, columns=options_df_columns
)
options_df.rename(
columns={
"bid": "Bid",
"ask": "Ask",
"strike": "Strike",
"bidsize": "Bid Size",
"asksize": "Ask Size",
"volume": "Volume",
"open_interest": "OI",
"delta": "Delta",
"gamma": "Gamma",
"theta": "Theta",
"vega": "Vega",
"ask_iv": "Ask IV",
"bid_iv": "Bid IV",
"mid_iv": "IV",
},
inplace=True,
)
options_columns = [
"Volume",
"OI",
"IV",
"Delta",
"Gamma",
"Theta",
"Vega",
"Bid Size",
"Bid",
"Ask",
"Ask Size",
"Bid IV",
"Ask IV",
]
options = pd.DataFrame(options_df, columns=options_columns)
options = options.reset_index()
options.drop(labels = ['Ticker'], inplace = True, axis = 1)
options.rename(columns = {'Expiration': 'expiration'}, inplace = True)
return options
@log_start_end(log=logger)
@check_api_key(["API_TRADIER_TOKEN"])
def option_expirations(symbol: str) -> List[str]:
"""Get available expiration dates for given ticker
Parameters
----------
symbol: str
Ticker symbol to get expirations for
Returns
-------
dates: List[str]
List of of available expirations
"""
r = requests.get(
"https://sandbox.tradier.com/v1/markets/options/expirations",
params={"symbol": symbol, "includeAllRoots": "true", "strikes": "false"},
headers={
"Authorization": f"Bearer {cfg.API_TRADIER_TOKEN}",
"Accept": "application/json",
},
)
if r.status_code == 200:
try:
dates = r.json()["expirations"]["date"]
return dates
except TypeError:
logging.exception("Error in tradier JSON response. Check loaded ticker.")
console.print("Error in tradier JSON response. Check loaded ticker.\n")
return []
else:
console.print("Tradier request failed. Check token. \n")
return []
@log_start_end(log=logger)
@check_api_key(["API_TRADIER_TOKEN"])
def get_option_chains(symbol: str, expiry: str) -> pd.DataFrame:
"""Display option chains [Source: Tradier]"
Parameters
----------
symbol : str
Ticker to get options for
expiry : str
Expiration date in the form of "YYYY-MM-DD"
Returns
-------
chains: pd.DataFrame
Dataframe with options for the given Symbol and Expiration date
"""
params = {"symbol": symbol, "expiration": expiry, "greeks": "true"}
headers = {
"Authorization": f"Bearer {cfg.API_TRADIER_TOKEN}",
"Accept": "application/json",
}
response = requests.get(
"https://sandbox.tradier.com/v1/markets/options/chains",
params
|