From 58dc9ee52dce121c1973892a6da11053af9f14ab Mon Sep 17 00:00:00 2001 From: Jamie Date: Fri, 16 Apr 2021 14:43:40 -0400 Subject: [PATCH] add in option chains :) --- gamestonk_terminal/config_terminal.py | 3 + gamestonk_terminal/options/README.md | 29 ++- gamestonk_terminal/options/chains_view.py | 208 ++++++++++++++++++++ gamestonk_terminal/options/op_controller.py | 9 +- gamestonk_terminal/options/volume_view.py | 2 +- 5 files changed, 246 insertions(+), 5 deletions(-) create mode 100644 gamestonk_terminal/options/chains_view.py diff --git a/gamestonk_terminal/config_terminal.py b/gamestonk_terminal/config_terminal.py index 4189a27ce4e..daf66a26be6 100644 --- a/gamestonk_terminal/config_terminal.py +++ b/gamestonk_terminal/config_terminal.py @@ -35,3 +35,6 @@ API_NEWS_TOKEN = os.getenv("GT_API_NEWS_TOKEN") or "REPLACE_ME" # Robinhood RH_USERNAME = os.getenv("GT_RH_USERNAME") or "REPLACE_ME" RH_PASSWORD = os.getenv("GT_RH_PASSWORD") or "REPLACE_ME" + +# https://tradier.com/products/market-data-api +TRADIER_TOKEN = os.getenv("GT_TRADIER_TOKEN") or "REPLACE_ME" diff --git a/gamestonk_terminal/options/README.md b/gamestonk_terminal/options/README.md index a86dceb2b2c..980be7495c4 100644 --- a/gamestonk_terminal/options/README.md +++ b/gamestonk_terminal/options/README.md @@ -1,11 +1,13 @@ # OPTIONS DATA -This menu aims to give insight on options. options can cause significant share price movement, and option pricing gives info about market sentiment for a ticker. +This menu aims to give insight on options. options can cause significant share price movement, and option pricing gives +info about market sentiment for a ticker. * [volume](#volume) * Show traded options for a given expiry [Yahoo Finance] - +* [chains](#chains) + * Display option chains for ## volume @@ -23,3 +25,26 @@ usage: volume --expiry yyyy-mm-dd Display volume graph for a date. [Source: Yahoo Finance] * -e, --expiry : expiration date. + +## chains +Display a table of options chains. + +This data requires a Tradier sandbox developer account, which can be made [here](#https://tradier.com/products/market-data-api) + +```` +usage: chains [--calls] [--puts] [-m MIN] [-M MAX] +```` +* --calls : Flag to only display call options +* --puts : Flag to display only put options +* -m : Minimum strike price to show +* -M : Maximum strike price to show + +For combines tables, call options are on the left and put options are on the right of the strike + +As an example, if I load my ticker and select an expiry, to view the options chain for strikes between $129 and $135, one would use: + +```` +chains -m 129 -M 135 +```` +Which outputs: +![im](https://user-images.githubusercontent.com/18151143/115068041-b191da00-9ebf-11eb-941e-4e255787ab94.png) diff --git a/gamestonk_terminal/options/chains_view.py b/gamestonk_terminal/options/chains_view.py new file mode 100644 index 00000000000..c05552a909e --- /dev/null +++ b/gamestonk_terminal/options/chains_view.py @@ -0,0 +1,208 @@ +"""Helper functions for the options menu""" +__docformat__ = "numpy" + +import argparse +from typing import List +import requests +import pandas as pd +import numpy as np +from tabulate import tabulate +from gamestonk_terminal.config_terminal import TRADIER_TOKEN +from gamestonk_terminal.helper_funcs import ( + check_non_negative, + parse_known_args_and_warn, +) + +option_columns = [ + "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 +column_map = {"mid_iv": "iv", "open_interest": "oi", "volume": "vol"} + + +def process_chains(response: requests.models.Response) -> pd.DataFrame: + """ + Function to take in the requests.get and return a DataFrame + Parameters + ---------- + response: requests.models.Response + This is the respnose from tradier api. + + Returns + ------- + opt_chain: pd.DataFrame + Dataframe with all available options + """ + json_response = response.json() + options = json_response["options"]["option"] + + opt_chain = pd.DataFrame(columns=df_columns) + for idx, option in enumerate(options): + data = [option[col] for col in option_columns] + data += [option["greeks"][col] for col in greek_columns] + opt_chain.loc[idx, :] = data + + return opt_chain + + +def get_option_chains(symbol: str, expiry: str) -> pd.DataFrame: + """ + + 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 gievn Symbol and Expiration date + """ + params = {"symbol": symbol, "expiration": expiry, "greeks": "true"} + + headers = {"Authorization": f"Bearer {TRADIER_TOKEN}", "Accept": "application/json"} + + response = requests.get( + "https://sandbox.tradier.com/v1/markets/options/chains", + params=params, + headers=headers, + ) + if response.status_code == 401: + print("Error in request.get -- check token") + return + + chains = process_chains(response) + return chains + + +def display_chains(symbol: str, expiry: str, other_args: List[str]): + + parser = argparse.ArgumentParser( + prog="chains", add_help=False, description="Display options chains" + ) + + parser.add_argument( + "--calls", + action="store_true", + default=False, + dest="calls_only", + help="Flag to show calls only", + ) + + parser.add_argument( + "--puts", + action="store_true", + default=False, + dest="puts_only", + help="Flag to show puts only", + ) + parser.add_argument( + "-m", + "--min", + dest="min_sp", + type=check_non_negative, + default=-1, + help="minimum strike price to consider.", + ) + parser.add_argument( + "-M", + "--max", + dest="max_sp", + type=check_non_negative, + default=-1, + help="maximum strike price to consider.", + ) + + chains_df = get_option_chains(symbol, expiry) + + default_columns = [ + "mid_iv", + "delta", + "volume", + "open_interest", + "bid", + "ask", + "strike", + "option_type", + ] + chains_df = chains_df[default_columns].rename(columns=column_map) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + if ns_parser.max_sp == -1 and ns_parser.min_sp == -1: + min_strike = np.percentile(chains_df["strike"], 25) + max_strike = np.percentile(chains_df["strike"], 75) + else: + min_strike = ns_parser.min_sp + max_strike = ns_parser.max_sp + + chains_df = chains_df[chains_df["strike"] >= min_strike] + chains_df = chains_df[chains_df["strike"] <= max_strike] + calls_df = chains_df[chains_df.option_type == "call"].drop( + columns=["option_type"] + ) + puts_df = chains_df[chains_df.option_type == "put"].drop( + columns=["option_type"] + ) + + if ns_parser.calls_only: + print( + tabulate( + calls_df, + headers=calls_df.columns, + tablefmt="grid", + showindex=False, + floatfmt=".2f", + ) + ) + return + + if ns_parser.puts_only: + print( + tabulate( + puts_df, + headers=puts_df.columns, + tablefmt="grid", + showindex=False, + floatfmt=".2f", + ) + ) + return + + puts_df = puts_df[puts_df.columns[::-1]] + chain_table = calls_df.merge(puts_df, on="strike") + + headers = [ + col.strip("_x") + if col.endswith("_x") + else col.strip("_y") + if col.endswith("_y") + else col + for col in chain_table.columns + ] + print( + tabulate( + chain_table, + headers=headers, + tablefmt="fancy_grid", + showindex=False, + floatfmt=".2f", + ) + ) + + except Exception as e: + print(e) + print("") + return diff --git a/gamestonk_terminal/options/op_controller.py b/gamestonk_terminal/options/op_controller.py index e373ba1f677..4caa51dbd63 100644 --- a/gamestonk_terminal/options/op_controller.py +++ b/gamestonk_terminal/options/op_controller.py @@ -9,7 +9,7 @@ import yfinance as yf from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.helper_funcs import get_flair, parse_known_args_and_warn from gamestonk_terminal import feature_flags as gtff -from gamestonk_terminal.options import volume_view +from gamestonk_terminal.options import volume_view, chains_view from gamestonk_terminal.menu import session @@ -17,7 +17,7 @@ class OptionsController: """Options Controller class.""" # Command choices - CHOICES = ["help", "q", "quit", "exp", "voi", "vcalls", "vputs"] + CHOICES = ["help", "q", "quit", "exp", "voi", "vcalls", "vputs", "chains"] def __init__(self, ticker: str, last_adj_close_price: float): """Construct data.""" @@ -93,6 +93,8 @@ class OptionsController: print(" vcalls calls volume + open interest plot") print(" vputs puts volume + open interest plot") print("") + print(" chains display option chains") + print("") return def switch(self, an_input: str): @@ -158,6 +160,9 @@ class OptionsController: self.options.puts, ) + def call_chains(self, other_args): + chains_view.display_chains(self.ticker, self.expiry_date, other_args) + def menu(ticker: str, last_adj_close_price: float): """ Options Menu. """ diff --git a/gamestonk_terminal/options/volume_view.py b/gamestonk_terminal/options/volume_view.py index a20e4cafc54..a4f3062a960 100644 --- a/gamestonk_terminal/options/volume_view.py +++ b/gamestonk_terminal/options/volume_view.py @@ -2,12 +2,12 @@ __docformat__ = "numpy" from bisect import bisect_left -import seaborn as sns from typing import List import argparse import pandas as pd import matplotlib.pyplot as plt import numpy as np +import seaborn as sns from gamestonk_terminal.helper_funcs import ( plot_autoscale,