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

Add options greeks to the SDK #4334

Merged
merged 2 commits into from
Feb 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions openbb_terminal/miscellaneous/library/trail_map.csv
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions openbb_terminal/sdk_core/models/stocks_sdk_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
97 changes: 97 additions & 0 deletions openbb_terminal/stocks/options/options_sdk_helper.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
"""Options Functions For OpenBB SDK"""

import logging
from datetime import datetime, timedelta
from typing import Optional, Union

import numpy as np
import pandas as pd
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,
Expand All @@ -17,6 +19,7 @@
tradier_model,
yfinance_model,
)
from openbb_terminal.stocks.options.op_helpers import Option

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -235,3 +238,97 @@ 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