From 141dd68e68b6cb76abdd1a9ef5c16bf545d020a8 Mon Sep 17 00:00:00 2001 From: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Date: Wed, 23 Aug 2023 11:40:31 -0700 Subject: [PATCH] Removed prints (#5367) * Removed prints * FIxed typing * FIxed typing * Fixed typing * Fixed typing * Fixed typing * Fixed typing * Fixed typing * Fix * Reverted stuff --- custom_pre_commit/check_doc.py | 4 +- custom_pre_commit/check_reserved_args.py | 2 +- openbb_terminal/account/account_view.py | 4 +- .../behavioural_analysis/finnhub_view.py | 1 - .../technical_analysis/volatility_model.py | 31 ++++++----- openbb_terminal/core/models/sources_model.py | 2 +- openbb_terminal/core/plots/backend.py | 6 +- openbb_terminal/core/plots/plotly_helper.py | 6 +- openbb_terminal/core/scripts/sdk_audit.py | 25 +++++---- .../core/session/sources_handler.py | 6 +- openbb_terminal/core/session/utils.py | 8 ++- .../cryptocurrency/cryptocurrency_helpers.py | 2 +- .../cryptocurrency/defi/coindix_view.py | 3 +- .../cryptocurrency/defi/llama_view.py | 3 +- .../due_diligence/dd_controller.py | 2 +- openbb_terminal/cryptocurrency/pyth_view.py | 2 +- .../econometrics/econometrics_view.py | 4 +- openbb_terminal/economy/finviz_model.py | 1 - openbb_terminal/economy/fred_model.py | 2 +- openbb_terminal/economy/fred_view.py | 2 +- openbb_terminal/forecast/helpers.py | 2 +- openbb_terminal/forecast/whisper_model.py | 8 ++- openbb_terminal/futures/sdk_helper.py | 5 +- openbb_terminal/loggers.py | 5 +- openbb_terminal/menu.py | 3 +- .../portfolio/portfolio_controller.py | 2 +- openbb_terminal/portfolio/portfolio_helper.py | 2 +- .../portfolio_optimization/optimizer_view.py | 12 ++-- .../yahoo_finance_model.py | 3 +- openbb_terminal/reports/widget_helpers.py | 3 +- openbb_terminal/rich_config.py | 8 +-- .../fundamental_analysis/sdk_helpers.py | 7 ++- openbb_terminal/stocks/options/cboe_model.py | 17 +++--- .../stocks/options/intrinio_model.py | 10 ++-- .../stocks/options/intrinio_view.py | 2 +- .../stocks/options/nasdaq_model.py | 8 +-- .../stocks/options/options_chains_model.py | 55 ++++++++++--------- .../stocks/options/options_chains_view.py | 11 ++-- .../stocks/options/options_sdk_helper.py | 2 +- openbb_terminal/stocks/options/tmx_model.py | 15 ++--- .../stocks/options/tradier_model.py | 4 +- .../stocks/options/yfinance_model.py | 2 +- openbb_terminal/terminal_controller.py | 4 +- pyproject.toml | 3 +- tests/conftest.py | 2 +- .../due_diligence/test_pycoingecko_view.py | 2 - .../technical_analysis/test_ta_controller.py | 6 +- .../forecast/test_forecast_controller.py | 1 - 48 files changed, 170 insertions(+), 150 deletions(-) diff --git a/custom_pre_commit/check_doc.py b/custom_pre_commit/check_doc.py index c690785e6ff..0f20540810d 100644 --- a/custom_pre_commit/check_doc.py +++ b/custom_pre_commit/check_doc.py @@ -67,12 +67,12 @@ def main(ignore_files: Optional[str], ignore_commands: Optional[str]): if not undocumented: sys.exit(0) else: - print("The following commands do not have documentation:") + print("The following commands do not have documentation:") # noqa: T201 undocumented = list(undocumented) undocumented.sort() for item in undocumented: - print(item) + print(item) # noqa: T201 sys.exit(1) diff --git a/custom_pre_commit/check_reserved_args.py b/custom_pre_commit/check_reserved_args.py index 9e9354ddb98..84f388d0eec 100644 --- a/custom_pre_commit/check_reserved_args.py +++ b/custom_pre_commit/check_reserved_args.py @@ -35,7 +35,7 @@ def process_file(file_path: str, exp: str): if long_arg is not None: long_arg = long_arg.group() if long_arg not in ("HistoryManager.hist_file", RESERVED_ARGS[short_arg]): - print( + print( # noqa: T201 f"{file_path}: " f"'-{short_arg}' argument expected '{RESERVED_ARGS[short_arg]}'" f" but assigned to '{long_arg}'" diff --git a/openbb_terminal/account/account_view.py b/openbb_terminal/account/account_view.py index 5dcbff376bf..fb40d32fbef 100644 --- a/openbb_terminal/account/account_view.py +++ b/openbb_terminal/account/account_view.py @@ -57,8 +57,7 @@ def display_personal_routines(df: pd.DataFrame, page: int, pages: int): show_index=True, index_name="#", ) - except Exception as exc: - print(exc) + except Exception: console.print("Failed to display personal routines.") @@ -72,7 +71,6 @@ def display_default_routines(df: pd.DataFrame): """ try: df = df.rename(columns={"date_updated": "updated_date"}) - print(df) df = clean_df(df) print_rich_table( df=df, diff --git a/openbb_terminal/common/behavioural_analysis/finnhub_view.py b/openbb_terminal/common/behavioural_analysis/finnhub_view.py index fbf69c2765b..b2a40729157 100644 --- a/openbb_terminal/common/behavioural_analysis/finnhub_view.py +++ b/openbb_terminal/common/behavioural_analysis/finnhub_view.py @@ -32,7 +32,6 @@ def display_sentiment_stats( Format to export data """ d_stats = finnhub_model.get_sentiment_stats(ticker) - print(d_stats) if d_stats.empty: return diff --git a/openbb_terminal/common/technical_analysis/volatility_model.py b/openbb_terminal/common/technical_analysis/volatility_model.py index b786799727a..39e6ea9017c 100644 --- a/openbb_terminal/common/technical_analysis/volatility_model.py +++ b/openbb_terminal/common/technical_analysis/volatility_model.py @@ -10,6 +10,7 @@ import pandas_ta as ta from openbb_terminal.common.technical_analysis import ta_helpers from openbb_terminal.decorators import log_start_end +from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) @@ -216,11 +217,11 @@ def standard_deviation( """ if window < 2: - print("Error: Window must be at least 2, defaulting to 30.") + console.print("Error: Window must be at least 2, defaulting to 30.") window = 30 if trading_periods and is_crypto: - print("is_crypto is overridden by trading_periods.") + console.print("is_crypto is overridden by trading_periods.") if not trading_periods: trading_periods = 365 if is_crypto else 252 @@ -273,11 +274,11 @@ def parkinson( """ if window < 1: - print("Error: Window must be at least 1, defaulting to 30.") + console.print("Error: Window must be at least 1, defaulting to 30.") window = 30 if trading_periods and is_crypto: - print("is_crypto is overridden by trading_periods.") + console.print("is_crypto is overridden by trading_periods.") if not trading_periods: trading_periods = 365 if is_crypto else 252 @@ -334,11 +335,11 @@ def garman_klass( """ if window < 1: - print("Error: Window must be at least 1, defaulting to 30.") + console.print("Error: Window must be at least 1, defaulting to 30.") window = 30 if trading_periods and is_crypto: - print("is_crypto is overridden by trading_periods.") + console.print("is_crypto is overridden by trading_periods.") if not trading_periods: trading_periods = 365 if is_crypto else 252 @@ -395,11 +396,11 @@ def hodges_tompkins( """ if window < 2: - print("Error: Window must be at least 2, defaulting to 30.") + console.print("Error: Window must be at least 2, defaulting to 30.") window = 30 if trading_periods and is_crypto: - print("is_crypto is overridden by trading_periods.") + console.print("is_crypto is overridden by trading_periods.") if not trading_periods: trading_periods = 365 if is_crypto else 252 @@ -460,11 +461,11 @@ def rogers_satchell( """ if window < 1: - print("Error: Window must be at least 1, defaulting to 30.") + console.print("Error: Window must be at least 1, defaulting to 30.") window = 30 if trading_periods and is_crypto: - print("is_crypto is overridden by trading_periods.") + console.print("is_crypto is overridden by trading_periods.") if not trading_periods: trading_periods = 365 if is_crypto else 252 @@ -521,11 +522,11 @@ def yang_zhang( """ if window < 2: - print("Error: Window must be at least 2, defaulting to 30.") + console.print("Error: Window must be at least 2, defaulting to 30.") window = 30 if trading_periods and is_crypto: - print("is_crypto is overridden by trading_periods.") + console.print("is_crypto is overridden by trading_periods.") if not trading_periods: trading_periods = 365 if is_crypto else 252 @@ -624,7 +625,7 @@ def cones( lower_q, upper_q = upper_q, lower_q if (lower_q >= 1) or (upper_q >= 1): - print("Error: lower_q and upper_q must be between 0 and 1") + console.print("Error: lower_q and upper_q must be between 0 and 1") cones_df = pd.DataFrame() return cones_df @@ -644,7 +645,9 @@ def cones( for window in windows: # Looping to build a dataframe with realized volatility over each window. if model not in VOLATILITY_MODELS: - print("Model not available. Available models: ", VOLATILITY_MODELS) + console.print( + "Model not available. Available models: ", VOLATILITY_MODELS + ) elif model == "STD": estimator = standard_deviation( window=window, data=data, is_crypto=is_crypto diff --git a/openbb_terminal/core/models/sources_model.py b/openbb_terminal/core/models/sources_model.py index ad8d885bff7..384aaf4a765 100644 --- a/openbb_terminal/core/models/sources_model.py +++ b/openbb_terminal/core/models/sources_model.py @@ -22,7 +22,7 @@ def read_default_sources() -> Dict: with open(DATA_SOURCES_DEFAULT_FILE) as file: return flatten(json.load(file)) except Exception as e: - print( + print( # noqa: T201 f"\nFailed to read data sources file: " f"{DATA_SOURCES_DEFAULT_FILE}\n{e}\n" ) diff --git a/openbb_terminal/core/plots/backend.py b/openbb_terminal/core/plots/backend.py index 2a8e02c5b4d..235af4d651f 100644 --- a/openbb_terminal/core/plots/backend.py +++ b/openbb_terminal/core/plots/backend.py @@ -23,7 +23,7 @@ from openbb_terminal.core.session.constants import BackendEnvironment try: from pywry import PyWry except ImportError as e: - print(f"\033[91m{e}\033[0m") + print(f"\033[91m{e}\033[0m") # noqa: T201 # pylint: disable=C0412 from openbb_terminal.core.plots.no_import import DummyBackend @@ -54,7 +54,7 @@ else: JUPYTER_NOTEBOOK = True PLOTS_CORE_PATH = Path(__file__).parent.resolve() -PLOTLYJS_PATH = PLOTS_CORE_PATH / "assets" / "plotly-2.24.2.min.js" +PLOTLYJS_PATH: Path = PLOTS_CORE_PATH / "assets" / "plotly-2.24.2.min.js" BACKEND = None @@ -496,7 +496,7 @@ async def download_plotly_js(): file.unlink(missing_ok=True) except Exception as err: # pylint: disable=W0703 - print(f"Error downloading plotly.js: {err}") + console.print(f"Error downloading plotly.js: {err}") def plots_backend() -> Backend: diff --git a/openbb_terminal/core/plots/plotly_helper.py b/openbb_terminal/core/plots/plotly_helper.py index 2546a75f6b3..19ca0c730ac 100644 --- a/openbb_terminal/core/plots/plotly_helper.py +++ b/openbb_terminal/core/plots/plotly_helper.py @@ -29,9 +29,7 @@ from scipy import stats from openbb_terminal import config_terminal from openbb_terminal.base_helpers import console, strtobool -from openbb_terminal.core.config.paths import ( - STYLES_DIRECTORY_REPO, -) +from openbb_terminal.core.config.paths import STYLES_DIRECTORY_REPO from openbb_terminal.core.plots.backend import PLOTLYJS_PATH, plots_backend from openbb_terminal.core.plots.config.openbb_styles import ( PLT_COLORWAY, @@ -59,7 +57,7 @@ class TerminalStyle: """ STYLES_REPO = STYLES_DIRECTORY_REPO - USER_STYLES_DIRECTORY = get_current_user().preferences.USER_STYLES_DIRECTORY + USER_STYLES_DIRECTORY: Path = get_current_user().preferences.USER_STYLES_DIRECTORY plt_styles_available: Dict[str, Path] = {} plt_style: str = "dark" diff --git a/openbb_terminal/core/scripts/sdk_audit.py b/openbb_terminal/core/scripts/sdk_audit.py index ee65cbb6185..b67f427a487 100644 --- a/openbb_terminal/core/scripts/sdk_audit.py +++ b/openbb_terminal/core/scripts/sdk_audit.py @@ -8,6 +8,7 @@ from typing import Callable, List, Tuple import pandas as pd from openbb_terminal.core.config.paths import MAP_PATH +from openbb_terminal.rich_config import console try: import darts # pylint: disable=W0611 # noqa: F401 @@ -84,8 +85,10 @@ def get_sdk(file_path: Path = MAP_PATH) -> pd.DataFrame: df = pd.read_csv(base_path / file_path) df_dups = len(df["trail"]) - len(df["trail"].drop_duplicates()) if df_dups > 0: - print(f"Number of duplicate sdk paths: {df_dups}") - print("This indicates that the same SDK trail is being used multiple times\n") + console.print(f"Number of duplicate sdk paths: {df_dups}") + console.print( + "This indicates that the same SDK trail is being used multiple times\n" + ) views = list(df[["view", "trail"]].itertuples(index=False, name=None)) models = list(df[["model", "trail"]].itertuples(index=False, name=None)) # Add in whether it is a view or a model in pandas @@ -146,8 +149,8 @@ def functions_df() -> pd.DataFrame: func_df["docstring"] = [x[1] for x in all_formatted] func_dups = len(func_df["name"]) - len(func_df["name"].drop_duplicates()) if func_dups > 0: - print(f"Number of duplicate functions found: {func_dups}") - print( + console.print(f"Number of duplicate functions found: {func_dups}") + console.print( "This may indicate that functions are defined several times in the terminal.\n" ) func_df = func_df.set_index("name") @@ -159,7 +162,7 @@ def save_df(data: pd.DataFrame) -> None: time_str = (str(timestamp)).replace(".", "") output_path = f"{time_str}_sdk_audit.csv" data.to_csv(output_path) - print(f"File saved to {output_path}") + console.print(f"File saved to {output_path}") def get_nonconforming_functions(data: pd.DataFrame) -> pd.DataFrame: @@ -192,7 +195,7 @@ def get_nonconforming_functions(data: pd.DataFrame) -> pd.DataFrame: def main(): - print( + console.print( "This tool checks all functions in a file with a name including 'view' or 'model'against\n" "all functions in the sdk, which is gathered from 'trail_map.csv'. If the generated csv\n" "has an entry for 'trail' that means it is in the SDK, and if it has an entry for\n" @@ -209,15 +212,17 @@ def main(): # Get further stats on bad data no_doc_count = len(final_df[final_df["docstring"].isnull()].index) if no_doc_count > 0: - print(f"The number of rows with blank docstrings is: {no_doc_count}") - print( + console.print(f"The number of rows with blank docstrings is: {no_doc_count}") + console.print( "This indicates a matching function does not exist, is not in a 'model' or 'view'\n" "file, or that the trailmap does not import it from the place it is defined.\n" ) dup_name_count = len(final_df[final_df.duplicated(keep=False)].index) if dup_name_count > 0: - print(f"The number of duplicate functions after merge is: {dup_name_count}") - print( + console.print( + f"The number of duplicate functions after merge is: {dup_name_count}" + ) + console.print( "This most likely indicates that the same function is being used at " "different SDK endpoints.\n" ) diff --git a/openbb_terminal/core/session/sources_handler.py b/openbb_terminal/core/session/sources_handler.py index 83901db44c2..ac1dd91b4f1 100644 --- a/openbb_terminal/core/session/sources_handler.py +++ b/openbb_terminal/core/session/sources_handler.py @@ -26,8 +26,8 @@ def read_sources(path: Path) -> Dict: return flatten(json.load(file)) return {} except Exception as e: - print(f"\nFailed to read data sources file: {path}\n{e}\n") - print("Falling back to OpenBB default sources.") + print(f"\nFailed to read data sources file: {path}\n{e}\n") # noqa: T201 + print("Falling back to OpenBB default sources.") # noqa: T201 return {} @@ -45,7 +45,7 @@ def write_sources(sources: Dict, path: Path): with open(path, "w") as f: json.dump(extend(sources), f, indent=4) except Exception as e: - print(f"\nFailed to write data sources file: {path}\n{e}\n") + print(f"\nFailed to write data sources file: {path}\n{e}\n") # noqa: T201 def merge_sources(incoming: Dict, allowed: Dict): diff --git a/openbb_terminal/core/session/utils.py b/openbb_terminal/core/session/utils.py index 45ab3e509ee..5d20941c541 100644 --- a/openbb_terminal/core/session/utils.py +++ b/openbb_terminal/core/session/utils.py @@ -27,7 +27,7 @@ def load_dict_to_model(dictionary: dict, model: Type[T]) -> T: try: return model(**dictionary) # type: ignore except ValidationError as error: - print(f"Error loading {model_name}:") + print(f"Error loading {model_name}:") # noqa: T201 for err in error.errors(): loc = err.get("loc", None) var_name = str(loc[0]) if loc else "" @@ -36,11 +36,13 @@ def load_dict_to_model(dictionary: dict, model: Type[T]) -> T: fields: dict[str, Any] = model.get_fields() if var and var_name in fields: default = fields[var_name].default - print(f" {var_name}: {msg}, using default -> {default}") + print( # noqa: T201 + f" {var_name}: {msg}, using default -> {default}" + ) return model(**dictionary) # type: ignore except Exception: - print(f"Error loading {model_name}, using defaults.") + print(f"Error loading {model_name}, using defaults.") # noqa: T201 return model() # type: ignore diff --git a/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py b/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py index 4c109e11bda..c9607701186 100644 --- a/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py +++ b/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py @@ -973,7 +973,7 @@ def plot_order_book( def check_cg_id(symbol: str): cg_id = get_coingecko_id(symbol) if not cg_id: - print(f"\n{symbol} not found on CoinGecko") + console.print(f"\n{symbol} not found on CoinGecko") return "" return symbol diff --git a/openbb_terminal/cryptocurrency/defi/coindix_view.py b/openbb_terminal/cryptocurrency/defi/coindix_view.py index 9199fa327fa..4bc49162232 100644 --- a/openbb_terminal/cryptocurrency/defi/coindix_view.py +++ b/openbb_terminal/cryptocurrency/defi/coindix_view.py @@ -8,6 +8,7 @@ from typing import Optional from openbb_terminal.cryptocurrency.defi import coindix_model from openbb_terminal.decorators import log_start_end from openbb_terminal.helper_funcs import export_data, print_rich_table +from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) @@ -62,7 +63,7 @@ def display_defi_vaults( chain=chain, protocol=protocol, kind=kind, sortby=sortby, ascend=ascend ) if df.empty: - print( + console.print( f"Couldn't find any vaults for " f"{'' if not chain else 'chain: ' + chain}" f"{'' if not protocol else ', protocol: ' + protocol}" diff --git a/openbb_terminal/cryptocurrency/defi/llama_view.py b/openbb_terminal/cryptocurrency/defi/llama_view.py index d3db45cd6f4..700a2a098e6 100644 --- a/openbb_terminal/cryptocurrency/defi/llama_view.py +++ b/openbb_terminal/cryptocurrency/defi/llama_view.py @@ -16,6 +16,7 @@ from openbb_terminal.helper_funcs import ( lambda_long_number_format, print_rich_table, ) +from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) @@ -166,7 +167,7 @@ def display_historical_tvl( name=available_protocols[dapp], ) else: - print(f"{dapp} not found\n") + console.print(f"{dapp} not found\n") if export and export != "": export_data( export, diff --git a/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py b/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py index 93ca524a1e5..5123f8f354f 100644 --- a/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py +++ b/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py @@ -51,7 +51,7 @@ FILTERS_VS_USD_BTC = ["usd", "btc"] def check_cg_id(symbol: str): cg_id = cryptocurrency_helpers.get_coingecko_id(symbol) if not cg_id: - print(f"\n{symbol} not found on CoinGecko") + console.print(f"\n{symbol} not found on CoinGecko") return "" return symbol diff --git a/openbb_terminal/cryptocurrency/pyth_view.py b/openbb_terminal/cryptocurrency/pyth_view.py index 490bb0cb153..c35914db340 100644 --- a/openbb_terminal/cryptocurrency/pyth_view.py +++ b/openbb_terminal/cryptocurrency/pyth_view.py @@ -28,4 +28,4 @@ def display_price(symbol: str) -> None: end="\r", ) except KeyboardInterrupt: - print(f"\n\nStopped watching {symbol} price and confidence interval\n") + console.print(f"\n\nStopped watching {symbol} price and confidence interval\n") diff --git a/openbb_terminal/econometrics/econometrics_view.py b/openbb_terminal/econometrics/econometrics_view.py index 6a34ffc126c..05a979f8cdd 100644 --- a/openbb_terminal/econometrics/econometrics_view.py +++ b/openbb_terminal/econometrics/econometrics_view.py @@ -122,9 +122,9 @@ def display_plot( ) except ValueError: - print(f"Could not convert column: {dataset_col}") + console.print(f"Could not convert column: {dataset_col}") except TypeError: - print(f"Could not convert column: {dataset_col}") + console.print(f"Could not convert column: {dataset_col}") if fig.is_image_export(export): export_data( diff --git a/openbb_terminal/economy/finviz_model.py b/openbb_terminal/economy/finviz_model.py index 8e28c209429..5f1c5ea04ff 100644 --- a/openbb_terminal/economy/finviz_model.py +++ b/openbb_terminal/economy/finviz_model.py @@ -99,7 +99,6 @@ def get_valuation_data( # Passing Raw data to Pandas DataFrame if using interactive mode if get_current_user().preferences.USE_INTERACTIVE_DF: return df_group - print(df_group.head()) df_group["Market Cap"] = df_group["Market Cap"].apply( lambda x: float(x.strip("B")) if x.endswith("B") diff --git a/openbb_terminal/economy/fred_model.py b/openbb_terminal/economy/fred_model.py index 153ee30e956..230880cce2e 100644 --- a/openbb_terminal/economy/fred_model.py +++ b/openbb_terminal/economy/fred_model.py @@ -428,7 +428,7 @@ def get_usd_liquidity(overlay: str = "", show: bool = False) -> pd.DataFrame: if overlay != "": overlay = overlay.upper() if overlay not in EQUITY_INDICES: - print( + console.print( "Invalid choice for the overlay." "Use `get_usd_liquidity(show = True)` to see display the list of choices." ) diff --git a/openbb_terminal/economy/fred_view.py b/openbb_terminal/economy/fred_view.py index df1dbce3ee9..bb5dba7daf0 100644 --- a/openbb_terminal/economy/fred_view.py +++ b/openbb_terminal/economy/fred_view.py @@ -353,7 +353,7 @@ def display_usd_liquidity( overlay = overlay.upper() if overlay not in fred_model.EQUITY_INDICES: - print( + console.print( "Invalid choice. Display available choices by adding the parameter, `show = True`." ) return None diff --git a/openbb_terminal/forecast/helpers.py b/openbb_terminal/forecast/helpers.py index 0e6dbcb8d6c..da42d8309fd 100644 --- a/openbb_terminal/forecast/helpers.py +++ b/openbb_terminal/forecast/helpers.py @@ -1078,7 +1078,7 @@ def get_prediction( ): _, val = ticker_series.split_before(train_split) - print(f"Predicting {model_name} for {n_predict} days") + console.print(f"Predicting {model_name} for {n_predict} days") if model_name not in ["Regression", "Logistic Regression"]: # need to create a new pytorch trainer for historical backtesting to remove progress bar best_model.trainer = None diff --git a/openbb_terminal/forecast/whisper_model.py b/openbb_terminal/forecast/whisper_model.py index 674b1c56c76..d66074a7de0 100644 --- a/openbb_terminal/forecast/whisper_model.py +++ b/openbb_terminal/forecast/whisper_model.py @@ -56,7 +56,9 @@ def get_audio(urls): for url in urls: result = ydl.extract_info(url, download=True) - print(f"Downloaded video \"{result['title']}\". Generating subtitles...") + console.print( + f"Downloaded video \"{result['title']}\". Generating subtitles..." + ) paths[result["title"]] = os.path.join(temp_dir, f"{result['id']}.mp3") return paths @@ -313,13 +315,13 @@ def transcribe_and_summarize( with open(vtt_path, "w", encoding="utf-8") as vtt: write_vtt(result["segments"], file=vtt, line_length=breaklines) - print("Saved VTT to", os.path.abspath(vtt_path)) + console.print("Saved VTT to", os.path.abspath(vtt_path)) else: srt_path = os.path.join(output_dir, f"{slugify(title)}.srt") with open(srt_path, "w", encoding="utf-8") as srt: write_srt(result["segments"], file=srt, line_length=breaklines) - print("Saved SRT to", os.path.abspath(srt_path)) + console.print("Saved SRT to", os.path.abspath(srt_path)) # Save summary to file summary_path = os.path.join(output_dir, f"{slugify(title)}_summary.txt") diff --git a/openbb_terminal/futures/sdk_helper.py b/openbb_terminal/futures/sdk_helper.py index 94688eac5d8..30ed7e72122 100644 --- a/openbb_terminal/futures/sdk_helper.py +++ b/openbb_terminal/futures/sdk_helper.py @@ -6,6 +6,7 @@ from typing import List, Optional, Union import pandas as pd from openbb_terminal.futures import yfinance_model +from openbb_terminal.rich_config import console from openbb_terminal.stocks import databento_model @@ -47,7 +48,9 @@ def get_historical( ) if source == "DataBento": if isinstance(symbols, list): - print("DataBento only supports one symbol at a time. Using first symbol.") + console.print( + "DataBento only supports one symbol at a time. Using first symbol." + ) symbols = symbols[0] return databento_model.get_historical_futures(symbols, start_date, end_date) return pd.DataFrame() diff --git a/openbb_terminal/loggers.py b/openbb_terminal/loggers.py index c48ebb5c886..bf93afb1f90 100644 --- a/openbb_terminal/loggers.py +++ b/openbb_terminal/loggers.py @@ -46,6 +46,7 @@ from openbb_terminal.core.session.current_system import ( set_system_variable, ) from openbb_terminal.helper_funcs import request +from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) logging_verbosity = get_current_system().LOGGING_VERBOSITY @@ -61,8 +62,8 @@ def get_app_id() -> str: app_id = get_log_dir().stem except OSError as e: if e.errno == 30: - print("Please move the application into a writable location.") - print( + console.print("Please move the application into a writable location.") + console.print( "Note for macOS users: copy `OpenBB Terminal` folder outside the DMG." ) else: diff --git a/openbb_terminal/menu.py b/openbb_terminal/menu.py index af870952b5e..bedc66a4ada 100644 --- a/openbb_terminal/menu.py +++ b/openbb_terminal/menu.py @@ -8,6 +8,7 @@ from prompt_toolkit.eventloop.inputhook import set_eventloop_with_inputhook from prompt_toolkit.history import FileHistory from openbb_terminal.core.config.paths import HIST_FILE_PATH +from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) @@ -59,7 +60,7 @@ try: # pylint: disable=unused-variable except Exception as e: # noqa: F841 logger.exception("%s", type(e).__name__) - print( + console.print( "WARNING: Prompt toolkit is turned on but did not initialize successfully." " Falling back to input()..." ) diff --git a/openbb_terminal/portfolio/portfolio_controller.py b/openbb_terminal/portfolio/portfolio_controller.py index 2677a0e6257..ff1374c55f4 100644 --- a/openbb_terminal/portfolio/portfolio_controller.py +++ b/openbb_terminal/portfolio/portfolio_controller.py @@ -560,7 +560,7 @@ class PortfolioController(BaseController): self.portfolio_name, self.benchmark_name ): if self.benchmark_name != "SPDR S&P 500 ETF Trust (SPY)": - print( + console.print( "This feature uses S&P 500 as benchmark and will disregard selected benchmark if different." ) # sector contribution diff --git a/openbb_terminal/portfolio/portfolio_helper.py b/openbb_terminal/portfolio/portfolio_helper.py index be79a63ab91..925c5c829c4 100644 --- a/openbb_terminal/portfolio/portfolio_helper.py +++ b/openbb_terminal/portfolio/portfolio_helper.py @@ -329,7 +329,7 @@ def get_start_date_from_period(period: str) -> date: elif 12 >= cm >= 10: start_date = date(date.today().year, 10, 1) else: - print("Error") + console.print("Error") elif period == "mtd": cur_month = date.today().month cur_year = date.today().year diff --git a/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py b/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py index 255df4e12d0..c1f64d8300d 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py +++ b/openbb_terminal/portfolio/portfolio_optimization/optimizer_view.py @@ -240,9 +240,9 @@ def portfolio_performance( factor_1 = str(int(time_factor[freq])) + ") " factor_2 = "√" + factor_1 - print("\nAnnual (by " + factor_1 + f"expected return: {100 * mu:.2f}%") - print("Annual (by " + factor_2 + f"volatility: {100 * sigma:.2f}%") - print(f"Sharpe ratio: {sharpe:.4f}") + console.print("\nAnnual (by " + factor_1 + f"expected return: {100 * mu:.2f}%") + console.print("Annual (by " + factor_2 + f"volatility: {100 * sigma:.2f}%") + console.print(f"Sharpe ratio: {sharpe:.4f}") if risk_measure != "MV": risk = rp.Sharpe_Risk( @@ -274,7 +274,7 @@ def portfolio_performance( if risk_measure in drawdowns: sharpe_2 = (mu - risk_free_rate) / risk - print( + console.print( risk_names[risk_measure.lower()].capitalize() + " : " + f"{100 * risk:.2f}%" @@ -282,7 +282,7 @@ def portfolio_performance( else: risk = risk * time_factor[freq] ** 0.5 sharpe_2 = (mu - risk_free_rate) / risk - print( + console.print( "Annual (by " + factor_2 + risk_names[risk_measure.lower()] @@ -290,7 +290,7 @@ def portfolio_performance( + f"{100 * risk:.2f}%" ) - print( + console.print( "Return / " + risk_names[risk_measure.lower()] + f" ratio: {sharpe_2:.4f}" diff --git a/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py b/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py index 42ddc99f896..5ac0e0a25df 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py +++ b/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py @@ -14,6 +14,7 @@ import yfinance as yf from dateutil.relativedelta import FR, relativedelta from openbb_terminal.decorators import log_start_end +from openbb_terminal.rich_config import console logger = logging.getLogger(__name__) @@ -341,7 +342,7 @@ def process_returns( if s not in stock_returns.iloc[:, selected_stocks] ] if filtered_out: - print( + console.print( "The following stocks were filtered out, due to too many NaNs: " + ", ".join(filtered_out) ) diff --git a/openbb_terminal/reports/widget_helpers.py b/openbb_terminal/reports/widget_helpers.py index dea9cd35cf4..a93c15cbcaa 100644 --- a/openbb_terminal/reports/widget_helpers.py +++ b/openbb_terminal/reports/widget_helpers.py @@ -12,6 +12,7 @@ from jinja2 import Template from openbb_terminal.core.config.paths import PACKAGE_DIRECTORY from openbb_terminal.core.plots.backend import PLOTLYJS_PATH +from openbb_terminal.rich_config import console def price_card_stylesheet(): @@ -166,7 +167,7 @@ def kpi(thresholds: List[float], sentences: List[str], value: float) -> str: if value > thresholds[1]: return f'

✅ {sentences[2]}. {value} > {thresholds[1]}

' return f'

🟡 {sentences[1]}. {thresholds[0]} < {value} < {thresholds[1]}

' - print("Error. KPI condition is not correctly set") + console.print("Error. KPI condition is not correctly set") return "" diff --git a/openbb_terminal/rich_config.py b/openbb_terminal/rich_config.py index 444151abb14..4cf896d2090 100644 --- a/openbb_terminal/rich_config.py +++ b/openbb_terminal/rich_config.py @@ -11,9 +11,7 @@ from rich.text import Text from openbb_terminal.core.plots.plotly_helper import theme from openbb_terminal.core.session.current_system import get_current_system -from openbb_terminal.core.session.current_user import ( - get_current_user, -) +from openbb_terminal.core.session.current_user import get_current_user # pylint: disable=no-member,c-extension-no-member @@ -263,11 +261,11 @@ class ConsoleAndPanel: else: self.__console.print(kwargs["text"]) else: - print(self.filter_rich_tags(kwargs["text"])) + print(self.filter_rich_tags(kwargs["text"])) # noqa: T201 elif not get_current_system().TEST_MODE: self.__console.print(*args, **kwargs) else: - print(*args, **kwargs) + print(*args, **kwargs) # noqa: T201 def input(self, *args, **kwargs): self.print(*args, **kwargs, end="") diff --git a/openbb_terminal/stocks/fundamental_analysis/sdk_helpers.py b/openbb_terminal/stocks/fundamental_analysis/sdk_helpers.py index 09277b8cf66..bdab3f3888f 100644 --- a/openbb_terminal/stocks/fundamental_analysis/sdk_helpers.py +++ b/openbb_terminal/stocks/fundamental_analysis/sdk_helpers.py @@ -3,6 +3,7 @@ __docformat__ = "numpy" import pandas as pd +from openbb_terminal.rich_config import console from openbb_terminal.stocks.fundamental_analysis import ( av_model, eodhd_model, @@ -83,7 +84,7 @@ def get_income_statement( """ if source == "YahooFinance": if quarterly: - print( + console.print( "Quarterly income statement not available from Yahoo Finance. Returning annual" ) df = yahoo_finance_model.get_financials( @@ -147,7 +148,7 @@ def get_balance_sheet( """ if source == "YahooFinance": if quarterly: - print( + console.print( "Quarterly statements not available from Yahoo Finance. Returning annual" ) df = yahoo_finance_model.get_financials( @@ -211,7 +212,7 @@ def get_cash_flow( """ if source == "YahooFinance": if quarterly: - print( + console.print( "Quarterly statements not available from Yahoo Finance. Returning annual" ) df = yahoo_finance_model.get_financials( diff --git a/openbb_terminal/stocks/options/cboe_model.py b/openbb_terminal/stocks/options/cboe_model.py index f3cbd73c7b2..6ea887109a6 100644 --- a/openbb_terminal/stocks/options/cboe_model.py +++ b/openbb_terminal/stocks/options/cboe_model.py @@ -9,6 +9,7 @@ import pandas as pd from requests.exceptions import HTTPError from openbb_terminal.helper_funcs import request +from openbb_terminal.rich_config import console from openbb_terminal.stocks.options.op_helpers import Options, PydanticOptions __docformat__ = "numpy" @@ -163,7 +164,7 @@ def get_ticker_info(symbol: str) -> Tuple[pd.DataFrame, list[str]]: if symbol_info_json.success is False: ticker_details = pd.DataFrame() ticker_expirations = [] - print("No data found for the symbol: " f"{symbol}" "") + console.print("No data found for the symbol: " f"{symbol}" "") else: symbol_details = pd.Series(symbol_info_json["details"]) symbol_details = pd.DataFrame(symbol_details).transpose() @@ -265,7 +266,7 @@ def get_ticker_info(symbol: str) -> Tuple[pd.DataFrame, list[str]]: ).rename(columns={f"{new_ticker}": f"{symbol}"}) except HTTPError: - print("There was an error with the request'\n") + console.print("There was an error with the request'\n") ticker_details = pd.DataFrame() ticker_expirations = list() return ticker_details, ticker_expirations @@ -313,7 +314,7 @@ def get_ticker_iv(symbol: str) -> pd.DataFrame: h_iv = request(quotes_iv_url) if h_iv.status_code != 200: - print("No data found for the symbol: " f"{symbol}" "") + console.print("No data found for the symbol: " f"{symbol}" "") return pd.DataFrame() data = h_iv.json() @@ -353,7 +354,7 @@ def get_ticker_iv(symbol: str) -> pd.DataFrame: ticker_iv = pd.DataFrame(h_data).transpose() except HTTPError: - print("There was an error with the request'\n") + console.print("There was an error with the request'\n") return pd.DataFrame(ticker_iv, columns=iv_order).transpose() @@ -402,7 +403,7 @@ def get_quotes(symbol: str) -> pd.DataFrame: r = request(quotes_url) if r.status_code != 200: - print("No data found for the symbol: " f"{symbol}" "") + console.print("No data found for the symbol: " f"{symbol}" "") return pd.DataFrame() r_json = r.json() @@ -470,7 +471,7 @@ def get_quotes(symbol: str) -> pd.DataFrame: quotes["changePercent"] = round(quotes["changePercent"], 2) except HTTPError: - print("There was an error with the request'\n") + console.print("There was an error with the request'\n") return pd.DataFrame() return quotes.reset_index() @@ -530,7 +531,9 @@ def load_options(symbol: str, pydantic: bool = False) -> Options: OptionsChains.symbol = symbol if OptionsChains.symbol not in OptionsChains.SYMBOLS.index: - print("The symbol, " f"{symbol}" ", was not found in the CBOE directory.") + console.print( + "The symbol, " f"{symbol}" ", was not found in the CBOE directory." + ) return OptionsChains info, _ = get_ticker_info(OptionsChains.symbol) if not info.empty: diff --git a/openbb_terminal/stocks/options/intrinio_model.py b/openbb_terminal/stocks/options/intrinio_model.py index 9c81906c81c..9d352e993c8 100644 --- a/openbb_terminal/stocks/options/intrinio_model.py +++ b/openbb_terminal/stocks/options/intrinio_model.py @@ -425,7 +425,7 @@ def get_ticker_info(symbol: str) -> pd.Series: try: info = intrinio.SecurityApi().get_security_by_id(symbol).to_dict() except Exception: - print("Security not found") + console.print("Security not found") return {} info = pd.Series(info).rename( @@ -536,7 +536,7 @@ def get_eod_chains(symbol: str, date: str) -> Options: symbol = symbol.upper() OptionsChains.SYMBOLS = get_all_ticker_symbols() if symbol not in OptionsChains.SYMBOLS: - print(f"{symbol}", "is not supported by Intrinio.") + console.print(f"{symbol}", "is not supported by Intrinio.") return OptionsChains OptionsChains.symbol = symbol if symbol not in TICKER_EXCEPTIONS: @@ -567,7 +567,7 @@ def get_eod_chains(symbol: str, date: str) -> Options: OptionsChains.last_price = underlying["adjClose"] # If the ticker is an index, it will not return underlying data. else: - print("Warning: Index options do not currently return underlying data.") + console.print("Warning: Index options do not currently return underlying data.") OptionsChains.underlying_name = OptionsChains.symbol OptionsChains.underlying_price = pd.Series(dtype=object) OptionsChains.last_price = 0 @@ -663,7 +663,7 @@ def load_options(symbol: str, date: str = "", pydantic=False) -> Options: OptionsChains.SYMBOLS = get_all_ticker_symbols() if symbol not in OptionsChains.SYMBOLS: - print(f"{symbol}", "is not supported by Intrinio.") + console.print(f"{symbol}", "is not supported by Intrinio.") return OptionsChains OptionsChains.symbol = symbol @@ -700,7 +700,7 @@ def load_options(symbol: str, date: str = "", pydantic=False) -> Options: # If the ticker is an index, it will not return underlying data. else: - print("Warning: Index options do not currently return underlying data.") + console.print("Warning: Index options do not currently return underlying data.") OptionsChains.underlying_name = OptionsChains.symbol OptionsChains.underlying_price = pd.Series(dtype=object) OptionsChains.last_price = 0 diff --git a/openbb_terminal/stocks/options/intrinio_view.py b/openbb_terminal/stocks/options/intrinio_view.py index d7becd0ae05..b3171c37c27 100644 --- a/openbb_terminal/stocks/options/intrinio_view.py +++ b/openbb_terminal/stocks/options/intrinio_view.py @@ -164,7 +164,7 @@ def view_historical_greeks( f"{strike} {['Call','Put'][put]} and {expiry} Expiration" ) if df.empty: - print(f"No data found for {chain_id}") + console.print(f"No data found for {chain_id}") return None df = df.rename(columns={"impliedVolatility": "iv", "close": "price"}) diff --git a/openbb_terminal/stocks/options/nasdaq_model.py b/openbb_terminal/stocks/options/nasdaq_model.py index d452f5086b8..399c3d38eeb 100644 --- a/openbb_terminal/stocks/options/nasdaq_model.py +++ b/openbb_terminal/stocks/options/nasdaq_model.py @@ -335,7 +335,7 @@ def get_available_greeks(OptionsChains, expiration: str = "") -> pd.DataFrame: expiration = OptionsChains.expirations[0] if expiration not in OptionsChains.expirations: - print( + console.print( f"{expiration}", " is not a valid expiration. Choose from, ", OptionsChains.expirations, @@ -406,7 +406,7 @@ def load_options(symbol: str, pydantic: bool = False) -> Options: OptionsChains.symbol not in OptionsChains.SYMBOLS.index and OptionsChains.symbol != "NDX" ): - print(OptionsChains.symbol, "was not found in the Nasdaq directory") + console.print(OptionsChains.symbol, "was not found in the Nasdaq directory") return OptionsChains OptionsChains.symbol = symbol @@ -461,7 +461,7 @@ def load_options(symbol: str, pydantic: bool = False) -> Options: if expiration == "": expiration = OptionsChains.expirations[0] if expiration not in OptionsChains.expirations: - print( + console.print( f"{expiration}", " is not a valid expiration. Choose from, ", OptionsChains.expirations, @@ -474,7 +474,7 @@ def load_options(symbol: str, pydantic: bool = False) -> Options: if not OptionsChains.chains.empty: if OptionsChains.last_price is None: OptionsChains.last_price = 0 - print("No last price for " + OptionsChains.symbol) + console.print("No last price for " + OptionsChains.symbol) if not pydantic: setattr(OptionsChains, "get_available_greeks", get_greeks) diff --git a/openbb_terminal/stocks/options/options_chains_model.py b/openbb_terminal/stocks/options/options_chains_model.py index b7b89f97e99..d6506f3de03 100644 --- a/openbb_terminal/stocks/options/options_chains_model.py +++ b/openbb_terminal/stocks/options/options_chains_model.py @@ -14,6 +14,7 @@ import pandas as pd # IMPORTATION INTERNAL from openbb_terminal.decorators import log_start_end +from openbb_terminal.rich_config import console from openbb_terminal.stocks.options.cboe_model import load_options as load_cboe from openbb_terminal.stocks.options.intrinio_model import load_options as load_intrinio from openbb_terminal.stocks.options.nasdaq_model import load_options as load_nasdaq @@ -111,7 +112,7 @@ def load_options_chains( """ if source not in SOURCES: - print("Invalid choice. Choose from: ", list(SOURCES), sep=None) + console.print("Invalid choice. Choose from: ", list(SOURCES), sep=None) return Options() if source == "Nasdaq": @@ -181,7 +182,7 @@ def validate_object( # noqa: PLR0911 scope = scope or "chains" if scope not in scopes: - print("Invalid choice. The supported methods are:", scopes) + console.print("Invalid choice. The supported methods are:", scopes) return pd.DataFrame() if scope == "object": @@ -194,7 +195,7 @@ def validate_object( # noqa: PLR0911 return True except AttributeError: - print( + console.print( "Error: Invalid data type supplied. The Options data object is required. " "Use load_options_chains() first." ) @@ -205,7 +206,7 @@ def validate_object( # noqa: PLR0911 if isinstance(options.last_price, float): return True except AttributeError: - print( + console.print( "`last_price` was not found in the OptionsChainsData object and is required for this operation." ) return False @@ -226,20 +227,20 @@ def validate_object( # noqa: PLR0911 ) if options is None or chains.empty: - print( + console.print( "No options chains data found in the supplied object. Use load_options_chains()." ) return pd.DataFrame() if "openInterest" not in chains.columns: - print("Expected column, openInterest, not found.") + console.print("Expected column, openInterest, not found.") return pd.DataFrame() if "volume" not in chains.columns: - print("Expected column, volume, not found.") + console.print("Expected column, volume, not found.") return pd.DataFrame() except AttributeError: - print("Error: Invalid data type supplied.") + console.print("Error: Invalid data type supplied.") return pd.DataFrame() return chains @@ -288,7 +289,7 @@ def validate_object( # noqa: PLR0911 return options - print( + console.print( "Error: No valid data supplied. Check the input to ensure it is not empty or None." ) @@ -379,7 +380,7 @@ def get_nearest_call_strike( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -448,7 +449,7 @@ def get_nearest_put_strike( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -511,7 +512,7 @@ def get_nearest_otm_strike( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -524,7 +525,9 @@ def get_nearest_otm_strike( moneyness = moneyness / 100 if moneyness > 100 or moneyness < 0: - print("Error: Moneyness must be expressed as a percentage between 0 and 100") + console.print( + "Error: Moneyness must be expressed as a percentage between 0 and 100" + ) return {} upper = options.last_price * (1 + moneyness) @@ -586,7 +589,7 @@ def calculate_straddle( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -721,7 +724,7 @@ def calculate_strangle( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -732,7 +735,7 @@ def calculate_strangle( options = validate_object(options, "nonZeroPrices", dte_estimate) if moneyness > 100 or moneyness < 0: - print("Error: Moneyness must be between 0 and 100.") + console.print("Error: Moneyness must be between 0 and 100.") return pd.DataFrame() strikes = get_nearest_otm_strike(options, moneyness) @@ -855,7 +858,7 @@ def calculate_vertical_call_spread( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -1000,7 +1003,7 @@ def calculate_vertical_put_spread( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -1133,7 +1136,7 @@ def calculate_synthetic_long( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -1232,7 +1235,7 @@ def calculate_synthetic_short( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the OptionsChain data object.") + console.print("`last_price` was not found in the OptionsChain data object.") return pd.DataFrame() if isinstance(options.chains, dict): @@ -1321,7 +1324,9 @@ def calculate_stats(options: Options, by: Optional[str] = "expiration") -> pd.Da """ if by not in ["expiration", "strike"]: - print("Invalid choice. The supported methods are: [expiration, strike]") + console.print( + "Invalid choice. The supported methods are: [expiration, strike]" + ) return pd.DataFrame() chains = deepcopy(options) @@ -1473,7 +1478,7 @@ def get_strategies( return pd.DataFrame() if validate_object(options, scope="strategies") is False: - print("`last_price` was not found in the Options data object.") + console.print("`last_price` was not found in the Options data object.") return pd.DataFrame() options.chains = ( @@ -1489,12 +1494,12 @@ def get_strategies( days = [days] if isinstance(days, int) else days # type: ignore[list-item] if not isinstance(vertical_calls, (list, float)) and vertical_calls is not None: - print( + console.print( "Two strike prices are required. Enter the sold price first, then the bought price." ) return pd.DataFrame() if not isinstance(vertical_puts, (list, float)) and vertical_puts is not None: - print( + console.print( "Two strike prices are required. Enter the sold price first, then the bought price." ) return pd.DataFrame() @@ -1653,7 +1658,7 @@ def calculate_skew( return pd.DataFrame() if options.hasIV is False: - print( + console.print( "Options data object does not have Implied Volatility and is required for this function." ) return pd.DataFrame() diff --git a/openbb_terminal/stocks/options/options_chains_view.py b/openbb_terminal/stocks/options/options_chains_view.py index 08d03616ef0..9d1795d3c2d 100644 --- a/openbb_terminal/stocks/options/options_chains_view.py +++ b/openbb_terminal/stocks/options/options_chains_view.py @@ -16,6 +16,7 @@ from scipy.spatial import Delaunay from openbb_terminal import OpenBBFigure from openbb_terminal.decorators import log_start_end from openbb_terminal.helper_funcs import export_data, print_rich_table +from openbb_terminal.rich_config import console from openbb_terminal.stocks.options import options_chains_model from openbb_terminal.stocks.options.op_helpers import Options @@ -87,7 +88,7 @@ def display_surface( return None if options.hasIV is False: - return print( + return console.print( "Options data object does not have Implied Volatility and is required for this function." ) @@ -104,7 +105,7 @@ def display_surface( ) if option_type not in ["otm", "itm", "puts", "calls"]: - print("Invalid option type, defaulting to 'otm'.") + console.print("Invalid option type, defaulting to 'otm'.") option_type = "otm" if oi: @@ -546,7 +547,7 @@ def display_skew( """ if options.hasIV is False: - return print( + return console.print( "Options data object does not have Implied Volatility and is required for this function." ) options = deepcopy(options) @@ -591,7 +592,7 @@ def display_skew( ["Expiration", "Strike", "Option Type", "IV", "ATM IV", "Skew"] ] if skew["IV"].sum() == 0 and len(expirations) == 1: - return print("No IV data available for this expiration.") + return console.print("No IV data available for this expiration.") index_name = "Strike" if len(expirations) > 1 else expiration call_skew = skew.query("`Option Type` == 'call'").set_index("Strike") @@ -810,7 +811,7 @@ def display_volatility( """ if options.hasIV is False: - return print( + return console.print( "Options data object does not have Implied Volatility and is required for this function." ) options = deepcopy(options) diff --git a/openbb_terminal/stocks/options/options_sdk_helper.py b/openbb_terminal/stocks/options/options_sdk_helper.py index 6ec7639cbe1..b91b5ec03c9 100644 --- a/openbb_terminal/stocks/options/options_sdk_helper.py +++ b/openbb_terminal/stocks/options/options_sdk_helper.py @@ -450,7 +450,7 @@ class OptionsChains(Options): # pylint: disable=too-few-public-methods if query is not None: if isinstance(query, pd.DataFrame): return options_chains_model.calculate_stats(query, by) - print("Query must be passed a Pandas DataFrame with chains data.") + console.print("Query must be passed a Pandas DataFrame with chains data.") return options_chains_model.calculate_stats(self, by) diff --git a/openbb_terminal/stocks/options/tmx_model.py b/openbb_terminal/stocks/options/tmx_model.py index e70be27c2fd..d28a2a12778 100644 --- a/openbb_terminal/stocks/options/tmx_model.py +++ b/openbb_terminal/stocks/options/tmx_model.py @@ -9,6 +9,7 @@ import pandas_market_calendars as mcal from pandas.tseries.holiday import next_workday from openbb_terminal.helper_funcs import request +from openbb_terminal.rich_config import console from openbb_terminal.stocks.options.op_helpers import Options, PydanticOptions __docformat__ = "numpy" @@ -86,7 +87,7 @@ def get_underlying_price(symbol: str) -> pd.Series: response = request(URL) if response.status_code != 200: - print("No price data found for the underlying security, " f"{symbol}") + console.print("No price data found for the underlying security, " f"{symbol}") return data data = response.json()["ticker"] @@ -188,7 +189,7 @@ def get_chains(symbol: str = "") -> Options: OptionsChains.source = "TMX" if symbol == "": - print("Please enter a symbol.") + console.print("Please enter a symbol.") return OptionsChains symbol = symbol.upper() @@ -200,7 +201,7 @@ def get_chains(symbol: str = "") -> Options: symbol = list(SYMBOLS.query("`Underlying Symbol` == @symbol").index.values)[0] if symbol not in OptionsChains.SYMBOLS.index and not OptionsChains.SYMBOLS.empty: - print( + console.print( "The symbol, " f"{symbol}" ", is not a valid TMX listing.", sep=None, ) @@ -344,14 +345,14 @@ def get_eodchains(symbol: str = "", date: str = "") -> Options: BASE_URL = "https://www.m-x.ca/en/trading/data/historical?symbol=" if symbol == "": - print("Please enter a symbol.") + console.print("Please enter a symbol.") return OptionsChains if ".TO" in symbol: symbol = symbol.replace(".TO", "") if symbol not in OptionsChains.SYMBOLS.index: - print( + console.print( "The symbol, " f"{symbol}" ", was not found in the TMX listings.", sep=None, ) @@ -363,7 +364,7 @@ def get_eodchains(symbol: str = "", date: str = "") -> Options: EOD_URL = BASE_URL + f"{OptionsChains.symbol}" "&dnld=1#quotes" if date != "": if pd.to_datetime(date) < pd.to_datetime("2009-01-01"): - print("Historical options data begins on 2009-01-02.") + console.print("Historical options data begins on 2009-01-02.") date = check_weekday(date) if date in holidays: date = (pd.to_datetime(date) + timedelta(days=1)).strftime("%Y-%m-%d") @@ -381,7 +382,7 @@ def get_eodchains(symbol: str = "", date: str = "") -> Options: ) data = pd.read_csv(EOD_URL) if data.empty: - print( + console.print( "No data found. Check the date to ensure the ticker was listed before that date." ) return OptionsChains diff --git a/openbb_terminal/stocks/options/tradier_model.py b/openbb_terminal/stocks/options/tradier_model.py index 8b3b1274cdb..90f96998584 100644 --- a/openbb_terminal/stocks/options/tradier_model.py +++ b/openbb_terminal/stocks/options/tradier_model.py @@ -466,7 +466,7 @@ def get_chains(symbol: str) -> Options: OptionsChains.symbol = symbol.upper() if OptionsChains.symbol not in list(OptionsChains.SYMBOLS["symbol"]): - print(f"{OptionsChains.symbol} is not support by Tradier.") + console.print(f"{OptionsChains.symbol} is not support by Tradier.") return OptionsChains OptionsChains.underlying_price = get_underlying_price(OptionsChains.symbol) @@ -544,7 +544,7 @@ def load_options(symbol: str, pydantic: bool = False) -> Options: if options.last_price is None: options.last_price = 0 - print("No last price for " + options.symbol) + console.print("No last price for " + options.symbol) if not pydantic: return options diff --git a/openbb_terminal/stocks/options/yfinance_model.py b/openbb_terminal/stocks/options/yfinance_model.py index 95c7a52ecd3..bc52bea0da1 100644 --- a/openbb_terminal/stocks/options/yfinance_model.py +++ b/openbb_terminal/stocks/options/yfinance_model.py @@ -419,7 +419,7 @@ def load_options(symbol: str, pydantic: bool = False) -> Options: if not chains.empty and OptionsChains.last_price is None: OptionsChains.last_price = 0 - print("No last price for " + OptionsChains.symbol) + console.print("No last price for " + OptionsChains.symbol) if not pydantic: return OptionsChains diff --git a/openbb_terminal/terminal_controller.py b/openbb_terminal/terminal_controller.py index e273d6a76f2..81b4a5a19a8 100644 --- a/openbb_terminal/terminal_controller.py +++ b/openbb_terminal/terminal_controller.py @@ -1043,7 +1043,7 @@ def run_scripts( terminal(file_cmds, test_mode=True) else: with suppress_stdout(): - print(f"To ensure: {output}") + console.print(f"To ensure: {output}") if output: timestamp = datetime.now().timestamp() stamp_str = str(timestamp).replace(".", "") @@ -1094,7 +1094,7 @@ def run_routine(file: str, routines_args=Optional[str]): elif default_routine_path.exists(): run_scripts(path=default_routine_path, routines_args=routines_args) else: - print( + console.print( f"Routine not found, please put your `.openbb` file into : {user_routine_path}." ) diff --git a/pyproject.toml b/pyproject.toml index 30e8abaa499..dc830e60ed3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -178,13 +178,14 @@ target-version = "py38" # This is an introductory addition of ruff. We should look to adding: # D: pydocstyle, PD: pandas-vet # All options here: https://github.com/charliermarsh/ruff#supported-rules -select = ["E", "W", "F", "Q", "S", "UP", "I", "PLC", "PLE", "PLR", "PLW", "SIM"] +select = ["E", "W", "F", "Q", "S", "UP", "I", "PLC", "PLE", "PLR", "PLW", "SIM", "T20"] # These ignores should be seen as temporary solutions to problems that will NEED fixed ignore = ["PLR2004", "PLR0913", "PLR0915"] [tool.ruff.per-file-ignores] "tests/*" = ["S101"] "*init*.py" = ["F401"] +"website/*" = ["T201"] [tool.ruff.flake8-import-conventions.aliases] "matplotlib.pyplot" = "plt" diff --git a/tests/conftest.py b/tests/conftest.py index e33852d6f5d..7502fbad40e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -355,7 +355,7 @@ def brotli_check(): def disable_rich(): def effect(df, *xargs, **kwargs): # pylint: disable=unused-argument - print(df.to_string()) + print(df.to_string()) # noqa: T201 helper_funcs.print_rich_table = effect diff --git a/tests/openbb_terminal/cryptocurrency/due_diligence/test_pycoingecko_view.py b/tests/openbb_terminal/cryptocurrency/due_diligence/test_pycoingecko_view.py index 0bd9602c69c..bed442834a0 100644 --- a/tests/openbb_terminal/cryptocurrency/due_diligence/test_pycoingecko_view.py +++ b/tests/openbb_terminal/cryptocurrency/due_diligence/test_pycoingecko_view.py @@ -1,5 +1,4 @@ import json -import os from unittest import TestCase, mock import pytest @@ -27,7 +26,6 @@ def test_display_potential_returns(): ) def get_bitcoin(mock_load): # pylint: disable=unused-argument - print(os.getcwd()) with open( "tests/openbb_terminal/cryptocurrency/due_diligence/json/test_pycoingecko_view/btc_usd_test_data.json", encoding="utf8", diff --git a/tests/openbb_terminal/etf/technical_analysis/test_ta_controller.py b/tests/openbb_terminal/etf/technical_analysis/test_ta_controller.py index 6307ada7974..6a4f0f64ff6 100644 --- a/tests/openbb_terminal/etf/technical_analysis/test_ta_controller.py +++ b/tests/openbb_terminal/etf/technical_analysis/test_ta_controller.py @@ -14,16 +14,14 @@ from openbb_terminal.core.session.current_user import ( ) from openbb_terminal.etf.technical_analysis import ta_controller -# pylint: disable=E1101 -# pylint: disable=W0603 -# pylint: disable=E1111 +# pylint: disable=E1101,W0603,E1111 EMPTY_DF = pd.DataFrame() MOCK_STOCK_DF = pd.read_csv( "tests/openbb_terminal/etf/technical_analysis/csv/test_ta_controller/stock_df.csv", index_col=0, ) -print(MOCK_STOCK_DF.columns) +print(MOCK_STOCK_DF.columns) # noqa: T201 @pytest.mark.vcr(record_mode="none") diff --git a/tests/openbb_terminal/forecast/test_forecast_controller.py b/tests/openbb_terminal/forecast/test_forecast_controller.py index b5282f8b3a0..7247e59aed7 100644 --- a/tests/openbb_terminal/forecast/test_forecast_controller.py +++ b/tests/openbb_terminal/forecast/test_forecast_controller.py @@ -62,7 +62,6 @@ def test_fc_update_runtime_choices(mocker): cont = fc.ForecastController() cont.datasets = {"stonks": df} cont.update_runtime_choices() - print(type(cont.completer)) assert isinstance(cont.completer, NestedCompleter)