From 21a7777370172ecffdeb416ab60400ed69feb0e4 Mon Sep 17 00:00:00 2001 From: northern-64bit <75195383+northern-64bit@users.noreply.github.com> Date: Sat, 25 Feb 2023 23:41:38 +0100 Subject: [PATCH 1/2] Add options greeks to the SDK --- .../miscellaneous/library/trail_map.csv | 1 + .../controllers/stocks_sdk_controller.py | 1 + .../sdk_core/models/stocks_sdk_model.py | 1 + .../stocks/options/options_sdk_helper.py | 99 +++++++++++++++++++ 4 files changed, 102 insertions(+) diff --git a/openbb_terminal/miscellaneous/library/trail_map.csv b/openbb_terminal/miscellaneous/library/trail_map.csv index ceb9940b51f8..6a026cdc6fe2 100644 --- a/openbb_terminal/miscellaneous/library/trail_map.csv +++ b/openbb_terminal/miscellaneous/library/trail_map.csv @@ -478,6 +478,7 @@ stocks.options.dte,openbb_terminal.stocks.options.yfinance_model.get_dte, stocks.options.eodchain,openbb_terminal.stocks.options.intrinio_model.get_full_chain_eod, stocks.options.expirations,openbb_terminal.stocks.options.options_sdk_helper.get_option_expirations, stocks.options.generate_data,openbb_terminal.stocks.options.yfinance_model.generate_data, +stocks.options.greeks,openbb_terminal.stocks.options.options_sdk_helper.get_greeks, stocks.options.grhist,openbb_terminal.stocks.options.screen.syncretism_model.get_historical_greeks,openbb_terminal.stocks.options.screen.syncretism_view.view_historical_greeks stocks.options.hist,openbb_terminal.stocks.options.options_sdk_helper.hist, stocks.options.info,openbb_terminal.stocks.options.barchart_model.get_options_info,openbb_terminal.stocks.options.barchart_view.print_options_data diff --git a/openbb_terminal/sdk_core/controllers/stocks_sdk_controller.py b/openbb_terminal/sdk_core/controllers/stocks_sdk_controller.py index 26679114052b..794b48336ebd 100644 --- a/openbb_terminal/sdk_core/controllers/stocks_sdk_controller.py +++ b/openbb_terminal/sdk_core/controllers/stocks_sdk_controller.py @@ -271,6 +271,7 @@ def options(self): `eodchain`: Get full EOD option date across all expirations\n `expirations`: Get Option Chain Expirations\n `generate_data`: Gets x values, and y values before and after premiums\n + `greeks`: Gets the greeks for a given option\n `grhist`: Get historical option greeks\n `grhist_chart`: Plots historical greeks for a given option. [Source: Syncretism]\n `hist`: Get historical option pricing.\n diff --git a/openbb_terminal/sdk_core/models/stocks_sdk_model.py b/openbb_terminal/sdk_core/models/stocks_sdk_model.py index 4399d7b6a16c..0d8309323d1e 100644 --- a/openbb_terminal/sdk_core/models/stocks_sdk_model.py +++ b/openbb_terminal/sdk_core/models/stocks_sdk_model.py @@ -491,6 +491,7 @@ def __init__(self): self.eodchain = lib.stocks_options_intrinio_model.get_full_chain_eod self.expirations = lib.stocks_options_sdk_helper.get_option_expirations self.generate_data = lib.stocks_options_yfinance_model.generate_data + self.greeks = lib.stocks_options_sdk_helper.get_greeks self.grhist = lib.stocks_options_screen_syncretism_model.get_historical_greeks self.grhist_chart = ( lib.stocks_options_screen_syncretism_view.view_historical_greeks diff --git a/openbb_terminal/stocks/options/options_sdk_helper.py b/openbb_terminal/stocks/options/options_sdk_helper.py index 39715225cb8f..c32090360216 100644 --- a/openbb_terminal/stocks/options/options_sdk_helper.py +++ b/openbb_terminal/stocks/options/options_sdk_helper.py @@ -1,6 +1,7 @@ """Options Functions For OpenBB SDK""" import logging +from datetime import datetime, timedelta from typing import Optional, Union import numpy as np @@ -8,6 +9,7 @@ from scipy.optimize import minimize from openbb_terminal.decorators import log_start_end +from openbb_terminal.helper_funcs import get_rf from openbb_terminal.rich_config import console from openbb_terminal.stocks.options import ( chartexchange_model, @@ -17,6 +19,7 @@ tradier_model, yfinance_model, ) +from openbb_terminal.stocks.options.op_helpers import Option logger = logging.getLogger(__name__) @@ -235,3 +238,99 @@ def get_delta_neutral(symbol: str, date: str, x0: Optional[float] = None) -> flo "Error getting delta neutral price for %s on %s: error:%s", symbol, date, e ) return np.nan + + +def get_greeks( + current_price: float, + chain: pd.DataFrame, + expire: str, + div_cont: float = 0, + rf: Optional[float] = None, +) -> pd.DataFrame: + """ + Gets the greeks for a given option + + Parameters + ---------- + current_price: float + The current price of the underlying + chain: pd.DataFrame + The dataframe with option chains + div_cont: float + The dividend continuous rate + expire: str + The date of expiration + rf: float + The risk-free rate + + Returns + ------- + pd.DataFrame + Dataframe with calculated option greeks + + Examples + -------- + >>> from openbb_terminal.sdk import openbb + >>> aapl_chain = openbb.stocks.options.chains("AAPL", source="Tradier") + >>> aapl_last_price = openbb.stocks.options.last_price("AAPL") + >>> greeks = openbb.stocks.options.greeks(aapl_last_price, aapl_chain, aapl_chain.iloc[0, 2]) + """ + + chain = chain.rename(columns={"iv": "impliedVolatility"}) + chain_columns = chain.columns.tolist() + if not all( + col in chain_columns for col in ["strike", "impliedVolatility", "optionType"] + ): + if "delta" not in chain_columns: + console.print( + "[red]It's not possible to calculate the greeks without the following " + "columns: `strike`, `impliedVolatility`, `optionType`.\n[/red]" + ) + return pd.DataFrame() + + risk_free = rf if rf is not None else get_rf() + expire_dt = datetime.strptime(expire, "%Y-%m-%d") + dif = (expire_dt - datetime.now() + timedelta(hours=16)).total_seconds() / ( + 60 * 60 * 24 + ) + strikes = [] + for _, row in chain.iterrows(): + vol = row["impliedVolatility"] + opt_type = 1 if row["optionType"] == "call" else -1 + opt = Option( + current_price, row["strike"], risk_free, div_cont, dif, vol, opt_type + ) + tmp = [ + opt.Delta(), + opt.Gamma(), + opt.Vega(), + opt.Theta(), + opt.Rho(), + opt.Phi(), + opt.Charm(), + opt.Vanna(0.01), + opt.Vomma(0.01), + ] + result = [row[col] for col in row.index.tolist()] + result += tmp + + strikes.append(result) + + greek_columns = [ + "Delta", + "Gamma", + "Vega", + "Theta", + "Rho", + "Phi", + "Charm", + "Vanna", + "Vomma" + ] + columns = ( + chain_columns + greek_columns + ) + + df = pd.DataFrame(strikes, columns=columns) + + return df From 2f8f52e20a07ffd5843cf50ec33f9e2a4bd612a5 Mon Sep 17 00:00:00 2001 From: northern-64bit <75195383+northern-64bit@users.noreply.github.com> Date: Sat, 25 Feb 2023 23:50:23 +0100 Subject: [PATCH 2/2] Linting --- openbb_terminal/stocks/options/options_sdk_helper.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/openbb_terminal/stocks/options/options_sdk_helper.py b/openbb_terminal/stocks/options/options_sdk_helper.py index c32090360216..7744b31e2e5d 100644 --- a/openbb_terminal/stocks/options/options_sdk_helper.py +++ b/openbb_terminal/stocks/options/options_sdk_helper.py @@ -325,11 +325,9 @@ def get_greeks( "Phi", "Charm", "Vanna", - "Vomma" + "Vomma", ] - columns = ( - chain_columns + greek_columns - ) + columns = chain_columns + greek_columns df = pd.DataFrame(strikes, columns=columns)