Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor stocks/options/voi,vol,oi,chains #4017

Merged
merged 85 commits into from
Jan 26, 2023
Merged
Show file tree
Hide file tree
Changes from 79 commits
Commits
Show all changes
85 commits
Select commit Hold shift + click to select a range
d8db53f
add raw option to yf stocks/options
hjoaquim Nov 30, 2022
722f897
Merge branch 'main' into fix3403
hjoaquim Dec 6, 2022
e33e535
Merge branch 'main' into fix3403
hjoaquim Dec 13, 2022
3b33c56
Merge branch 'main' into fix3403
hjoaquim Jan 3, 2023
5b33624
Merge branch 'main' into fix3403
hjoaquim Jan 3, 2023
f15b1dc
Merge branch 'main' into fix3403
hjoaquim Jan 4, 2023
f7dcb56
removed redundant functions
hjoaquim Jan 4, 2023
31d88a0
naming convention for nasdaq
hjoaquim Jan 4, 2023
6c189a7
naming convention for tradier
hjoaquim Jan 4, 2023
8aa73ad
some protection for undefined api key
hjoaquim Jan 4, 2023
bdae45f
some protection for undefined api key
hjoaquim Jan 4, 2023
2bf2613
added function to set option chain
hjoaquim Jan 4, 2023
f329eef
added function to set current price + some name consistency
hjoaquim Jan 4, 2023
bd71f7c
Merge branch 'main' into fix3403
hjoaquim Jan 4, 2023
1dfc26f
vol to work source independent
hjoaquim Jan 4, 2023
711ae3b
export options
hjoaquim Jan 4, 2023
bb7e89e
using the flags calls/puts only
hjoaquim Jan 5, 2023
5c948b8
centralised oi function
hjoaquim Jan 5, 2023
62571a6
centralised voi function
hjoaquim Jan 5, 2023
16cd17a
removing tests from removed functions
hjoaquim Jan 5, 2023
caef653
Merge branch 'main' into fix3403
hjoaquim Jan 5, 2023
646b7a7
tradier to use chain object
hjoaquim Jan 6, 2023
7157f4b
nasdaq and yf to use chain
hjoaquim Jan 6, 2023
94e8872
sdk functions
hjoaquim Jan 6, 2023
bb95ec1
Merge branch 'main' into fix3403
hjoaquim Jan 6, 2023
80dfd9a
Fix plot look when using eval and add query to choices (#3881)
montezdesousa Jan 6, 2023
d072871
Merge branch 'main' into fix3403
hjoaquim Jan 7, 2023
4ff55b0
cope with new autocompletion
hjoaquim Jan 7, 2023
33766b6
using class attrb to deal with source
hjoaquim Jan 7, 2023
b729ec1
preparing to use get full option chain
hjoaquim Jan 7, 2023
187ac1e
removing unused function
hjoaquim Jan 8, 2023
631b5dd
moving things arround
hjoaquim Jan 8, 2023
65eea13
functions oi,voi,vol working
hjoaquim Jan 8, 2023
1f66b21
getting rid of Chain obj for Tradier
hjoaquim Jan 8, 2023
99abb7e
getting rid of Chain obj for good
hjoaquim Jan 8, 2023
5e8c287
fixing tests
hjoaquim Jan 8, 2023
790be8c
fixing tests
hjoaquim Jan 8, 2023
4f371e2
fixing tests
hjoaquim Jan 8, 2023
1a090f1
Revert "fixing tests"
hjoaquim Jan 8, 2023
7ad0952
fixing tests
hjoaquim Jan 8, 2023
52869a7
adding sdk functionality
hjoaquim Jan 8, 2023
ec8e5b1
bug fixing
hjoaquim Jan 9, 2023
49eb16a
adding exp as arg
hjoaquim Jan 9, 2023
63c74ca
fixing tests
hjoaquim Jan 9, 2023
365c9e0
integration tests
hjoaquim Jan 9, 2023
fc58757
Lock ruff version so that new lints dont break our CI (#3905)
colin99d Jan 9, 2023
ecee73e
Merge branch 'main' into fix3403
hjoaquim Jan 9, 2023
791320c
Merge branch 'develop' into fix3403
hjoaquim Jan 13, 2023
05624b6
Merge branch 'fix3403' of github.com:hjoaquim/OpenBBTerminal into fix…
hjoaquim Jan 13, 2023
01c1a6d
Merge branch 'develop' into fix3403
jmaslek Jan 13, 2023
ff50def
Merge branch 'develop' into fix3403
jmaslek Jan 13, 2023
b920347
adding progress bar
hjoaquim Jan 16, 2023
cda180b
Merge branch 'develop' into fix3403
hjoaquim Jan 16, 2023
4ec0ce3
Merge branch 'fix3403' of github.com:hjoaquim/OpenBBTerminal into fix…
hjoaquim Jan 16, 2023
a476e0f
Merge branch 'develop' into fix3403
hjoaquim Jan 16, 2023
3b6691a
removing - from the voi plot
hjoaquim Jan 16, 2023
bd9ca5c
Merge branch 'fix3403' of github.com:hjoaquim/OpenBBTerminal into fix…
hjoaquim Jan 16, 2023
b825363
Merge branch 'develop' into fix3403
jmaslek Jan 17, 2023
37eea71
Merge branch 'develop' into fix3403
hjoaquim Jan 17, 2023
1d14432
Merge branch 'develop' into fix3403
jmaslek Jan 19, 2023
a132920
Merge branch 'develop' into feature/refactor-options
jmaslek Jan 19, 2023
e3e9624
Merge branch 'develop' into feature/refactor-options
hjoaquim Jan 20, 2023
ee6b6c5
improved messages and fixed autocompletion
hjoaquim Jan 20, 2023
80ed7b2
refactored chains
hjoaquim Jan 20, 2023
7a7738b
removing unused stuff
hjoaquim Jan 20, 2023
29f7ad3
adding to_display
hjoaquim Jan 20, 2023
df31414
Merge branch 'develop' into feature/refactor-options
jmaslek Jan 22, 2023
fd1fce9
Merge branch 'develop' into feature/refactor-options
hjoaquim Jan 23, 2023
21b8dd9
refactored chains command
hjoaquim Jan 23, 2023
d34fc6a
yf show_greeks to use 1 as default opt_type
hjoaquim Jan 23, 2023
f918bd6
Merge branch 'develop' into feature/refactor-options
jmaslek Jan 23, 2023
3e33eae
tests
hjoaquim Jan 24, 2023
213ef44
Merge branch 'feature/refactor-options' of github.com:hjoaquim/OpenBB…
hjoaquim Jan 24, 2023
90aec83
Merge branch 'develop' into feature/refactor-options
hjoaquim Jan 24, 2023
a0e8727
fix tests
hjoaquim Jan 24, 2023
6c1ab0b
fix tests
hjoaquim Jan 24, 2023
df30580
fix tests
hjoaquim Jan 24, 2023
9e73264
remove tests
hjoaquim Jan 24, 2023
7fe93ad
fixed tests
hjoaquim Jan 24, 2023
0bd0ec6
Merge branch 'develop' into feature/refactor-options
hjoaquim Jan 24, 2023
7e701c2
Merge branch 'develop' into feature/refactor-options
hjoaquim Jan 25, 2023
85c7964
removing redudant test
hjoaquim Jan 26, 2023
2845cf8
Merge branch 'feature/refactor-options' of github.com:hjoaquim/OpenBB…
hjoaquim Jan 26, 2023
d55ee82
Merge branch 'develop' into feature/refactor-options
hjoaquim Jan 26, 2023
f3b8a8d
fixing the test by sorting the columns and making sure export can hav…
hjoaquim Jan 26, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion openbb_terminal/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def wrapper_decorator(*args, **kwargs):
undefined_apis_name = ", ".join(undefined_apis)
console.print(
f"[red]{undefined_apis_name} not defined. "
"Set API Keys in ~/.openbb_terminal/.env or under keys menu.[/red]\n"
"Set API Keys in ~/.openbb_terminal/.env or under keys menu.[/red]"
) # pragma: allowlist secret
return None
return func(*args, **kwargs)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
stocks
options
# screen
# view
# view high_IV
# set high_IV
# scr
# q
# unu -l 2 -s Strike -a -c
# unu -l 2 -s Vol
# calc
# load ${ticker=aapl}
# exp 0
# pcr
# info
# chains
# oi
# vol
# voi
# hist 100
# grhist 100
# greeks
# plot -x ltd -y iv
# parity -p -m 150 -M 175
# binom -s 150
# load spy
# vsurf
# load ${ticker=NDX} --source Nasdaq
# exp 0 --source Nasdaq
# chains --source Nasdaq
# oi --source Nasdaq
# vol --source Nasdaq
# voi --source Nasdaq
screen
view
view --preset high_IV.ini
set --preset high_IV.ini
scr
q
unu -l 2 -s Strike -r -c
unu -l 2 -s Vol
calc
load aapl
exp 0
pcr
info
chains
oi
vol
voi
hist 100
grhist 100
greeks
plot -x ltd -y iv
parity -p -m 150 -M 175
binom -s 150
load spy
vsurf
load NDX --source Nasdaq
exp 0
chains --source Nasdaq
oi
vol
voi
exit
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
stocks
options
load ${ticker=aapl}
load aapl
exp 0
payoff
list
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
stocks
options
load ${ticker=aapl}
load aapl
exp 0
pricing
add 150 -c 3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ stocks
options
screen
view
view high_IV
set high_IV
view high_IV.ini
set high_IV.ini
scr
ca
historical
Expand Down
4 changes: 4 additions & 0 deletions openbb_terminal/miscellaneous/library/trail_map.csv
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,10 @@ stocks.options.grhist,openbb_terminal.stocks.options.screen.syncretism_model.get
stocks.options.screen.screener_output,openbb_terminal.stocks.options.screen.syncretism_model.get_screener_output,openbb_terminal.stocks.options.screen.syncretism_view.view_screener_output
stocks.options.hist,openbb_terminal.stocks.options.options_sdk_helper.hist,
stocks.options.chains,openbb_terminal.stocks.options.options_sdk_helper.get_full_option_chain,
stocks.options.price,openbb_terminal.stocks.options.options_sdk_helper.get_option_current_price,
stocks.options.vol,openbb_terminal.stocks.options.options_view.plot_vol,
stocks.options.oi,openbb_terminal.stocks.options.options_view.plot_oi,
stocks.options.voi,openbb_terminal.stocks.options.options_view.plot_voi,
stocks.options.last_price,openbb_terminal.stocks.options.tradier_model.last_price,
stocks.options.expirations,openbb_terminal.stocks.options.options_sdk_helper.get_option_expirations,
stocks.options.process_chains,openbb_terminal.stocks.options.tradier_model.process_chains,
Expand Down
172 changes: 68 additions & 104 deletions openbb_terminal/stocks/options/nasdaq_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
__docformat__ = "numpy"

import logging
from datetime import datetime
from datetime import datetime, timedelta
from typing import List

import numpy as np
Expand All @@ -11,12 +11,38 @@

from openbb_terminal.decorators import log_start_end
from openbb_terminal.rich_config import console
from openbb_terminal.stocks.options.op_helpers import get_dte_from_expiration as get_dte

logger = logging.getLogger(__name__)
# pylint: disable=unsupported-assignment-operation


@log_start_end(log=logger)
def get_dte_from_expiration(date: str) -> float:
"""
Converts a date to total days until the option would expire.
This assumes that the date is in the form %B %d, %Y such as January 11, 2023
This calculates time from 'now' to 4 PM the date of expiration
This is particularly a helper for nasdaq results.

Parameters
----------
date: str
Date in format %B %d, %Y

Returns
-------
float
Days to expiration as a decimal
"""
# Get the date as a datetime and add 16 hours (4PM)
expiration_time = datetime.strptime(date, "%B %d, %Y") + timedelta(hours=16)
# Find total seconds from now
time_to_now = (expiration_time - datetime.now()).total_seconds()
# Convert to days
time_to_now /= 60 * 60 * 24
return time_to_now


@log_start_end(log=logger)
def get_full_option_chain(symbol: str) -> pd.DataFrame:
"""Get the full option chain for symbol over all expirations
Expand Down Expand Up @@ -45,50 +71,53 @@ def get_full_option_chain(symbol: str) -> pd.DataFrame:
" AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15"
},
).json()

if response_json["status"]["rCode"] == 200:
df = pd.DataFrame(response_json["data"]["table"]["rows"]).drop(
columns=["c_colour", "p_colour", "drillDownURL"]
)
df["expirygroup"] = (
df["expirygroup"].replace("", np.nan).fillna(method="ffill")
)
# Make numeric
columns_w_types = {
"c_Last": float,
"c_Change": float,
"c_Bid": float,
"c_Ask": float,
"c_Volume": int,
"c_Openinterest": int,
"strike": float,
"p_Last": float,
"p_Change": float,
"p_Bid": float,
"p_Ask": float,
"p_Volume": int,
"p_Openinterest": int,
}

for key, _ in columns_w_types.items():
df[key] = df[key].replace(",", "", regex=True)

df = (
df.fillna(np.nan)
.dropna(axis=0)
.replace("--", 0)
.astype(columns_w_types)
)
df["DTE"] = df["expirygroup"].apply(lambda t: get_dte(t))
df = df[df.DTE > 0]
df = df.drop(columns=["DTE"])
return df
return process_response(response_json)

console.print(f"[red]{symbol} Option Chain not found.[/red]\n")
return pd.DataFrame()


def process_response(response_json):
df = pd.DataFrame(response_json["data"]["table"]["rows"]).drop(
columns=["c_colour", "p_colour", "drillDownURL"]
)
df["expirygroup"] = df["expirygroup"].replace("", np.nan).fillna(method="ffill")
# Make numeric
columns_w_types = {
"c_Last": float,
"c_Change": float,
"c_Bid": float,
"c_Ask": float,
"c_Volume": int,
"c_Openinterest": int,
"strike": float,
"p_Last": float,
"p_Change": float,
"p_Bid": float,
"p_Ask": float,
"p_Volume": int,
"p_Openinterest": int,
}

for key, _ in columns_w_types.items():
df[key] = df[key].replace(",", "", regex=True)

df = df.fillna(np.nan).dropna(axis=0).replace("--", 0).astype(columns_w_types)
df["DTE"] = df["expirygroup"].apply(lambda t: get_dte_from_expiration(t))
df = df[df.DTE > 0]
df = df.drop(columns=["DTE"])

df["expiration"] = pd.to_datetime(
df["expirygroup"], format="%B %d, %Y"
).dt.strftime("%Y-%m-%d")

return df


@log_start_end(log=logger)
def get_expirations(symbol: str) -> List[str]:
def option_expirations(symbol: str) -> List[str]:
"""Get available expirations

Parameters
Expand All @@ -110,71 +139,6 @@ def get_expirations(symbol: str) -> List[str]:
return [datetime.strptime(exp, "%B %d, %Y").strftime("%Y-%m-%d") for exp in exps]


@log_start_end(log=logger)
def get_chain_given_expiration(symbol: str, expiration: str) -> pd.DataFrame:
"""Get option chain for symbol at a given expiration

Parameters
----------
symbol: str
Symbol to get chain for
expiration: str
Expiration to get chain for

Returns
-------
pd.DataFrame
Dataframe of option chain
"""
for asset in ["stocks", "index", "etf"]:
url = (
f"https://api.nasdaq.com/api/quote/{symbol}/option-chain?assetclass={asset}&"
f"fromdate={expiration}&todate={expiration}&excode=oprac&callput=callput&money=all&type=all"
)

response_json = requests.get(
url,
headers={
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"
" AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15"
},
).json()
if response_json["status"]["rCode"] == 200:
df = (
pd.DataFrame(
response_json.get("data", {}).get("table", {}).get("rows", {})
)
.drop(columns=["c_colour", "p_colour", "drillDownURL", "expirygroup"])
.fillna(np.nan)
.dropna(axis=0)
)
# Make numeric
columns_w_types = {
"c_Last": float,
"c_Change": float,
"c_Bid": float,
"c_Ask": float,
"c_Volume": int,
"c_Openinterest": int,
"strike": float,
"p_Last": float,
"p_Change": float,
"p_Bid": float,
"p_Ask": float,
"p_Volume": int,
"p_Openinterest": int,
}

for key, _ in columns_w_types.items():
df[key] = df[key].replace(",", "", regex=True)

df = df.replace("--", 0).astype(columns_w_types)
return df

console.print(f"[red]{symbol} Option Chain not found.[/red]\n")
return pd.DataFrame()


@log_start_end(log=logger)
def get_last_price(symbol: str) -> float:
"""Get the last price from nasdaq
Expand Down
Loading