diff --git a/gamestonk_terminal/discovery/stockgrid_view.py b/gamestonk_terminal/discovery/stockgrid_view.py index bf153ef923e..36d098d93f7 100644 --- a/gamestonk_terminal/discovery/stockgrid_view.py +++ b/gamestonk_terminal/discovery/stockgrid_view.py @@ -56,16 +56,24 @@ def darkshort(other_args: List[str]): if not ns_parser: return - d_fields = { - "sv": "Short Volume", - "sv_pct": "Short Volume %", - "nsv": "Net Short Volume", - "nsv_dollar": "Net Short Volume $", - "dpp": "Dark Pools Position", - "dpp_dollar": "Dark Pools Position $", + d_fields_endpoints = { + "sv": "Short+Volume", + "sv_pct": "Short+Volume+%25", + "nsv": "Net+Short+Volume", + "nsv_dollar": "Net+Short+Volume+$", + "dpp": "Dark+Pools+Position", + "dpp_dollar": "Dark+Pools+Position+$", } - link = "https://stockgridapp.herokuapp.com/get_dark_pool_data?top=Dark+Pools+Position+$&minmax=desc" + field = d_fields_endpoints[ns_parser.sort_field] + + if ns_parser.ascending: + order = "asc" + else: + order = "desc" + + link = f"https://stockgridapp.herokuapp.com/get_dark_pool_data?top={field}&minmax={order}" + response = requests.get(link) df = pd.DataFrame(response.json()["data"]) @@ -80,7 +88,7 @@ def darkshort(other_args: List[str]): "Dark Pools Position", "Dark Pools Position $", ] - ].sort_values(by=d_fields[ns_parser.sort_field], ascending=ns_parser.ascending) + ] dp_date = df["Date"].values[0] df = df.drop(columns=["Date"]) df["Net Short Volume $"] = df["Net Short Volume $"] / 100_000_000 diff --git a/gamestonk_terminal/fundamental_analysis/README.md b/gamestonk_terminal/fundamental_analysis/README.md index 914675970e5..c0aaf16486c 100644 --- a/gamestonk_terminal/fundamental_analysis/README.md +++ b/gamestonk_terminal/fundamental_analysis/README.md @@ -19,6 +19,7 @@ This menu aims to extract all fundamentals of a pre-loaded company, and the usag * cash flow statement of the company [YAHOO FINANCE](#YAHOO_FINANCE) + * income statement of the company * [info](#info) * information scope of the company @@ -29,41 +30,12 @@ This menu aims to extract all fundamentals of a pre-loaded company, and the usag * [cal](#cal) * calendar earnings and estimates of the company -[ALPHA VANTAGE](#ALPHA_VANTAGE) -* [overview](#overview) - * overview of the company -* [incom](#incom) - * income statements of the company -* [balance](#balance) - * balance sheet of the company -* [cash](#cash) - * cash flow of the company -* [earnings](#earnings) - * earnings dates and reported EPS +[ALPHA VANTAGE menu](/gamestonk_terminal/fundamental_analysis/alpha_vantage/) -[FINANCIAL MODELING PREP](#FINANCIAL_MODELING_PREP) -* [profile](#profile) - * profile of the company -* [quote](#quote) - * quote of the company -* [enterprise](#enterprise) - * enterprise value of the company over time -* [dcf](#dcf) - * discounted cash flow of the company over time -* [inc](#inc) - * income statements of the company -* [bal](#bal) - * balance sheet of the company -* [cashf](#cashf) - * cash flow of the company -* [metrics](#metrics) - * key metrics of the company -* [ratios](#ratios) - * financial ratios of the company -* [growth](#growth) - * financial statement growth of the company +[FINANCIAL MODELING PREP menu](/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/) + **Note:** _Some of these functionalities are repeated in the sense of the overall information contained within. However, since none of the provided data is paid, there isn't a single all-time up-to-date API source. You get what you pay for. It comes to the user to select the functionalities under the API that they trust the most, or compare their outputs, and then make an informed decision._ @@ -156,181 +128,3 @@ usage: cal Calendar earnings of the company. Including revenue and earnings estimates. [Source: Yahoo Finance] -## ALPHA VANTAGE - -### overview - -```text -usage: overview -``` - -Prints an overview about the company. The following fields are expected: Symbol, Asset type, Name, Description, Exchange, Currency, Country, Sector, Industry, Address, Full time employees, Fiscal year end, Latest quarter, Market capitalization, EBITDA, PE ratio, PEG ratio, Book value, Dividend per share, Dividend yield, EPS, Revenue per share TTM, Profit margin, Operating margin TTM, Return on assets TTM, Return on equity TTM, Revenue TTM, Gross profit TTM, Diluted EPS TTM, Quarterly earnings growth YOY, Quarterly revenue growth YOY, Analyst target price, Trailing PE, Forward PE, Price to sales ratio TTM, Price to book ratio, EV to revenue, EV to EBITDA, Beta, 52 week high, 52 week low, 50 day moving average, 200 day moving average, Shares outstanding, Shares float, Shares short, Shares short prior month, Short ratio, Short percent outstanding, Short percent float, Percent insiders, Percent institutions, Forward annual dividend rate, Forward annual dividend yield, Payout ratio, Dividend date, Ex dividend date, Last split factor, and Last split date. [Source: Alpha Vantage] - -### incom - -```text -usage: income [-n N_NUM] [-q] -``` - -Prints a complete income statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Cost and expenses, Cost of revenue, Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date, Final link, General and administrative expenses, Gross profit, Gross profit ratio, Income before tax, Income before tax ratio, Income tax expense, Interest expense, Link, Net income, Net income ratio, Operating expenses, Operating income, Operating income ratio, Other expenses, Period, Research and development expenses, Revenue, Selling and marketing expenses, Total other income expenses net, Weighted average shs out, Weighted average shs out dil [Source: Alpha Vantage] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### balance - -```text -usage: balance [-n N_NUM] [-q] -``` - -Prints a complete balance sheet statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Account payables, Accumulated other comprehensive income loss, Cash and cash equivalents, Cash and short term investments, Common stock, Deferred revenue, Deferred revenue non current, Deferred tax liabilities non current, Filling date, Final link, Goodwill, Goodwill and intangible assets, Intangible assets, Inventory, Link, Long term debt, Long term investments, Net debt, Net receivables, Other assets, Other current assets, Other current liabilities, Other liabilities, Other non current assets, Other non current liabilities, Othertotal stockholders equity, Period, Property plant equipment net, Retained earnings, Short term debt, Short term investments, Tax assets, Tax payables, Total assets, Total current assets, Total current liabilities, Total debt, Total investments, Total liabilities, Total liabilities and stockholders equity, Total non current assets, Total non current liabilities, and Total stockholders equity. [Source: Alpha Vantage] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### cash - -```text -usage: cash [-n N_NUM] [-q] -``` - -Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Alpha Vantage] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Alpha Vantage] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### earnings - -```text -usage: earnings [-n N_NUM] [-q] -``` - -Print earnings dates and reported EPS of the company. The following fields are expected: Fiscal Date Ending and Reported EPS. [Source: Alpha Vantage] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -## FINANCIAL MODELING PREP - -### profile - -```text -usage: profile -``` - -Prints information about, among other things, the industry, sector exchange and company description. The following fields are expected: Address, Beta, Ceo, Changes, Cik, City, Company name, Country, Currency, Cusip, Dcf, Dcf diff, Default image, Description, Exchange, Exchange short name, Full time employees, Image, Industry, Ipo date, Isin, Last div, Mkt cap, Phone, Price, Range, Sector, State, Symbol, Vol avg, Website, Zip. [Source: Financial Modeling Prep] - -### quote - -```text -usage: quote -``` - -Prints actual information about the company which is, among other things, the day high, market cap, open and close price and price-to-equity ratio. The following fields are expected: Avg volume, Change, Changes percentage, Day high, Day low, Earnings announcement, Eps, Exchange, Market cap, Name, Open, Pe, Previous close, Price, Price avg200, Price avg50, Shares outstanding, Symbol, Timestamp, Volume, Year high, and Year low. [Source: Financial Modeling Prep] - -### enterprise - -```text -usage: enterprise [-n N_NUM] [-q] -``` - -Prints stock price, number of shares, market capitalization and enterprise value over time. The following fields are expected: Add total debt, Enterprise value, Market capitalization, Minus cash and cash equivalents, Number of shares, Stock price, and Symbol. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### dcf - -```text -usage: dcf [-n N_NUM] [-q] -``` - -Prints the discounted cash flow of a company over time including the DCF of today. The following fields are expected: DCF, Stock price, and Date. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### inc - -```text -usage: inc [-n N_NUM] [-q] -``` - -Prints a complete income statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Cost and expenses, Cost of revenue, Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date, Final link, General and administrative expenses, Gross profit, Gross profit ratio, Income before tax, Income before tax ratio, Income tax expense, Interest expense, Link, Net income, Net income ratio, Operating expenses, Operating income, Operating income ratio, Other expenses, Period, Research and development expenses, Revenue, Selling and marketing expenses, Total other income expenses net, Weighted average shs out, Weighted average shs out dil [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### bal - -```text -usage: bal [-n N_NUM] [-q] -``` - -Prints a complete balance sheet statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Account payables, Accumulated other comprehensive income loss, Cash and cash equivalents, Cash and short term investments, Common stock, Deferred revenue, Deferred revenue non current, Deferred tax liabilities non current, Filling date, Final link, Goodwill, Goodwill and intangible assets, Intangible assets, Inventory, Link, Long term debt, Long term investments, Net debt, Net receivables, Other assets, Other current assets, Other current liabilities, Other liabilities, Other non current assets, Other non current liabilities, Othertotal stockholders equity, Period, Property plant equipment net, Retained earnings, Short term debt, Short term investments, Tax assets, Tax payables, Total assets, Total current assets, Total current liabilities, Total debt, Total investments, Total liabilities, Total liabilities and stockholders equity, Total non current assets, Total non current liabilities, and Total stockholders equity. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### cashf - -```text -usage: cashf [-n N_NUM] [-q] -``` - -Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### metrics - -```text -usage: metrics [-n N_NUM] [-q] -``` - -Prints a list of the key metrics of a company over time. This can be either quarterly or annually. This includes, among other things, Return on Equity (ROE), Working Capital, Current Ratio and Debt to Assets. The following fields are expected: Average inventory, Average payables, Average receivables, Book value per share, Capex per share, Capex to depreciation, Capex to operating cash flow, Capex to revenue, Cash per share, Current ratio, Days of inventory on hand, Days payables outstanding, Days sales outstanding, Debt to assets, Debt to equity, Dividend yield, Earnings yield, Enterprise value, Enterprise value over EBITDA, Ev to free cash flow, Ev to operating cash flow, Ev to sales, Free cash flow per share, Free cash flow yield, Graham net net, Graham number, Income quality, Intangibles to total assets, Interest debt per share, Inventory turnover, Market cap, Net current asset value, Net debt to EBITDA, Net income per share, Operating cash flow per share, Payables turnover, Payout ratio, Pb ratio, Pe ratio, Pfcf ratio, Pocfratio, Price to sales ratio, Ptb ratio, Receivables turnover, Research and ddevelopement to revenue, Return on tangible assets, Revenue per share, Roe, Roic, Sales general and administrative to revenue, Shareholders equity per share, Stock based compensation to revenue, Tangible book value per share, and Working capital. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### ratios - -```text -usage: ratios [-n N_NUM] [-q] -``` - -Prints in-depth ratios of a company over time. This can be either quarterly or annually. This contains, among other things, Price-to-Book Ratio, Payout Ratio and Operating Cycle. The following fields are expected: Asset turnover, Capital expenditure coverage ratio, Cash conversion cycle, Cash flow coverage ratios, Cash flow to debt ratio, Cash per share, Cash ratio, Company equity multiplier, Current ratio, Days of inventory outstanding, Days of payables outstanding, Days of sales outstanding, Debt equity ratio, Debt ratio, Dividend paid and capex coverage ratio, Dividend payout ratio, Dividend yield, Ebit per revenue, Ebt per ebit, Effective tax rate, Enterprise value multiple, Fixed asset turnover, Free cash flow operating cash flow ratio, Free cash flow per share, Gross profit margin, Inventory turnover, Long term debt to capitalization, Net income per EBT, Net profit margin, Operating cash flow per share, Operating cash flow sales ratio, Operating cycle, Operating profit margin, Payables turnover, Payout ratio, Pretax profit margin, Price book value ratio, Price cash flow ratio, Price earnings ratio, Price earnings to growth ratio, Price fair value, Price sales ratio, Price to book ratio, Price to free cash flows ratio, Price to operating cash flows ratio, Price to sales ratio, Quick ratio, Receivables turnover, Return on assets, Return on capital employed, Return on equity, Short term coverage ratios, and Total debt to capitalization. [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - -### growth - -```text -usage: growth [-n N_NUM] [-q] -``` - -Prints the growth of several financial statement items and ratios over time. This can be either annually and quarterly. These are, among other things, Revenue Growth (3, 5 and 10 years), inventory growth and operating cash flow growth (3, 5 and 10 years). The following fields are expected: Asset growth, Book valueper share growth, Debt growth, Dividendsper share growth, Ebitgrowth, Epsdiluted growth, Epsgrowth, Five y dividendper share growth per share, Five y net income growth per share, Five y operating c f growth per share, Five y revenue growth per share, Five y shareholders equity growth per share, Free cash flow growth, Gross profit growth, Inventory growth, Net income growth, Operating cash flow growth, Operating income growth, Rdexpense growth, Receivables growth, Revenue growth, Sgaexpenses growth, Ten y dividendper share growth per share, Ten y net income growth per share, Ten y operating c f growth per share, Ten y revenue growth per share, Ten y shareholders equity growth per share, Three y dividendper share growth per share, Three y net income growth per share, Three y operating c f growth per share, Three y revenue growth per share, Three y shareholders equity growth per share, Weighted average shares diluted growth, and Weighted average shares growth [Source: Financial Modeling Prep] - -* n : Number of latest years/quarters. Default 1. -* q : Quarter fundamental data flag. Default False. - - -### score - -```text -usage: score -``` - -Value investing tool based on Warren Buffett, Joseph Piotroski and Benjamin Graham thoughts [Source: Financial Modeling Prep] diff --git a/gamestonk_terminal/fundamental_analysis/alpha_vantage/README.md b/gamestonk_terminal/fundamental_analysis/alpha_vantage/README.md new file mode 100644 index 00000000000..ba64b07f8de --- /dev/null +++ b/gamestonk_terminal/fundamental_analysis/alpha_vantage/README.md @@ -0,0 +1,67 @@ +# ALPHA VANTAGE + +This menu aims to provide fundamental analysis of a company based on Alpha Vantage data. + +* [overview](#overview) + * overview of the company +* [incom](#incom) + * income statements of the company +* [balance](#balance) + * balance sheet of the company +* [cash](#cash) + * cash flow of the company +* [earnings](#earnings) + * earnings dates and reported EPS + + +### overview + +```text +usage: overview +``` + +Prints an overview about the company. The following fields are expected: Symbol, Asset type, Name, Description, Exchange, Currency, Country, Sector, Industry, Address, Full time employees, Fiscal year end, Latest quarter, Market capitalization, EBITDA, PE ratio, PEG ratio, Book value, Dividend per share, Dividend yield, EPS, Revenue per share TTM, Profit margin, Operating margin TTM, Return on assets TTM, Return on equity TTM, Revenue TTM, Gross profit TTM, Diluted EPS TTM, Quarterly earnings growth YOY, Quarterly revenue growth YOY, Analyst target price, Trailing PE, Forward PE, Price to sales ratio TTM, Price to book ratio, EV to revenue, EV to EBITDA, Beta, 52 week high, 52 week low, 50 day moving average, 200 day moving average, Shares outstanding, Shares float, Shares short, Shares short prior month, Short ratio, Short percent outstanding, Short percent float, Percent insiders, Percent institutions, Forward annual dividend rate, Forward annual dividend yield, Payout ratio, Dividend date, Ex dividend date, Last split factor, and Last split date. [Source: Alpha Vantage] + +### incom + +```text +usage: income [-n N_NUM] [-q] +``` + +Prints a complete income statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Cost and expenses, Cost of revenue, Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date, Final link, General and administrative expenses, Gross profit, Gross profit ratio, Income before tax, Income before tax ratio, Income tax expense, Interest expense, Link, Net income, Net income ratio, Operating expenses, Operating income, Operating income ratio, Other expenses, Period, Research and development expenses, Revenue, Selling and marketing expenses, Total other income expenses net, Weighted average shs out, Weighted average shs out dil [Source: Alpha Vantage] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### balance + +```text +usage: balance [-n N_NUM] [-q] +``` + +Prints a complete balance sheet statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Account payables, Accumulated other comprehensive income loss, Cash and cash equivalents, Cash and short term investments, Common stock, Deferred revenue, Deferred revenue non current, Deferred tax liabilities non current, Filling date, Final link, Goodwill, Goodwill and intangible assets, Intangible assets, Inventory, Link, Long term debt, Long term investments, Net debt, Net receivables, Other assets, Other current assets, Other current liabilities, Other liabilities, Other non current assets, Other non current liabilities, Othertotal stockholders equity, Period, Property plant equipment net, Retained earnings, Short term debt, Short term investments, Tax assets, Tax payables, Total assets, Total current assets, Total current liabilities, Total debt, Total investments, Total liabilities, Total liabilities and stockholders equity, Total non current assets, Total non current liabilities, and Total stockholders equity. [Source: Alpha Vantage] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### cash + +```text +usage: cash [-n N_NUM] [-q] +``` + +Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Alpha Vantage] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### earnings + +```text +usage: earnings [-n N_NUM] [-q] +``` + +Print earnings dates and reported EPS of the company. The following fields are expected: Fiscal Date Ending and Reported EPS. [Source: Alpha Vantage] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. diff --git a/gamestonk_terminal/fundamental_analysis/alpha_vantage_controller.py b/gamestonk_terminal/fundamental_analysis/alpha_vantage/av_controller.py similarity index 92% rename from gamestonk_terminal/fundamental_analysis/alpha_vantage_controller.py rename to gamestonk_terminal/fundamental_analysis/alpha_vantage/av_controller.py index 7591d0666d2..c169aa7b009 100644 --- a/gamestonk_terminal/fundamental_analysis/alpha_vantage_controller.py +++ b/gamestonk_terminal/fundamental_analysis/alpha_vantage/av_controller.py @@ -5,7 +5,7 @@ import argparse from typing import List from prompt_toolkit.completion import NestedCompleter -from gamestonk_terminal.fundamental_analysis import alpha_vantage_view as avv +from gamestonk_terminal.fundamental_analysis.alpha_vantage import av_view from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import get_flair from gamestonk_terminal.menu import session @@ -104,27 +104,27 @@ class AlphaVantageController: def call_overview(self, other_args: List[str]): """Process overview command""" - avv.overview(other_args, self.ticker) + av_view.overview(other_args, self.ticker) def call_key(self, other_args: List[str]): """Process overview command""" - avv.key(other_args, self.ticker) + av_view.key(other_args, self.ticker) def call_income(self, other_args: List[str]): """Process income command""" - avv.income_statement(other_args, self.ticker) + av_view.income_statement(other_args, self.ticker) def call_balance(self, other_args: List[str]): """Process balance command""" - avv.balance_sheet(other_args, self.ticker) + av_view.balance_sheet(other_args, self.ticker) def call_cash(self, other_args: List[str]): """Process cash command""" - avv.cash_flow(other_args, self.ticker) + av_view.cash_flow(other_args, self.ticker) def call_earnings(self, other_args: List[str]): """Process earnings command""" - avv.earnings(other_args, self.ticker) + av_view.earnings(other_args, self.ticker) def menu(ticker: str, start: str, interval: str): diff --git a/gamestonk_terminal/fundamental_analysis/alpha_vantage_view.py b/gamestonk_terminal/fundamental_analysis/alpha_vantage/av_view.py similarity index 100% rename from gamestonk_terminal/fundamental_analysis/alpha_vantage_view.py rename to gamestonk_terminal/fundamental_analysis/alpha_vantage/av_view.py diff --git a/gamestonk_terminal/fundamental_analysis/fa_controller.py b/gamestonk_terminal/fundamental_analysis/fa_controller.py index a282942c1c3..6e0ecfe6212 100644 --- a/gamestonk_terminal/fundamental_analysis/fa_controller.py +++ b/gamestonk_terminal/fundamental_analysis/fa_controller.py @@ -5,11 +5,11 @@ import argparse from typing import List from prompt_toolkit.completion import NestedCompleter -from gamestonk_terminal.fundamental_analysis import alpha_vantage_controller as avc -from gamestonk_terminal.fundamental_analysis import business_insider_view as biw -from gamestonk_terminal.fundamental_analysis import ( - financial_modeling_prep_controller as fmpc, - financial_modeling_prep_view as fmpv, +from gamestonk_terminal.fundamental_analysis.alpha_vantage import av_controller +from gamestonk_terminal.fundamental_analysis import business_insider_view +from gamestonk_terminal.fundamental_analysis.financial_modeling_prep import ( + fmp_controller, + fmp_view, ) from gamestonk_terminal.fundamental_analysis import finviz_view from gamestonk_terminal.fundamental_analysis import market_watch_view @@ -136,7 +136,7 @@ class FundamentalAnalysisController: def call_mgmt(self, other_args: List[str]): """Process mgmt command""" - biw.management(other_args, self.ticker) + business_insider_view.management(other_args, self.ticker) def call_screener(self, other_args: List[str]): """Process screener command""" @@ -144,7 +144,7 @@ class FundamentalAnalysisController: def call_score(self, other_args: List[str]): """Process score command""" - fmpv.valinvest_score(other_args, self.ticker) + fmp_view.valinvest_score(other_args, self.ticker) def call_income(self, other_args: List[str]): """Process income command""" @@ -174,18 +174,16 @@ class FundamentalAnalysisController: """Process cal command""" yahoo_finance_view.calendar_earnings(other_args, self.ticker) - # pylint: disable=unused-argument - def call_av(self, other_args: List[str]): + def call_av(self, _): """Process av command""" - ret = avc.menu(self.ticker, self.start, self.interval) + ret = av_controller.menu(self.ticker, self.start, self.interval) if ret is not True: self.print_help() - # pylint: disable=unused-argument - def call_fmp(self, other_args: List[str]): + def call_fmp(self, _): """Process fmp command""" - ret = fmpc.menu(self.ticker, self.start, self.interval) + ret = fmp_controller.menu(self.ticker, self.start, self.interval) if ret is not True: self.print_help() diff --git a/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/README.md b/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/README.md new file mode 100644 index 00000000000..2f99ca081be --- /dev/null +++ b/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/README.md @@ -0,0 +1,143 @@ +# FINANCIAL MODELING PREP + +This menu aims to provide fundamental analysis of a company based on Financial Modeling Prep data. + +* [profile](#profile) + * profile of the company +* [quote](#quote) + * quote of the company +* [enterprise](#enterprise) + * enterprise value of the company over time +* [dcf](#dcf) + * discounted cash flow of the company over time +* [inc](#inc) + * income statements of the company +* [bal](#bal) + * balance sheet of the company +* [cashf](#cashf) + * cash flow of the company +* [metrics](#metrics) + * key metrics of the company +* [ratios](#ratios) + * financial ratios of the company +* [growth](#growth) + * financial statement growth of the company + + +### profile + +```text +usage: profile +``` + +Prints information about, among other things, the industry, sector exchange and company description. The following fields are expected: Address, Beta, Ceo, Changes, Cik, City, Company name, Country, Currency, Cusip, Dcf, Dcf diff, Default image, Description, Exchange, Exchange short name, Full time employees, Image, Industry, Ipo date, Isin, Last div, Mkt cap, Phone, Price, Range, Sector, State, Symbol, Vol avg, Website, Zip. [Source: Financial Modeling Prep] + +### quote + +```text +usage: quote +``` + +Prints actual information about the company which is, among other things, the day high, market cap, open and close price and price-to-equity ratio. The following fields are expected: Avg volume, Change, Changes percentage, Day high, Day low, Earnings announcement, Eps, Exchange, Market cap, Name, Open, Pe, Previous close, Price, Price avg200, Price avg50, Shares outstanding, Symbol, Timestamp, Volume, Year high, and Year low. [Source: Financial Modeling Prep] + +### enterprise + +```text +usage: enterprise [-n N_NUM] [-q] +``` + +Prints stock price, number of shares, market capitalization and enterprise value over time. The following fields are expected: Add total debt, Enterprise value, Market capitalization, Minus cash and cash equivalents, Number of shares, Stock price, and Symbol. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### dcf + +```text +usage: dcf [-n N_NUM] [-q] +``` + +Prints the discounted cash flow of a company over time including the DCF of today. The following fields are expected: DCF, Stock price, and Date. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### inc + +```text +usage: inc [-n N_NUM] [-q] +``` + +Prints a complete income statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Cost and expenses, Cost of revenue, Depreciation and amortization, Ebitda, Ebitdaratio, Eps, Epsdiluted, Filling date, Final link, General and administrative expenses, Gross profit, Gross profit ratio, Income before tax, Income before tax ratio, Income tax expense, Interest expense, Link, Net income, Net income ratio, Operating expenses, Operating income, Operating income ratio, Other expenses, Period, Research and development expenses, Revenue, Selling and marketing expenses, Total other income expenses net, Weighted average shs out, Weighted average shs out dil [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### bal + +```text +usage: bal [-n N_NUM] [-q] +``` + +Prints a complete balance sheet statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Account payables, Accumulated other comprehensive income loss, Cash and cash equivalents, Cash and short term investments, Common stock, Deferred revenue, Deferred revenue non current, Deferred tax liabilities non current, Filling date, Final link, Goodwill, Goodwill and intangible assets, Intangible assets, Inventory, Link, Long term debt, Long term investments, Net debt, Net receivables, Other assets, Other current assets, Other current liabilities, Other liabilities, Other non current assets, Other non current liabilities, Othertotal stockholders equity, Period, Property plant equipment net, Retained earnings, Short term debt, Short term investments, Tax assets, Tax payables, Total assets, Total current assets, Total current liabilities, Total debt, Total investments, Total liabilities, Total liabilities and stockholders equity, Total non current assets, Total non current liabilities, and Total stockholders equity. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### cashf + +```text +usage: cashf [-n N_NUM] [-q] +``` + +Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +Prints a complete cash flow statement over time. This can be either quarterly or annually. The following fields are expected: Accepted date, Accounts payables, Accounts receivables, Acquisitions net, Capital expenditure, Cash at beginning of period, Cash at end of period, Change in working capital, Common stock issued, Common stock repurchased, Debt repayment, Deferred income tax, Depreciation and amortization, Dividends paid, Effect of forex changes on cash, Filling date, Final link, Free cash flow, Inventory, Investments in property plant and equipment, Link, Net cash provided by operating activities, Net cash used for investing activities, Net cash used provided by financing activities, Net change in cash, Net income, Operating cash flow, Other financing activities, Other investing activities, Other non cash items, Other working capital, Period, Purchases of investments, Sales maturities of investments, Stock based compensation. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### metrics + +```text +usage: metrics [-n N_NUM] [-q] +``` + +Prints a list of the key metrics of a company over time. This can be either quarterly or annually. This includes, among other things, Return on Equity (ROE), Working Capital, Current Ratio and Debt to Assets. The following fields are expected: Average inventory, Average payables, Average receivables, Book value per share, Capex per share, Capex to depreciation, Capex to operating cash flow, Capex to revenue, Cash per share, Current ratio, Days of inventory on hand, Days payables outstanding, Days sales outstanding, Debt to assets, Debt to equity, Dividend yield, Earnings yield, Enterprise value, Enterprise value over EBITDA, Ev to free cash flow, Ev to operating cash flow, Ev to sales, Free cash flow per share, Free cash flow yield, Graham net net, Graham number, Income quality, Intangibles to total assets, Interest debt per share, Inventory turnover, Market cap, Net current asset value, Net debt to EBITDA, Net income per share, Operating cash flow per share, Payables turnover, Payout ratio, Pb ratio, Pe ratio, Pfcf ratio, Pocfratio, Price to sales ratio, Ptb ratio, Receivables turnover, Research and ddevelopement to revenue, Return on tangible assets, Revenue per share, Roe, Roic, Sales general and administrative to revenue, Shareholders equity per share, Stock based compensation to revenue, Tangible book value per share, and Working capital. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### ratios + +```text +usage: ratios [-n N_NUM] [-q] +``` + +Prints in-depth ratios of a company over time. This can be either quarterly or annually. This contains, among other things, Price-to-Book Ratio, Payout Ratio and Operating Cycle. The following fields are expected: Asset turnover, Capital expenditure coverage ratio, Cash conversion cycle, Cash flow coverage ratios, Cash flow to debt ratio, Cash per share, Cash ratio, Company equity multiplier, Current ratio, Days of inventory outstanding, Days of payables outstanding, Days of sales outstanding, Debt equity ratio, Debt ratio, Dividend paid and capex coverage ratio, Dividend payout ratio, Dividend yield, Ebit per revenue, Ebt per ebit, Effective tax rate, Enterprise value multiple, Fixed asset turnover, Free cash flow operating cash flow ratio, Free cash flow per share, Gross profit margin, Inventory turnover, Long term debt to capitalization, Net income per EBT, Net profit margin, Operating cash flow per share, Operating cash flow sales ratio, Operating cycle, Operating profit margin, Payables turnover, Payout ratio, Pretax profit margin, Price book value ratio, Price cash flow ratio, Price earnings ratio, Price earnings to growth ratio, Price fair value, Price sales ratio, Price to book ratio, Price to free cash flows ratio, Price to operating cash flows ratio, Price to sales ratio, Quick ratio, Receivables turnover, Return on assets, Return on capital employed, Return on equity, Short term coverage ratios, and Total debt to capitalization. [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + +### growth + +```text +usage: growth [-n N_NUM] [-q] +``` + +Prints the growth of several financial statement items and ratios over time. This can be either annually and quarterly. These are, among other things, Revenue Growth (3, 5 and 10 years), inventory growth and operating cash flow growth (3, 5 and 10 years). The following fields are expected: Asset growth, Book valueper share growth, Debt growth, Dividendsper share growth, Ebitgrowth, Epsdiluted growth, Epsgrowth, Five y dividendper share growth per share, Five y net income growth per share, Five y operating c f growth per share, Five y revenue growth per share, Five y shareholders equity growth per share, Free cash flow growth, Gross profit growth, Inventory growth, Net income growth, Operating cash flow growth, Operating income growth, Rdexpense growth, Receivables growth, Revenue growth, Sgaexpenses growth, Ten y dividendper share growth per share, Ten y net income growth per share, Ten y operating c f growth per share, Ten y revenue growth per share, Ten y shareholders equity growth per share, Three y dividendper share growth per share, Three y net income growth per share, Three y operating c f growth per share, Three y revenue growth per share, Three y shareholders equity growth per share, Weighted average shares diluted growth, and Weighted average shares growth [Source: Financial Modeling Prep] + +* n : Number of latest years/quarters. Default 1. +* q : Quarter fundamental data flag. Default False. + + +### score + +```text +usage: score +``` + +Value investing tool based on Warren Buffett, Joseph Piotroski and Benjamin Graham thoughts [Source: Financial Modeling Prep] diff --git a/gamestonk_terminal/fundamental_analysis/financial_modeling_prep_controller.py b/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/fmp_controller.py similarity index 89% rename from gamestonk_terminal/fundamental_analysis/financial_modeling_prep_controller.py rename to gamestonk_terminal/fundamental_analysis/financial_modeling_prep/fmp_controller.py index d8b8dbf15ae..ba4c546f41a 100644 --- a/gamestonk_terminal/fundamental_analysis/financial_modeling_prep_controller.py +++ b/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/fmp_controller.py @@ -5,7 +5,7 @@ import argparse from typing import List from prompt_toolkit.completion import NestedCompleter -from gamestonk_terminal.fundamental_analysis import financial_modeling_prep_view as fmpv +from gamestonk_terminal.fundamental_analysis.financial_modeling_prep import fmp_view from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( get_flair, @@ -114,43 +114,43 @@ class FinancialModelingPrepController: def call_profile(self, other_args: List[str]): """Process profile command""" - fmpv.profile(other_args, self.ticker) + fmp_view.profile(other_args, self.ticker) def call_quote(self, other_args: List[str]): """Process quote command""" - fmpv.quote(other_args, self.ticker) + fmp_view.quote(other_args, self.ticker) def call_enterprise(self, other_args: List[str]): """Process income command""" - fmpv.enterprise(other_args, self.ticker) + fmp_view.enterprise(other_args, self.ticker) def call_dcf(self, other_args: List[str]): """Process dcf command""" - fmpv.discounted_cash_flow(other_args, self.ticker) + fmp_view.discounted_cash_flow(other_args, self.ticker) def call_income(self, other_args: List[str]): """Process income command""" - fmpv.income_statement(other_args, self.ticker) + fmp_view.income_statement(other_args, self.ticker) def call_balance(self, other_args: List[str]): """Process balance command""" - fmpv.balance_sheet(other_args, self.ticker) + fmp_view.balance_sheet(other_args, self.ticker) def call_cash(self, other_args: List[str]): """Process cash command""" - fmpv.cash_flow(other_args, self.ticker) + fmp_view.cash_flow(other_args, self.ticker) def call_metrics(self, other_args: List[str]): """Process metrics command""" - fmpv.key_metrics(other_args, self.ticker) + fmp_view.key_metrics(other_args, self.ticker) def call_ratios(self, other_args: List[str]): """Process cash command""" - fmpv.financial_ratios(other_args, self.ticker) + fmp_view.financial_ratios(other_args, self.ticker) def call_growth(self, other_args: List[str]): """Process cash command""" - fmpv.financial_statement_growth(other_args, self.ticker) + fmp_view.financial_statement_growth(other_args, self.ticker) def menu(ticker: str, start: str, interval: str): diff --git a/gamestonk_terminal/fundamental_analysis/financial_modeling_prep_view.py b/gamestonk_terminal/fundamental_analysis/financial_modeling_prep/fmp_view.py similarity index 100% rename from gamestonk_terminal/fundamental_analysis/financial_modeling_prep_view.py rename to gamestonk_terminal/fundamental_analysis/financial_modeling_prep/fmp_view.py diff --git a/gamestonk_terminal/main_helper.py b/gamestonk_terminal/main_helper.py index cb331b80dea..28d3ba39e95 100644 --- a/gamestonk_terminal/main_helper.py +++ b/gamestonk_terminal/main_helper.py @@ -138,7 +138,7 @@ def load(other_args: List[str], s_ticker, s_start, s_interval, df_stock): try: # For the case where a user uses: 'load BB' if other_args: - if "-" not in other_args[0]: + if "-t" not in other_args: other_args.insert(0, "-t") ns_parser = parse_known_args_and_warn(parser, other_args) diff --git a/gamestonk_terminal/options/README.md b/gamestonk_terminal/options/README.md index 7413f9a88aa..09adc30801f 100644 --- a/gamestonk_terminal/options/README.md +++ b/gamestonk_terminal/options/README.md @@ -1,6 +1,6 @@ # OPTIONS -This menu aims to give insight on options. +This menu aims to give insight on options. 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. The usage of the following commands along with an example will be exploited below: @@ -96,7 +96,7 @@ Display options chains. [Source: Tradier] ## info This scrapes the options information from barchart.com/stocks overview. This includes information such as Historical Volatility and IV Rank. -In order to run, the selenium webdriver must be installed. +In order to run, the selenium webdriver must be installed. Currently, this runs on either Chrome or Firefox. The path to the driver should be defined in [config_terminal.py](#config_terminal.py). Note this may take more time than other commands to process. diff --git a/gamestonk_terminal/options/op_scrape_view.py b/gamestonk_terminal/options/barchart_view.py similarity index 100% rename from gamestonk_terminal/options/op_scrape_view.py rename to gamestonk_terminal/options/barchart_view.py diff --git a/gamestonk_terminal/options/op_controller.py b/gamestonk_terminal/options/op_controller.py index c31ef57867f..3025ce1da4e 100644 --- a/gamestonk_terminal/options/op_controller.py +++ b/gamestonk_terminal/options/op_controller.py @@ -10,7 +10,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, chains_view, op_scrape_view +from gamestonk_terminal.options import yahoo_view, tradier_view, barchart_view from gamestonk_terminal.menu import session @@ -133,7 +133,7 @@ class OptionsController: def call_voi(self, other_args: List[str]): """Process voi command.""" - volume_view.plot_volume_open_interest( + yahoo_view.plot_volume_open_interest( other_args, self.ticker, self.expiry_date, @@ -144,7 +144,7 @@ class OptionsController: def call_vcalls(self, other_args: List[str]): """Process vcalls command.""" - volume_view.plot_calls_volume_open_interest( + yahoo_view.plot_calls_volume_open_interest( other_args, self.ticker, self.expiry_date, @@ -154,7 +154,7 @@ class OptionsController: def call_vputs(self, other_args: List[str]): """Process vcalls command.""" - volume_view.plot_puts_volume_open_interest( + yahoo_view.plot_puts_volume_open_interest( other_args, self.ticker, self.expiry_date, @@ -163,10 +163,10 @@ class OptionsController: ) def call_chains(self, other_args): - chains_view.display_chains(self.ticker, self.expiry_date, other_args) + tradier_view.display_chains(self.ticker, self.expiry_date, other_args) def call_info(self, other_args): - op_scrape_view.print_options_data(self.ticker, other_args) + barchart_view.print_options_data(self.ticker, other_args) def menu(ticker: str, stock: pd.DataFrame): diff --git a/gamestonk_terminal/options/chains_view.py b/gamestonk_terminal/options/tradier_view.py similarity index 83% rename from gamestonk_terminal/options/chains_view.py rename to gamestonk_terminal/options/tradier_view.py index 8a1afdefdd7..3b063c662ea 100644 --- a/gamestonk_terminal/options/chains_view.py +++ b/gamestonk_terminal/options/tradier_view.py @@ -99,9 +99,9 @@ def get_option_chains(symbol: str, expiry: str) -> pd.DataFrame: params=params, headers=headers, ) - if response.status_code == 401: - print("Error in request.get -- check token") - return + if response.status_code != 200: + print("Error in request. Check TRADIER_TOKEN\n") + return pd.DataFrame() chains = process_chains(response) return chains @@ -156,21 +156,31 @@ def display_chains(symbol: str, expiry: str, other_args: List[str]): "gamma, theta, vega, ask_iv, bid_iv, mid_iv} ", ) - chains_df = get_option_chains(symbol, expiry) - try: ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return + + chains_df = get_option_chains(symbol, expiry) + + if chains_df.empty: + return + columns = ns_parser.to_display + ["strike", "option_type"] chains_df = chains_df[columns].rename(columns=column_map) - if ns_parser.max_sp == -1 and ns_parser.min_sp == -1: + + if 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 + + if ns_parser.max_sp == -1: + max_strike = np.percentile(chains_df["strike"], 75) + else: max_strike = ns_parser.max_sp + print(f"The strike prices are displayed between {min_strike} and {max_strike}") + 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( @@ -190,9 +200,8 @@ def display_chains(symbol: str, expiry: str, other_args: List[str]): floatfmt=".2f", ) ) - return - if ns_parser.puts_only: + elif ns_parser.puts_only: print( tabulate( puts_df, @@ -202,31 +211,30 @@ def display_chains(symbol: str, expiry: str, other_args: List[str]): floatfmt=".2f", ) ) - return - puts_df = puts_df[puts_df.columns[::-1]] - chain_table = calls_df.merge(puts_df, on="strike") + else: + 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", + 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", + ) ) - ) print("") except Exception as e: - print(e) - print("") + print(e, "\n") return diff --git a/gamestonk_terminal/options/volume_helper.py b/gamestonk_terminal/options/volume_helper.py deleted file mode 100644 index 4a0f40d03c5..00000000000 --- a/gamestonk_terminal/options/volume_helper.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Functions for analyzing options data""" -__docformat__ = "numpy" -from typing import Union -import pandas as pd -import numpy as np - - -def get_loss_at_strike( - strike: Union[int, float], chain: pd.DataFrame -) -> Union[int, float]: - """ - Function to get the loss at the given expiry - Parameters - ---------- - strike: Union[int,float] - Value to calculate total loss at - chain: Dataframe: - Dataframe containing at least strike and openInterest - - Returns - ------- - loss: Union[float,int] - Total loss - """ - - itm_calls = chain[chain.index < strike][["OI_call"]] - itm_calls["loss"] = (strike - itm_calls.index) * itm_calls["OI_call"] - call_loss = itm_calls["loss"].sum() - # The *-1 below is due to a sign change for plotting in the _view code - itm_puts = chain[chain.index > strike][["OI_put"]] - itm_puts["loss"] = (itm_puts.index - strike) * itm_puts["OI_put"] * -1 - put_loss = itm_puts.loss.sum() - loss = call_loss + put_loss - return loss - - -def get_max_pain(chain: pd.DataFrame) -> Union[int, float]: - """ - Returns the max pain for a given call/put dataframe - Parameters - ---------- - chain: DataFrame - Dataframe to calculate value from - - Returns - ------- - max_pain : - Max pain value - """ - - strikes = np.array(chain.index) - if ("OI_call" not in chain.columns) or ("OI_put" not in chain.columns): - print("Incorrect columns. Unable to parse max pain") - return np.nan - - loss = [] - for price_at_exp in strikes: - loss.append(get_loss_at_strike(price_at_exp, chain)) - - chain["loss"] = loss - max_pain = chain["loss"].idxmin() - - return max_pain diff --git a/gamestonk_terminal/options/volume_view.py b/gamestonk_terminal/options/yahoo_view.py similarity index 89% rename from gamestonk_terminal/options/volume_view.py rename to gamestonk_terminal/options/yahoo_view.py index 9558690ff3c..d1e3dc15b96 100644 --- a/gamestonk_terminal/options/volume_view.py +++ b/gamestonk_terminal/options/yahoo_view.py @@ -16,7 +16,6 @@ from gamestonk_terminal.helper_funcs import ( ) from gamestonk_terminal import config_plot as cfgPlot from gamestonk_terminal import feature_flags as gtff -from gamestonk_terminal.options.volume_helper import get_max_pain def plot_volume_open_interest( @@ -460,3 +459,59 @@ def plot_puts_volume_open_interest( except Exception as e: print(e, "\n") return + + +def get_loss_at_strike(strike: float, chain: pd.DataFrame) -> float: + """ + Function to get the loss at the given expiry + Parameters + ---------- + strike: Union[int,float] + Value to calculate total loss at + chain: Dataframe: + Dataframe containing at least strike and openInterest + + Returns + ------- + loss: Union[float,int] + Total loss + """ + + itm_calls = chain[chain.index < strike][["OI_call"]] + itm_calls["loss"] = (strike - itm_calls.index) * itm_calls["OI_call"] + call_loss = itm_calls["loss"].sum() + # The *-1 below is due to a sign change for plotting in the _view code + itm_puts = chain[chain.index > strike][["OI_put"]] + itm_puts["loss"] = (itm_puts.index - strike) * itm_puts["OI_put"] * -1 + put_loss = itm_puts.loss.sum() + loss = call_loss + put_loss + return loss + + +def get_max_pain(chain: pd.DataFrame) -> int: + """ + Returns the max pain for a given call/put dataframe + Parameters + ---------- + chain: DataFrame + Dataframe to calculate value from + + Returns + ------- + max_pain : int + Max pain value + """ + + strikes = np.array(chain.index) + if ("OI_call" not in chain.columns) or ("OI_put" not in chain.columns): + print("Incorrect columns. Unable to parse max pain") + return np.nan + + loss = [] + for price_at_exp in strikes: + loss.append(get_loss_at_strike(price_at_exp, chain)) + + chain["loss"] = loss + max_pain = chain["loss"].idxmin() + + return max_pain diff --git a/terminal.py b/terminal.py index f3cf36218b7..b596d619507 100644 --- a/terminal.py +++ b/terminal.py @@ -57,6 +57,9 @@ from gamestonk_terminal.etf import etf_controller class TerminalController: """Terminal Controller class""" + # To hold suffix for Yahoo Finance + suffix = "" + # Command choices CHOICES_TICKER_DEPENDENT = [ "ba", @@ -134,7 +137,6 @@ What do you want to do? q(uit) to abandon the program Contexts: -> scr screener stocks, \t\t e.g. overview/performance, using preset filters > mill papermill menu, \t\t menu to generate notebook reports > econ economic data, \t\t\t e.g.: events, FRED data, GDP, VIXCLS > pa portfolio analysis, \t\t analyses your custom portfolio @@ -180,7 +182,9 @@ Contexts: > bt strategy backtester, \t e.g.: simple ema, ema cross, rsi strategies > pred prediction techniques, \t e.g.: regression, arima, rnn, lstm""" - help_text += "\n> disc discover trending stocks, \t e.g. map, sectors, high short interest\n" + help_text += """\n> disc discover trending stocks, \t e.g. map, sectors, high short interest +> scr screener stocks, \t\t e.g. overview/performance, using preset filters + """ print(help_text) def switch(self, an_input: str): @@ -232,7 +236,9 @@ Contexts: other_args, self.ticker, self.start, self.interval, self.stock ) if "." in self.ticker: - self.ticker = self.ticker.split(".")[0] + self.ticker, self.suffix = self.ticker.split(".") + else: + self.suffix = "" def call_quote(self, other_args: List[str]): """Process quote command""" @@ -241,7 +247,7 @@ Contexts: def call_candle(self, _): """Process candle command""" candle( - self.ticker, + self.ticker + "." + self.suffix if self.suffix else self.ticker, (datetime.now() - timedelta(days=180)).strftime("%Y-%m-%d"), )