From cebf454cdf4b4eefd3d0c01aa0417610383aac3a Mon Sep 17 00:00:00 2001 From: Colin Delahunty <72827203+colin99d@users.noreply.github.com> Date: Mon, 20 Feb 2023 19:27:34 -0500 Subject: [PATCH] Added flake8-simplify (#4227) * Added flake8-simplify * Update linting.yml * update. left 1 for you colin * Fix that one * Missed * Fix * mypy --------- Co-authored-by: james --- custom_pre_commit/check_doc.py | 10 +- generate_sdk.py | 7 +- openbb_terminal/account/account_controller.py | 25 +- .../alternative/oss/github_model.py | 4 +- .../alternative/oss/oss_controller.py | 26 +- .../behavioural_analysis/reddit_model.py | 111 +-- openbb_terminal/common/common_model.py | 5 +- openbb_terminal/common/newsapi_model.py | 10 +- .../common/quantitative_analysis/qa_model.py | 19 +- .../common/quantitative_analysis/qa_view.py | 15 +- .../custom_indicators_view.py | 5 +- .../integration_controller.py | 24 +- openbb_terminal/core/library/breadcrumb.py | 5 +- openbb_terminal/core/scripts/sdk_audit.py | 5 +- .../cryptocurrency/crypto_controller.py | 4 +- .../cryptocurrency/cryptocurrency_helpers.py | 5 +- .../cryptocurrency/defi/defi_controller.py | 6 +- .../cryptocurrency/defi/llama_view.py | 2 +- .../defi/terraengineer_model.py | 2 +- .../discovery/discovery_controller.py | 7 +- .../due_diligence/dd_controller.py | 212 +++--- .../due_diligence/pycoingecko_model.py | 4 +- .../due_diligence/tokenterminal_view.py | 5 +- .../cryptocurrency/onchain/ethplorer_view.py | 9 +- .../onchain/onchain_controller.py | 14 +- .../cryptocurrency/onchain/shroom_model.py | 9 +- .../overview/coinpaprika_model.py | 5 +- .../overview/overview_controller.py | 4 +- .../cryptocurrency/tools/tools_controller.py | 4 +- openbb_terminal/custom_prompt_toolkit.py | 31 +- .../econometrics/econometrics_controller.py | 71 +- openbb_terminal/economy/economy_controller.py | 42 +- .../quantitative_analysis/qa_controller.py | 5 +- openbb_terminal/economy/yfinance_model.py | 12 +- openbb_terminal/economy/yfinance_view.py | 5 +- openbb_terminal/forecast/helpers.py | 34 +- openbb_terminal/forecast/linregr_model.py | 5 +- openbb_terminal/forecast/regr_model.py | 5 +- openbb_terminal/forex/forex_controller.py | 10 +- openbb_terminal/forex/forex_helper.py | 7 +- .../forex/oanda/oanda_controller.py | 10 +- openbb_terminal/forex/oanda/oanda_model.py | 19 +- openbb_terminal/futures/yfinance_model.py | 2 +- openbb_terminal/helper_funcs.py | 46 +- openbb_terminal/keys_controller.py | 9 +- openbb_terminal/mutual_funds/avanza_view.py | 9 +- openbb_terminal/mutual_funds/mstarpy_view.py | 24 +- .../mutual_funds/mutual_fund_controller.py | 9 +- openbb_terminal/parent_classes.py | 24 +- .../portfolio/portfolio_controller.py | 691 +++++++++--------- .../parameters/Parameter.py | 13 +- .../parameters/params_controller.py | 13 +- .../parameters/params_view.py | 7 +- .../portfolio_optimization/po_controller.py | 55 +- .../portfolio_optimization/po_engine.py | 2 +- .../yahoo_finance_model.py | 18 +- openbb_terminal/reports/reports_model.py | 5 +- openbb_terminal/rich_config.py | 19 +- openbb_terminal/session/local_model.py | 16 +- openbb_terminal/session/user.py | 5 +- openbb_terminal/settings_controller.py | 97 ++- .../comparison_analysis/ca_controller.py | 9 +- .../stocks/dark_pool_shorts/finra_model.py | 5 +- .../stocks/dark_pool_shorts/quandl_model.py | 9 +- .../dark_pool_shorts/stockgrid_model.py | 5 +- .../stocks/discovery/finnhub_model.py | 18 +- .../stocks/fundamental_analysis/dcf_model.py | 2 +- .../market_watch_model.py | 5 +- .../fundamental_analysis/marketwatch_model.py | 28 +- .../stocks/insider/businessinsider_view.py | 37 +- .../stocks/insider/openinsider_view.py | 14 +- .../stocks/options/hedge/hedge_controller.py | 6 +- .../stocks/options/hedge/hedge_model.py | 7 +- openbb_terminal/stocks/options/op_helpers.py | 22 +- .../stocks/options/options_controller.py | 9 +- .../stocks/options/screen/syncretism_model.py | 10 +- .../stocks/options/yfinance_model.py | 9 +- .../stocks/options/yfinance_view.py | 18 +- .../quantitative_analysis/beta_model.py | 12 +- .../stocks/screener/screener_controller.py | 63 +- .../stockanalysis_view.py | 5 +- openbb_terminal/stocks/stocks_controller.py | 5 +- openbb_terminal/stocks/stocks_helper.py | 21 +- .../technical_analysis/tradingview_model.py | 7 +- .../tradinghours/tradinghours_controller.py | 12 +- openbb_terminal/terminal_controller.py | 197 +++-- openbb_terminal/terminal_helper.py | 11 +- pyproject.toml | 4 +- tests/helpers/tools.py | 2 +- .../session/test_local_model.py | 4 +- tests/test_helpers.py | 5 +- website/controller_doc_classes.py | 4 +- website/generate_sdk_markdown.py | 5 +- 93 files changed, 1164 insertions(+), 1289 deletions(-) diff --git a/custom_pre_commit/check_doc.py b/custom_pre_commit/check_doc.py index 6a63e381ffd..c690785e6ff 100644 --- a/custom_pre_commit/check_doc.py +++ b/custom_pre_commit/check_doc.py @@ -32,14 +32,8 @@ def main(ignore_files: Optional[str], ignore_commands: Optional[str]): Commands that should not be checked """ - if ignore_files: - ignore_file_list = ignore_files.split(",") - else: - ignore_file_list = [] - if ignore_commands: - ignore_cmds_list = ignore_commands.split(",") - else: - ignore_cmds_list = [] + ignore_file_list = ignore_files.split(",") if ignore_files else [] + ignore_cmds_list = ignore_commands.split(",") if ignore_commands else [] path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) gst_path = os.path.join(path, "openbb_terminal/") main_yaml_filename = os.path.join(path, "website/data/menu/main.yml") diff --git a/generate_sdk.py b/generate_sdk.py index 124fa983b16..116c4baa76d 100644 --- a/generate_sdk.py +++ b/generate_sdk.py @@ -122,10 +122,7 @@ class BuildCategoryModelClasses: def check_submodules(self, category: str) -> bool: """Checks if a category has submodules.""" - for d in self.categories[category].values(): - if isinstance(d, dict): - return True - return False + return any(isinstance(d, dict) for d in self.categories[category].values()) def write_init_imports(self, importstr: str, filestr: str) -> None: """Checks if a category has submodules and adds the imports to the init file.""" @@ -172,7 +169,7 @@ class BuildCategoryModelClasses: subcat : Optional[str], optional The subcategory name, by default None """ - def_name = category if not subcat else subcat + def_name = subcat if subcat else category if subcat: subcat = f" {self.get_subcat_fullname(subcat)}" diff --git a/openbb_terminal/account/account_controller.py b/openbb_terminal/account/account_controller.py index 88b3208f97b..881315ff366 100644 --- a/openbb_terminal/account/account_controller.py +++ b/openbb_terminal/account/account_controller.py @@ -154,16 +154,12 @@ class AccountController(BaseController): FeatureFlagsController.set_feature_flag( "OPENBB_SYNC_ENABLED", True, force=True ) - elif ns_parser.off: - if obbff.SYNC_ENABLED: - FeatureFlagsController.set_feature_flag( - "OPENBB_SYNC_ENABLED", False, force=True - ) + elif ns_parser.off and obbff.SYNC_ENABLED: + FeatureFlagsController.set_feature_flag( + "OPENBB_SYNC_ENABLED", False, force=True + ) - if obbff.SYNC_ENABLED: - sync = "ON" - else: - sync = "OFF" + sync = "ON" if obbff.SYNC_ENABLED else "OFF" if ns_parser.on or ns_parser.off: console.print(f"[info]sync:[/info] {sync}") @@ -431,10 +427,13 @@ class AccountController(BaseController): auth_header=User.get_auth_header(), name=name, ) - if response and response.status_code == 200: - if name in self.REMOTE_CHOICES: - self.REMOTE_CHOICES.remove(name) - self.update_runtime_choices() + if ( + response + and response.status_code == 200 + and name in self.REMOTE_CHOICES + ): + self.REMOTE_CHOICES.remove(name) + self.update_runtime_choices() else: console.print("[info]Aborted.[/info]") diff --git a/openbb_terminal/alternative/oss/github_model.py b/openbb_terminal/alternative/oss/github_model.py index a4f1e19a9a3..6393c7b274b 100644 --- a/openbb_terminal/alternative/oss/github_model.py +++ b/openbb_terminal/alternative/oss/github_model.py @@ -120,9 +120,7 @@ def get_stars_history(repo: str) -> pd.DataFrame: stars[sorted_keys[i]] += stars[sorted_keys[i - 1]] df = pd.DataFrame( { - "Date": [ - datetime.strptime(date, "%Y-%m-%d").date() for date in stars.keys() - ], + "Date": [datetime.strptime(date, "%Y-%m-%d").date() for date in stars], "Stars": stars.values(), } ) diff --git a/openbb_terminal/alternative/oss/oss_controller.py b/openbb_terminal/alternative/oss/oss_controller.py index edc4ac15298..194b6f1946e 100644 --- a/openbb_terminal/alternative/oss/oss_controller.py +++ b/openbb_terminal/alternative/oss/oss_controller.py @@ -88,11 +88,10 @@ class OSSController(BaseController): export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES, raw=True, ) - if ns_parser: - if valid_repo(ns_parser.repo): - github_view.display_star_history( - repo=ns_parser.repo, export=ns_parser.export - ) + if ns_parser and valid_repo(ns_parser.repo): + github_view.display_star_history( + repo=ns_parser.repo, export=ns_parser.export + ) @log_start_end(log=logger) def call_rs(self, other_args: List[str]): @@ -116,15 +115,14 @@ class OSSController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED, raw=True ) - if ns_parser: - if valid_repo(ns_parser.repo): - github_view.display_repo_summary( - repo=ns_parser.repo, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and valid_repo(ns_parser.repo): + github_view.display_repo_summary( + repo=ns_parser.repo, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_rossidx(self, other_args: List[str]): diff --git a/openbb_terminal/common/behavioural_analysis/reddit_model.py b/openbb_terminal/common/behavioural_analysis/reddit_model.py index f01f3b54885..452b0b7bef3 100644 --- a/openbb_terminal/common/behavioural_analysis/reddit_model.py +++ b/openbb_terminal/common/behavioural_analysis/reddit_model.py @@ -170,10 +170,11 @@ def get_popular_tickers( pd.DataFrame DataFrame of top tickers from supplied subreddits """ - if subreddits: - sub_reddit_list = subreddits.split(",") if "," in subreddits else [subreddits] - else: - sub_reddit_list = l_sub_reddits + sub_reddit_list = ( + (subreddits.split(",") if "," in subreddits else [subreddits]) + if subreddits + else l_sub_reddits + ) d_watchlist_tickers: dict = {} l_watchlist_author = [] @@ -223,31 +224,31 @@ def get_popular_tickers( # Get more information about post using PRAW api submission = praw_api.submission(id=submission.id) - if submission is not None: - # Ensure that the post hasn't been removed by moderator in the meanwhile, - # that there is a description and it's not just an image, that the flair is - # meaningful, and that we aren't re-considering same author's content - if ( - not submission.removed_by_category - and (submission.selftext or submission.title) - and submission.author.name not in l_watchlist_author - ): - l_tickers_found = find_tickers(submission) + # Ensure that the post hasn't been removed by moderator in the meanwhile, + # that there is a description and it's not just an image, that the flair is + # meaningful, and that we aren't re-considering same author's content + if ( + submission is not None + and not submission.removed_by_category + and (submission.selftext or submission.title) + and submission.author.name not in l_watchlist_author + ): + l_tickers_found = find_tickers(submission) - if l_tickers_found: - n_tickers += len(l_tickers_found) + if l_tickers_found: + n_tickers += len(l_tickers_found) - # Add another author's name to the parsed watchlists - l_watchlist_author.append(submission.author.name) + # Add another author's name to the parsed watchlists + l_watchlist_author.append(submission.author.name) - # Lookup stock tickers within a watchlist - for key in l_tickers_found: - if key in d_watchlist_tickers: - # Increment stock ticker found - d_watchlist_tickers[key] += 1 - else: - # Initialize stock ticker found - d_watchlist_tickers[key] = 1 + # Lookup stock tickers within a watchlist + for key in l_tickers_found: + if key in d_watchlist_tickers: + # Increment stock ticker found + d_watchlist_tickers[key] += 1 + else: + # Initialize stock ticker found + d_watchlist_tickers[key] = 1 except ResponseException as e: logger.exception("Invalid response: %s", str(e)) @@ -812,37 +813,37 @@ def get_due_dilligence( submission = praw_api.submission(id=submission.id) # Ensure that the post hasn't been removed in the meanwhile - if not submission.removed_by_category: - # Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag - if ( - submission.link_flair_text in l_flair_text, - submission.link_flair_text not in ["Yolo", "Meme"], - )[show_all_flairs]: - s_datetime = datetime.utcfromtimestamp( - submission.created_utc - ).strftime("%Y-%m-%d %H:%M:%S") - s_link = f"https://old.reddit.com{submission.permalink}" - s_all_awards = "".join( - f"{award['count']} {award['name']}\n" - for award in submission.all_awardings - ) + # Either just filter out Yolo, and Meme flairs, or focus on DD, based on b_DD flag + if ( + not submission.removed_by_category + and submission.link_flair_text in l_flair_text, + submission.link_flair_text not in ["Yolo", "Meme"], + )[show_all_flairs]: + s_datetime = datetime.utcfromtimestamp(submission.created_utc).strftime( + "%Y-%m-%d %H:%M:%S" + ) + s_link = f"https://old.reddit.com{submission.permalink}" + s_all_awards = "".join( + f"{award['count']} {award['name']}\n" + for award in submission.all_awardings + ) - s_all_awards = s_all_awards[:-2] + s_all_awards = s_all_awards[:-2] - data = [ - s_datetime, - submission.subreddit, - submission.link_flair_text, - submission.title, - submission.score, - submission.num_comments, - f"{round(100 * submission.upvote_ratio)}%", - s_all_awards, - s_link, - ] - subs.loc[len(subs)] = data - # Increment count of valid posts found - n_flair_posts_found += 1 + data = [ + s_datetime, + submission.subreddit, + submission.link_flair_text, + submission.title, + submission.score, + submission.num_comments, + f"{round(100 * submission.upvote_ratio)}%", + s_all_awards, + s_link, + ] + subs.loc[len(subs)] = data + # Increment count of valid posts found + n_flair_posts_found += 1 # Check if number of wanted posts found has been reached if n_flair_posts_found > limit - 1: diff --git a/openbb_terminal/common/common_model.py b/openbb_terminal/common/common_model.py index 47fb214f1f0..1130469b4de 100644 --- a/openbb_terminal/common/common_model.py +++ b/openbb_terminal/common/common_model.py @@ -80,10 +80,7 @@ def load( return wage_panel.load() return getattr(sm.datasets, file).load_pandas().data - if file in data_files: - full_file = data_files[file] - else: - full_file = file + full_file = data_files[file] if file in data_files else file if not Path(full_file).exists(): console.print(f"[red]Cannot find the file {full_file}[/red]\n") diff --git a/openbb_terminal/common/newsapi_model.py b/openbb_terminal/common/newsapi_model.py index 826ffb9d766..69faa8fdeff 100644 --- a/openbb_terminal/common/newsapi_model.py +++ b/openbb_terminal/common/newsapi_model.py @@ -71,11 +71,11 @@ def get_news( f" {query} were found since {start_date}\n", ) - if show_newest: - articles = response_json["articles"] - - else: - articles = response_json["articles"][::-1] + articles = ( + response_json["articles"] + if show_newest + else response_json["articles"][::-1] + ) elif response.status_code == 426: console.print(f"Error in request: {response.json()['message']}", "\n") diff --git a/openbb_terminal/common/quantitative_analysis/qa_model.py b/openbb_terminal/common/quantitative_analysis/qa_model.py index cf3824359d3..881cfb00825 100644 --- a/openbb_terminal/common/quantitative_analysis/qa_model.py +++ b/openbb_terminal/common/quantitative_analysis/qa_model.py @@ -269,10 +269,7 @@ def get_var( percentile_custom = stats.norm.ppf(1 - percentile) # Mean - if use_mean: - mean = data_return.mean() - else: - mean = 0 + mean = data_return.mean() if use_mean else 0 # Standard Deviation std = data_return.std(axis=0) @@ -396,10 +393,7 @@ def get_es( percentile_custom = stats.norm.ppf(1 - percentile) # Mean - if use_mean: - mean = data_return.mean() - else: - mean = 0 + mean = data_return.mean() if use_mean else 0 # Standard Deviation std = data_return.std(axis=0) @@ -418,10 +412,11 @@ def get_es( es_95 = -b * (1 - np.log(2 * 0.05)) + mean es_99 = -b * (1 - np.log(2 * 0.01)) + mean - if (1 - percentile) < 0.5: - es_custom = -b * (1 - np.log(2 * (1 - percentile))) + mean - else: - es_custom = 0 + es_custom = ( + -b * (1 - np.log(2 * (1 - percentile))) + mean + if 1 - percentile < 0.5 + else 0 + ) elif distribution == "student_t": # Calculating ES based on the Student-t distribution diff --git a/openbb_terminal/common/quantitative_analysis/qa_view.py b/openbb_terminal/common/quantitative_analysis/qa_view.py index 59f911335dd..01a116040b1 100644 --- a/openbb_terminal/common/quantitative_analysis/qa_view.py +++ b/openbb_terminal/common/quantitative_analysis/qa_view.py @@ -316,10 +316,7 @@ def display_bw( theme.style_primary_axis(ax) color = theme.get_colors()[0] - if yearly: - x_data = data.index.year - else: - x_data = data.index.month + x_data = data.index.year if yearly else data.index.month box_plot = sns.boxplot( x=x_data, y=data, @@ -913,10 +910,7 @@ def display_raw( Export data as CSV, JSON, XLSX """ - if isinstance(data, pd.Series): - df1 = pd.DataFrame(data) - else: - df1 = data.copy() + df1 = pd.DataFrame(data) if isinstance(data, pd.Series) else data.copy() if sortby: try: @@ -1213,10 +1207,7 @@ def display_sortino( adjust the sortino ratio """ sortino_ratio = qa_model.get_sortino(data, target_return, window, adjusted) - if adjusted: - str_adjusted = "Adjusted " - else: - str_adjusted = "" + str_adjusted = "Adjusted " if adjusted else "" fig, ax = plt.subplots() ax.plot(sortino_ratio[int(window - 1) :]) diff --git a/openbb_terminal/common/technical_analysis/custom_indicators_view.py b/openbb_terminal/common/technical_analysis/custom_indicators_view.py index 3d5880cdb2a..0ab11aa98ef 100644 --- a/openbb_terminal/common/technical_analysis/custom_indicators_view.py +++ b/openbb_terminal/common/technical_analysis/custom_indicators_view.py @@ -94,10 +94,7 @@ def fibonacci_retracement( return ax1.plot(plot_data[close_col]) - if is_intraday(data): - date_format = "%b %d %H:%M" - else: - date_format = "%Y-%m-%d" + date_format = "%b %d %H:%M" if is_intraday(data) else "%Y-%m-%d" min_date_index = plot_data[ plot_data["date"] == min_date.strftime(date_format) ].index diff --git a/openbb_terminal/core/integration_tests/integration_controller.py b/openbb_terminal/core/integration_tests/integration_controller.py index 7fdfc3fd40b..cf473ae1f6c 100644 --- a/openbb_terminal/core/integration_tests/integration_controller.py +++ b/openbb_terminal/core/integration_tests/integration_controller.py @@ -259,10 +259,11 @@ def run_scripts( simulate_argv = f"/{'/'.join([line.rstrip() for line in lines])}" file_cmds = simulate_argv.replace("//", "/home/").split() file_cmds = insert_start_slash(file_cmds) if file_cmds else file_cmds - if export_folder: - file_cmds = [f"export {export_folder}{' '.join(file_cmds)}"] - else: - file_cmds = [" ".join(file_cmds)] + file_cmds = ( + [f"export {export_folder}{' '.join(file_cmds)}"] + if export_folder + else [" ".join(file_cmds)] + ) obbff.REMEMBER_CONTEXTS = 0 if verbose: @@ -661,13 +662,14 @@ def parse_args_and_run(): special_args_dict = {x: getattr(ns_parser, x) for x in special_arguments_values} - if ns_parser.verbose: - if ns_parser.subprocesses is None or ns_parser.subprocesses > 0: - console.print( - "WARNING: verbose mode and multiprocessing are not compatible. " - "The output of the scripts is mixed up. Consider running with --subproc 0.\n", - style="yellow", - ) + if ns_parser.verbose and ( + ns_parser.subprocesses is None or ns_parser.subprocesses > 0 + ): + console.print( + "WARNING: verbose mode and multiprocessing are not compatible. " + "The output of the scripts is mixed up. Consider running with --subproc 0.\n", + style="yellow", + ) if ns_parser.list_: return display_available_scripts(ns_parser.path, ns_parser.skip) diff --git a/openbb_terminal/core/library/breadcrumb.py b/openbb_terminal/core/library/breadcrumb.py index 42008ea1df1..c12a6560b4a 100644 --- a/openbb_terminal/core/library/breadcrumb.py +++ b/openbb_terminal/core/library/breadcrumb.py @@ -113,10 +113,7 @@ class Breadcrumb: trail = self._trail trail_map = self._trail_map - if trail == "": - trail_next = name - else: - trail_next = f"{trail}.{name}" + trail_next = name if trail == "" else f"{trail}.{name}" if trail_map.get_model_function( trail=trail_next diff --git a/openbb_terminal/core/scripts/sdk_audit.py b/openbb_terminal/core/scripts/sdk_audit.py index 24e50756422..7e38f4d2c83 100644 --- a/openbb_terminal/core/scripts/sdk_audit.py +++ b/openbb_terminal/core/scripts/sdk_audit.py @@ -59,9 +59,8 @@ def all_view_models() -> List[Path]: all_files = os.walk(base_path) for root, _, files in all_files: for filename in files: - if filename.endswith(".py"): - if "view" in filename or "model" in filename: - file_list.append(f"{root}/{filename}") + if filename.endswith(".py") and ("view" in filename or "model" in filename): + file_list.append(f"{root}/{filename}") clean_list = set(file_list) return [Path(x) for x in clean_list] diff --git a/openbb_terminal/cryptocurrency/crypto_controller.py b/openbb_terminal/cryptocurrency/crypto_controller.py index 8f571f8fd13..6ead9155aee 100644 --- a/openbb_terminal/cryptocurrency/crypto_controller.py +++ b/openbb_terminal/cryptocurrency/crypto_controller.py @@ -256,7 +256,7 @@ class CryptoController(CryptoBaseController): upper_symbol = ns_parser.symbol.upper() if "-USD" not in ns_parser.symbol: upper_symbol += "-USD" - if upper_symbol in pyth_model.ASSETS.keys(): + if upper_symbol in pyth_model.ASSETS: console.print( "[param]If it takes too long, you can use 'Ctrl + C' to cancel.\n[/param]" ) @@ -503,7 +503,7 @@ class CryptoController(CryptoBaseController): choices=range(1, 300), metavar="SKIP", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( diff --git a/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py b/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py index 2b24178f037..abfb6b01e11 100644 --- a/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py +++ b/openbb_terminal/cryptocurrency/cryptocurrency_helpers.py @@ -704,10 +704,7 @@ def display_all_coins( if show_all: coins_func = coins_func_map.get(source) - if coins_func: - df = coins_func() - else: - df = prepare_all_coins_df() + df = coins_func() if coins_func else prepare_all_coins_df() elif not source or source not in sources: df = prepare_all_coins_df() diff --git a/openbb_terminal/cryptocurrency/defi/defi_controller.py b/openbb_terminal/cryptocurrency/defi/defi_controller.py index 26d9022b59b..71b16e6263e 100644 --- a/openbb_terminal/cryptocurrency/defi/defi_controller.py +++ b/openbb_terminal/cryptocurrency/defi/defi_controller.py @@ -120,7 +120,7 @@ class DefiController(BaseController): default=False, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "--address") ns_parser = self.parse_known_args_and_warn( @@ -165,7 +165,7 @@ class DefiController(BaseController): default=10, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-a") ns_parser = self.parse_known_args_and_warn( @@ -401,7 +401,7 @@ class DefiController(BaseController): required="-h" not in other_args, help="dApps to search historical TVL. Should be split by , e.g.: anchor,sushiswap,pancakeswap", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-d") ns_parser = self.parse_known_args_and_warn( diff --git a/openbb_terminal/cryptocurrency/defi/llama_view.py b/openbb_terminal/cryptocurrency/defi/llama_view.py index a9b180b4cf9..96bedc22898 100644 --- a/openbb_terminal/cryptocurrency/defi/llama_view.py +++ b/openbb_terminal/cryptocurrency/defi/llama_view.py @@ -165,7 +165,7 @@ def display_historical_tvl( if isinstance(available_protocols, dict): for dapp in dapps.split(","): - if dapp in available_protocols.keys(): + if dapp in available_protocols: df = llama_model.get_defi_protocol(dapp) if not df.empty: ax.plot(df, label=available_protocols[dapp]) diff --git a/openbb_terminal/cryptocurrency/defi/terraengineer_model.py b/openbb_terminal/cryptocurrency/defi/terraengineer_model.py index 80daeef23f1..06e6e871bbd 100644 --- a/openbb_terminal/cryptocurrency/defi/terraengineer_model.py +++ b/openbb_terminal/cryptocurrency/defi/terraengineer_model.py @@ -36,7 +36,7 @@ def get_history_asset_from_terra_address( """ if asset.lower() not in ASSETS: - raise Exception(f"Choose a valid asset from {', '.join(ASSETS)}") + raise Exception(f"Select a valid asset from {', '.join(ASSETS)}") # noqa: S608 if not address.startswith("terra"): raise Exception( diff --git a/openbb_terminal/cryptocurrency/discovery/discovery_controller.py b/openbb_terminal/cryptocurrency/discovery/discovery_controller.py index 93f66931c22..2dfdaae7d43 100644 --- a/openbb_terminal/cryptocurrency/discovery/discovery_controller.py +++ b/openbb_terminal/cryptocurrency/discovery/discovery_controller.py @@ -143,7 +143,7 @@ class DiscoveryController(BaseController): "Only works when raw data is displayed." ), ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( @@ -558,9 +558,8 @@ class DiscoveryController(BaseController): "Only works when raw data is displayed." ), ) - if other_args: - if not other_args[0][0] == "-": - other_args.insert(0, "-q") + if other_args and other_args[0][0] != "-": + other_args.insert(0, "-q") ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED diff --git a/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py b/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py index 6922cdb4c7f..c41e423b831 100644 --- a/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py +++ b/openbb_terminal/cryptocurrency/due_diligence/dd_controller.py @@ -408,9 +408,8 @@ class DueDiligenceController(CryptoBaseController): default=(datetime.now() - timedelta(days=367)).strftime("%Y-%m-%d"), ) - if other_args: - if not other_args[0][0] == "-": - other_args.insert(0, "-e") + if other_args and other_args[0][0] != "-": + other_args.insert(0, "-e") ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES @@ -483,7 +482,7 @@ class DueDiligenceController(CryptoBaseController): default=(datetime.now() - timedelta(days=367)).strftime("%Y-%m-%d"), ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-e") ns_parser = self.parse_known_args_and_warn( @@ -615,15 +614,14 @@ class DueDiligenceController(CryptoBaseController): parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - pycoingecko_view.display_info( - symbol=self.symbol, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + pycoingecko_view.display_info( + symbol=self.symbol, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_market(self, other_args): @@ -665,15 +663,14 @@ class DueDiligenceController(CryptoBaseController): parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - pycoingecko_view.display_web( - self.symbol, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + pycoingecko_view.display_web( + self.symbol, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_social(self, other_args): @@ -881,7 +878,7 @@ class DueDiligenceController(CryptoBaseController): metavar="VS", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-e") ns_parser = self.parse_known_args_and_warn( @@ -929,7 +926,7 @@ class DueDiligenceController(CryptoBaseController): metavar="VS", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-e") ns_parser = self.parse_known_args_and_warn( @@ -953,10 +950,7 @@ class DueDiligenceController(CryptoBaseController): """Process balance command""" coin = self.symbol.upper() values = binance_model.show_available_pairs_for_given_symbol(coin) - if values: - quotes = values[1] - else: - quotes = None + quotes = values[1] if values else None parser = argparse.ArgumentParser( prog="balance", @@ -1009,13 +1003,12 @@ class DueDiligenceController(CryptoBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - coinpaprika_view.display_price_supply( - self.symbol, - ns_parser.vs, - ns_parser.export, - ) + if ns_parser and self.symbol: + coinpaprika_view.display_price_supply( + self.symbol, + ns_parser.vs, + ns_parser.export, + ) @log_start_end(log=logger) def call_basic(self, other_args): @@ -1031,12 +1024,11 @@ class DueDiligenceController(CryptoBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - coinpaprika_view.display_basic( - self.symbol, - ns_parser.export, - ) + if ns_parser and self.symbol: + coinpaprika_view.display_basic( + self.symbol, + ns_parser.export, + ) @log_start_end(log=logger) def call_mkt(self, other_args): @@ -1102,20 +1094,19 @@ class DueDiligenceController(CryptoBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - coinpaprika_view.display_markets( - from_symbol=self.symbol, - to_symbol=ns_parser.vs, - limit=ns_parser.limit, - sortby=ns_parser.sortby, - ascend=ns_parser.reverse, - links=ns_parser.urls, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + coinpaprika_view.display_markets( + from_symbol=self.symbol, + to_symbol=ns_parser.vs, + limit=ns_parser.limit, + sortby=ns_parser.sortby, + ascend=ns_parser.reverse, + links=ns_parser.urls, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_ex(self, other_args): @@ -1163,18 +1154,17 @@ class DueDiligenceController(CryptoBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - coinpaprika_view.display_exchanges( - symbol=self.symbol, - limit=ns_parser.limit, - sortby=ns_parser.sortby, - ascend=ns_parser.reverse, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + coinpaprika_view.display_exchanges( + symbol=self.symbol, + limit=ns_parser.limit, + sortby=ns_parser.sortby, + ascend=ns_parser.reverse, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_events(self, other_args): @@ -1232,19 +1222,18 @@ class DueDiligenceController(CryptoBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - coinpaprika_view.display_events( - symbol=self.symbol, - limit=ns_parser.limit, - sortby=ns_parser.sortby, - ascend=ns_parser.reverse, - links=ns_parser.urls, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + coinpaprika_view.display_events( + symbol=self.symbol, + limit=ns_parser.limit, + sortby=ns_parser.sortby, + ascend=ns_parser.reverse, + links=ns_parser.urls, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_twitter(self, other_args): @@ -1293,18 +1282,17 @@ class DueDiligenceController(CryptoBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - coinpaprika_view.display_twitter( - symbol=self.symbol, - limit=ns_parser.limit, - sortby=ns_parser.sortby, - ascend=ns_parser.reverse, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + coinpaprika_view.display_twitter( + symbol=self.symbol, + limit=ns_parser.limit, + sortby=ns_parser.sortby, + ascend=ns_parser.reverse, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_mcapdom(self, other_args: List[str]): @@ -1513,15 +1501,14 @@ class DueDiligenceController(CryptoBaseController): parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if self.symbol: - messari_view.display_tokenomics( - symbol=self.symbol.upper(), - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and self.symbol: + messari_view.display_tokenomics( + symbol=self.symbol.upper(), + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_pi(self, other_args: List[str]): @@ -1735,7 +1722,7 @@ class DueDiligenceController(CryptoBaseController): default="", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-t") ns_parser = self.parse_known_args_and_warn( @@ -1895,7 +1882,7 @@ class DueDiligenceController(CryptoBaseController): help="Choose project of interest", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-p") ns_parser = self.parse_known_args_and_warn( @@ -1929,18 +1916,17 @@ class DueDiligenceController(CryptoBaseController): help="Choose project of interest", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-p") ns_parser = self.parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if ns_parser.project in tokenterminal_model.get_project_ids(): - tokenterminal_view.display_description( - project=ns_parser.project, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and ns_parser.project in tokenterminal_model.get_project_ids(): + tokenterminal_view.display_description( + project=ns_parser.project, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) diff --git a/openbb_terminal/cryptocurrency/due_diligence/pycoingecko_model.py b/openbb_terminal/cryptocurrency/due_diligence/pycoingecko_model.py index e749353ab08..4c4ce25cf5a 100644 --- a/openbb_terminal/cryptocurrency/due_diligence/pycoingecko_model.py +++ b/openbb_terminal/cryptocurrency/due_diligence/pycoingecko_model.py @@ -449,9 +449,7 @@ class Coin: social_dct = {} links = self._get_links() - for ( - channel - ) in CHANNELS.keys(): # pylint: disable=consider-iterating-dictionary) + for channel in CHANNELS: # pylint: disable=consider-iterating-dictionary) if channel in links: value = links.get(channel, "") if channel == "twitter_screen_name": diff --git a/openbb_terminal/cryptocurrency/due_diligence/tokenterminal_view.py b/openbb_terminal/cryptocurrency/due_diligence/tokenterminal_view.py index f07a43def29..6b8d715803c 100644 --- a/openbb_terminal/cryptocurrency/due_diligence/tokenterminal_view.py +++ b/openbb_terminal/cryptocurrency/due_diligence/tokenterminal_view.py @@ -80,10 +80,7 @@ def display_fundamental_metric_from_project_over_time( else metric_over_time.values / 1e6, ) ax.set_xlabel("Time") - if max(metric_over_time.values) < 10000: - labeltouse = "[USD]" - else: - labeltouse = "[1M USD]" + labeltouse = "[USD]" if max(metric_over_time.values) < 10000 else "[1M USD]" ax.set_ylabel(f"{metric.replace('_', ' ').capitalize()} {labeltouse}") ax.set_xlim([metric_over_time.index[0], metric_over_time.index[-1]]) diff --git a/openbb_terminal/cryptocurrency/onchain/ethplorer_view.py b/openbb_terminal/cryptocurrency/onchain/ethplorer_view.py index 3dd19bd3e07..b0ee0d56cde 100644 --- a/openbb_terminal/cryptocurrency/onchain/ethplorer_view.py +++ b/openbb_terminal/cryptocurrency/onchain/ethplorer_view.py @@ -237,10 +237,11 @@ def display_token_info( ) socials = ["website", "telegram", "reddit", "twitter", "coingecko"] - if social: - df = df[df["Metric"].isin(["balance", "name", "symbol"] + socials)] - else: - df = df[~df["Metric"].isin(socials)] + df = ( + df[df["Metric"].isin(["balance", "name", "symbol"] + socials)] + if social + else df[~df["Metric"].isin(socials)] + ) print_rich_table( df, headers=list(df.columns), show_index=False, title="ERC20 Token Information" diff --git a/openbb_terminal/cryptocurrency/onchain/onchain_controller.py b/openbb_terminal/cryptocurrency/onchain/onchain_controller.py index bccd85ec86d..9963764726b 100644 --- a/openbb_terminal/cryptocurrency/onchain/onchain_controller.py +++ b/openbb_terminal/cryptocurrency/onchain/onchain_controller.py @@ -189,7 +189,7 @@ class OnchainController(BaseController): default=12, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-u") ns_parser = self.parse_known_args_and_warn( @@ -231,7 +231,7 @@ class OnchainController(BaseController): choices=shroom_model.DAPP_STATS_PLATFORM_CHOICES, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-p") ns_parser = self.parse_known_args_and_warn( @@ -413,7 +413,7 @@ class OnchainController(BaseController): default=(datetime.now()).strftime("%Y-%m-%d"), ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( @@ -577,7 +577,7 @@ class OnchainController(BaseController): required="-h" not in other_args, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "--address") ns_parser = self.parse_known_args_and_warn( @@ -1183,7 +1183,7 @@ class OnchainController(BaseController): "Only works when raw data is displayed." ), ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( @@ -1261,7 +1261,7 @@ class OnchainController(BaseController): "Only works when raw data is displayed." ), ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( @@ -1527,7 +1527,7 @@ class OnchainController(BaseController): "Only works when raw data is displayed." ), ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( diff --git a/openbb_terminal/cryptocurrency/onchain/shroom_model.py b/openbb_terminal/cryptocurrency/onchain/shroom_model.py index de8f503072e..1e89d9d1d51 100644 --- a/openbb_terminal/cryptocurrency/onchain/shroom_model.py +++ b/openbb_terminal/cryptocurrency/onchain/shroom_model.py @@ -200,10 +200,11 @@ def get_total_value_locked( if not (user_address or address_name): console.print("[red]No user address or address name provided.[/red]") return pd.DataFrame() - if user_address: - extra_sql = f"user_address = '{user_address}' and" - else: - extra_sql = f"address_name = '{address_name}' and" + extra_sql = ( + f"user_address = '{user_address}' and" + if user_address + else f"address_name = '{address_name}' and" + ) sql = f""" SELECT diff --git a/openbb_terminal/cryptocurrency/overview/coinpaprika_model.py b/openbb_terminal/cryptocurrency/overview/coinpaprika_model.py index c24f49397fe..929bccbcabf 100644 --- a/openbb_terminal/cryptocurrency/overview/coinpaprika_model.py +++ b/openbb_terminal/cryptocurrency/overview/coinpaprika_model.py @@ -91,10 +91,7 @@ def get_global_info() -> pd.DataFrame: for key, date in global_markets.items(): if "date" in key: try: - if isinstance(date, datetime): - new_date = date - else: - new_date = parser.parse(date) + new_date = date if isinstance(date, datetime) else parser.parse(date) global_markets[key] = new_date.strftime("%Y-%m-%d %H:%M:%S") except (KeyError, ValueError, TypeError) as e: logger.exception(str(e)) diff --git a/openbb_terminal/cryptocurrency/overview/overview_controller.py b/openbb_terminal/cryptocurrency/overview/overview_controller.py index d574c4a0953..ee8da9c36ab 100644 --- a/openbb_terminal/cryptocurrency/overview/overview_controller.py +++ b/openbb_terminal/cryptocurrency/overview/overview_controller.py @@ -160,7 +160,7 @@ class OverviewController(BaseController): choices=get_categories_keys(), metavar="CATEGORY", ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-c") ns_parser = self.parse_known_args_and_warn( @@ -226,7 +226,7 @@ class OverviewController(BaseController): help="Display N items", default=10, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-m") ns_parser = self.parse_known_args_and_warn( diff --git a/openbb_terminal/cryptocurrency/tools/tools_controller.py b/openbb_terminal/cryptocurrency/tools/tools_controller.py index 36ea881688a..bd0ac8af6b2 100644 --- a/openbb_terminal/cryptocurrency/tools/tools_controller.py +++ b/openbb_terminal/cryptocurrency/tools/tools_controller.py @@ -107,7 +107,7 @@ class ToolsController(BaseController): help="Flag to show narrative instead of dataframe", default=False, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "-a") ns_parser = self.parse_known_args_and_warn( @@ -168,7 +168,7 @@ class ToolsController(BaseController): default=False, ) - if other_args and not other_args[0][0] == "-": + if other_args and other_args[0][0] != "-": other_args.insert(0, "--apr") ns_parser = self.parse_known_args_and_warn( diff --git a/openbb_terminal/custom_prompt_toolkit.py b/openbb_terminal/custom_prompt_toolkit.py index 0004ac5b774..d67a0abbafe 100644 --- a/openbb_terminal/custom_prompt_toolkit.py +++ b/openbb_terminal/custom_prompt_toolkit.py @@ -223,13 +223,13 @@ class NestedCompleter(Completer): if cmd: self.options = { k: self.original_options.get(cmd).options[k] # type: ignore - for k in self.original_options.get(cmd).options.keys() # type: ignore + for k in self.original_options.get(cmd).options # type: ignore if k not in self.flags_processed } else: self.options = { k: self.original_options[k] - for k in self.original_options.keys() + for k in self.original_options if k not in self.flags_processed } @@ -262,7 +262,7 @@ class NestedCompleter(Completer): else: self.options = { k: self.original_options[k] - for k in self.original_options.keys() + for k in self.original_options if k not in self.flags_processed } @@ -294,13 +294,13 @@ class NestedCompleter(Completer): if cmd: self.options = { k: self.original_options.get(cmd).options[k] # type: ignore - for k in self.original_options.get(cmd).options.keys() # type: ignore + for k in self.original_options.get(cmd).options # type: ignore if k not in self.flags_processed } else: self.options = { k: self.original_options[k] - for k in self.original_options.keys() + for k in self.original_options if k not in self.flags_processed } @@ -325,13 +325,13 @@ class NestedCompleter(Completer): if cmd: self.options = { k: self.original_options.get(cmd).options[k] # type: ignore - for k in self.original_options.get(cmd).options.keys() # type: ignore + for k in self.original_options.get(cmd).options # type: ignore if k not in self.flags_processed } else: self.options = { k: self.original_options[k] - for k in self.original_options.keys() + for k in self.original_options if k not in self.flags_processed } @@ -366,35 +366,32 @@ class NestedCompleter(Completer): if cmd: self.options = { k: self.original_options.get(cmd).options[k] # type: ignore - for k in self.original_options.get(cmd).options.keys() # type: ignore + for k in self.original_options.get(cmd).options # type: ignore if k not in self.flags_processed } else: self.options = { k: self.original_options[k] - for k in self.original_options.keys() + for k in self.original_options if k not in self.flags_processed } command = self.options.get(cmd) - if command: - options = command.options # type: ignore - else: - options = {} - command_options = [f"{cmd} {opt}" for opt in options.keys()] + options = command.options if command else {} # type: ignore + command_options = [f"{cmd} {opt}" for opt in options] text_list = [text in val for val in command_options] - if cmd and cmd in self.options.keys() and text_list: + if cmd and cmd in self.options and text_list: completer = WordCompleter( list(self.options.get(cmd).options.keys()), # type: ignore ignore_case=self.ignore_case, ) - elif bool([val for val in self.options.keys() if text in val]): + elif bool([val for val in self.options if text in val]): completer = WordCompleter( list(self.options.keys()), ignore_case=self.ignore_case ) else: # The user has delete part of the first command and we need to reset options - if bool([val for val in self.original_options.keys() if text in val]): + if bool([val for val in self.original_options if text in val]): self.options = self.original_options self.flags_processed = list() completer = WordCompleter( diff --git a/openbb_terminal/econometrics/econometrics_controller.py b/openbb_terminal/econometrics/econometrics_controller.py index c53ff96d2e2..220596d8155 100644 --- a/openbb_terminal/econometrics/econometrics_controller.py +++ b/openbb_terminal/econometrics/econometrics_controller.py @@ -158,7 +158,7 @@ class EconometricsController(BaseController): if session and obbff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} choices["load"] = { - "--file": {c: {} for c in self.DATA_FILES.keys()}, + "--file": {c: {} for c in self.DATA_FILES}, "-f": "--file", "-alias": None, "-a": "-alias", @@ -564,10 +564,9 @@ class EconometricsController(BaseController): ) if ns_parser: - if not ns_parser.name: - dataset_names = list(self.datasets.keys()) - else: - dataset_names = [ns_parser.name] + dataset_names = ( + list(self.datasets.keys()) if not ns_parser.name else [ns_parser.name] + ) for name in dataset_names: df = self.datasets[name] @@ -790,10 +789,11 @@ class EconometricsController(BaseController): index = ns_parser.index if index: - if "," in index: - values_found = [val.strip() for val in index.split(",")] - else: - values_found = [index] + values_found = ( + [val.strip() for val in index.split(",")] + if "," in index + else [index] + ) columns = list() for value in values_found: @@ -1735,32 +1735,31 @@ class EconometricsController(BaseController): parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES ) - if ns_parser: - if ns_parser.ts: - # We are going to pass through a variable number of series, so datasets will be a list of series - if len(ns_parser.ts) > 1: - datasets = [] - for series in ns_parser.ts: - if "." not in series: - console.print( - "[red]Invalid time series format. Should be dataset.column, " - "e.g. historical.open[/red]\n" - ) - else: - dataset, column = series.split(".") - datasets.append(self.datasets[dataset][column]) + if ns_parser and ns_parser.ts: + # We are going to pass through a variable number of series, so datasets will be a list of series + if len(ns_parser.ts) > 1: + datasets = [] + for series in ns_parser.ts: + if "." not in series: + console.print( + "[red]Invalid time series format. Should be dataset.column, " + "e.g. historical.open[/red]\n" + ) + else: + dataset, column = series.split(".") + datasets.append(self.datasets[dataset][column]) - econometrics_view.display_cointegration_test( - *datasets, - significant=ns_parser.significant, - plot=ns_parser.plot, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + econometrics_view.display_cointegration_test( + *datasets, + significant=ns_parser.significant, + plot=ns_parser.plot, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) - else: - console.print( - "[red]More than one dataset.column must be provided.\n[/red]" - ) + else: + console.print( + "[red]More than one dataset.column must be provided.\n[/red]" + ) diff --git a/openbb_terminal/economy/economy_controller.py b/openbb_terminal/economy/economy_controller.py index e36f6640c58..b7411a1abaf 100644 --- a/openbb_terminal/economy/economy_controller.py +++ b/openbb_terminal/economy/economy_controller.py @@ -227,9 +227,7 @@ class EconomyController(BaseController): if self.DATASETS: options = [ - option - for _, values in self.DATASETS.items() - for option in values.keys() + option for _, values in self.DATASETS.items() for option in values ] # help users to select multiple timeseries for one axis @@ -1154,15 +1152,15 @@ class EconomyController(BaseController): console.print(name) return - if ns_parser.start_date: - start_date = ns_parser.start_date.strftime("%Y-%m-%d") - else: - start_date = None + start_date = ( + ns_parser.start_date.strftime("%Y-%m-%d") + if ns_parser.start_date + else None + ) - if ns_parser.end_date: - end_date = ns_parser.end_date.strftime("%Y-%m-%d") - else: - end_date = None + end_date = ( + ns_parser.end_date.strftime("%Y-%m-%d") if ns_parser.end_date else None + ) # TODO: Add `Investing` to sources again when `investpy` is fixed @@ -1272,12 +1270,11 @@ class EconomyController(BaseController): units = self.UNITS[country.replace(" ", "_")][ parameter_abbreviation ] - if transform: - transformtype = ( - f" ({econdb_model.TRANSFORM[transform]}) " - ) - else: - transformtype = " " + transformtype = ( + f" ({econdb_model.TRANSFORM[transform]}) " + if transform + else " " + ) dataset_yaxis1[ f"{country}{transformtype}[{parameter}, Units: {units}]" ] = data[variable] @@ -1349,12 +1346,11 @@ class EconomyController(BaseController): units = self.UNITS[country.replace(" ", "_")][ parameter_abbreviation ] - if transform: - transformtype = ( - f" ({econdb_model.TRANSFORM[transform]}) " - ) - else: - transformtype = " " + transformtype = ( + f" ({econdb_model.TRANSFORM[transform]}) " + if transform + else " " + ) dataset_yaxis2[ f"{country}{transformtype}[{parameter}, Units: {units}]" ] = data[variable] diff --git a/openbb_terminal/economy/quantitative_analysis/qa_controller.py b/openbb_terminal/economy/quantitative_analysis/qa_controller.py index 2027c51d088..afe62293bc2 100644 --- a/openbb_terminal/economy/quantitative_analysis/qa_controller.py +++ b/openbb_terminal/economy/quantitative_analysis/qa_controller.py @@ -267,10 +267,7 @@ class QaController(StockBaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED ) - if isinstance(self.data, pd.Series): - data = self.data.to_frame() - else: - data = self.data + data = self.data.to_frame() if isinstance(self.data, pd.Series) else self.data if ns_parser: qa_view.display_raw( data=data, diff --git a/openbb_terminal/economy/yfinance_model.py b/openbb_terminal/economy/yfinance_model.py index 757191f0685..360662e5487 100644 --- a/openbb_terminal/economy/yfinance_model.py +++ b/openbb_terminal/economy/yfinance_model.py @@ -617,10 +617,7 @@ def get_index( pd.Series A series with the requested index """ - if index.lower() in INDICES: - ticker = INDICES[index.lower()]["ticker"] - else: - ticker = index + ticker = INDICES[index.lower()]["ticker"] if index.lower() in INDICES else index try: if start_date: @@ -737,10 +734,9 @@ def get_search_indices(keyword: list, limit: int = 10) -> pd.DataFrame: pd.Dataframe Dataframe with the available options. """ - if isinstance(keyword, str): - keyword_adjusted = keyword.replace(",", " ") - else: - keyword_adjusted = " ".join(keyword) + keyword_adjusted = ( + keyword.replace(",", " ") if isinstance(keyword, str) else " ".join(keyword) # type: ignore + ) indices = fd.select_indices() diff --git a/openbb_terminal/economy/yfinance_view.py b/openbb_terminal/economy/yfinance_view.py index 3767f8ba57d..13ef01d2f16 100644 --- a/openbb_terminal/economy/yfinance_view.py +++ b/openbb_terminal/economy/yfinance_view.py @@ -75,10 +75,7 @@ def show_indices( ax = external_axes[0] for index in indices: - if index.lower() in INDICES: - label = INDICES[index.lower()]["name"] - else: - label = index + label = INDICES[index.lower()]["name"] if index.lower() in INDICES else index if not indices_data[index].empty: if returns: diff --git a/openbb_terminal/forecast/helpers.py b/openbb_terminal/forecast/helpers.py index c65dd0f59fb..579a8939839 100644 --- a/openbb_terminal/forecast/helpers.py +++ b/openbb_terminal/forecast/helpers.py @@ -251,10 +251,7 @@ def prepare_scale_train_valid_test( "minmax": MinMaxScaler(), "normalization": Normalizer(), } - if Preprocess is None: - scaler = None - else: - scaler = pre_dict.get(Preprocess, None) + scaler = None if Preprocess is None else pre_dict.get(Preprocess, None) if s_end_date: data = data[data.index <= s_end_date] @@ -901,23 +898,28 @@ def clean_data( # check if target column is in data and if the target_column has any inf # replace all inf with nan. This is because darts does not handle inf # Creating a timeseries with fillna=True will replace all nan with interoplated values - if target_column and target_column in data.columns: - if data[target_column].isin([np.inf, -np.inf]).any(): - console.print( - f"[red]The target column [{target_column}] has inf values. Cleaning...[/red]\n" - ) - data = data.replace([np.inf, -np.inf], np.nan) + if ( + target_column + and target_column in data.columns + and data[target_column].isin([np.inf, -np.inf]).any() + ): + console.print( + f"[red]The target column [{target_column}] has inf values. Cleaning...[/red]\n" + ) + data = data.replace([np.inf, -np.inf], np.nan) # check if past covariates are in data and if they have any inf if past_covariates: covariates = past_covariates.split(",") for covariate in covariates: - if covariate in data.columns: - if data[covariate].isin([np.inf, -np.inf]).any(): - console.print( - f"[red]The covariate:{covariate} has inf values. Cleaning...[/red]\n" - ) - data = data.replace([np.inf, -np.inf], np.nan) + if ( + covariate in data.columns + and data[covariate].isin([np.inf, -np.inf]).any() + ): + console.print( + f"[red]The covariate:{covariate} has inf values. Cleaning...[/red]\n" + ) + data = data.replace([np.inf, -np.inf], np.nan) if isinstance(data, pd.Series): col = data.name diff --git a/openbb_terminal/forecast/linregr_model.py b/openbb_terminal/forecast/linregr_model.py index 27711fa13df..4ad548cc22c 100644 --- a/openbb_terminal/forecast/linregr_model.py +++ b/openbb_terminal/forecast/linregr_model.py @@ -80,10 +80,7 @@ def get_linear_regression_data( past_covariates, data, train_split, use_scalers ) - if past_covariates is not None: - lags_past_covariates = lags - else: - lags_past_covariates = None + lags_past_covariates = lags if past_covariates is not None else None lin_reg_model = LinearRegressionModel( output_chunk_length=output_chunk_length, diff --git a/openbb_terminal/forecast/regr_model.py b/openbb_terminal/forecast/regr_model.py index 5e27df13af4..5ebd3da6abd 100644 --- a/openbb_terminal/forecast/regr_model.py +++ b/openbb_terminal/forecast/regr_model.py @@ -74,10 +74,7 @@ def get_regression_data( past_covariates, data, train_split, use_scalers ) - if past_covariates is not None: - lags_past_covariates = lags - else: - lags_past_covariates = None + lags_past_covariates = lags if past_covariates is not None else None reg_model = RegressionModel( output_chunk_length=output_chunk_length, diff --git a/openbb_terminal/forex/forex_controller.py b/openbb_terminal/forex/forex_controller.py index 6c9d92df8c8..1ef383d19c7 100644 --- a/openbb_terminal/forex/forex_controller.py +++ b/openbb_terminal/forex/forex_controller.py @@ -293,10 +293,12 @@ class ForexController(BaseController): data = stocks_helper.process_candle(self.data) if ns_parser.raw: - if ns_parser.trendlines: - if (data.index[1] - data.index[0]).total_seconds() >= 86400: - data = stocks_helper.find_trendline(data, "OC_High", "high") - data = stocks_helper.find_trendline(data, "OC_Low", "low") + if ( + ns_parser.trendlines + and (data.index[1] - data.index[0]).total_seconds() >= 86400 + ): + data = stocks_helper.find_trendline(data, "OC_High", "high") + data = stocks_helper.find_trendline(data, "OC_Low", "low") qa_view.display_raw( data=data, diff --git a/openbb_terminal/forex/forex_helper.py b/openbb_terminal/forex/forex_helper.py index ec6663149b1..2bd4838ad0d 100644 --- a/openbb_terminal/forex/forex_helper.py +++ b/openbb_terminal/forex/forex_helper.py @@ -275,10 +275,9 @@ def display_candle( if "Volume" in data.columns: has_volume = bool(data["Volume"].sum() > 0) - if add_trend: - if (data.index[1] - data.index[0]).total_seconds() >= 86400: - data = stocks_helper.find_trendline(data, "OC_High", "high") - data = stocks_helper.find_trendline(data, "OC_Low", "low") + if add_trend and (data.index[1] - data.index[0]).total_seconds() >= 86400: + data = stocks_helper.find_trendline(data, "OC_High", "high") + data = stocks_helper.find_trendline(data, "OC_Low", "low") if use_matplotlib: ap0 = [] diff --git a/openbb_terminal/forex/oanda/oanda_controller.py b/openbb_terminal/forex/oanda/oanda_controller.py index 148666943cd..619a49b0ac0 100644 --- a/openbb_terminal/forex/oanda/oanda_controller.py +++ b/openbb_terminal/forex/oanda/oanda_controller.py @@ -302,9 +302,8 @@ class OandaController(BaseController): type=str, help="The pending order ID to cancel.", ) - if other_args: - if "-" not in other_args[0]: - other_args.insert(0, "-i") + if other_args and "-" not in other_args[0]: + other_args.insert(0, "-i") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: orderID = ns_parser.orderID @@ -372,9 +371,8 @@ class OandaController(BaseController): help="The number of units on the trade to close. If not set it " + "defaults to all units. ", ) - if other_args: - if "-i" not in other_args[0] and "-h" not in other_args[0]: - other_args.insert(0, "-i") + if other_args and "-i" not in other_args[0] and "-h" not in other_args[0]: + other_args.insert(0, "-i") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: orderID = ns_parser.orderID diff --git a/openbb_terminal/forex/oanda/oanda_model.py b/openbb_terminal/forex/oanda/oanda_model.py index 8f423bcaa6f..4a2b7aa8733 100644 --- a/openbb_terminal/forex/oanda/oanda_model.py +++ b/openbb_terminal/forex/oanda/oanda_model.py @@ -299,10 +299,11 @@ def create_order_request( "Error: An instrument should be loaded before running this command." ) return False - if "JPY" in instrument or "THB" in instrument or "HUF" in instrument: - price = round(price, 3) - else: - price = round(price, 5) + price = ( + round(price, 3) + if "JPY" in instrument or "THB" in instrument or "HUF" in instrument + else round(price, 5) + ) data = { "order": { "price": price, @@ -708,10 +709,7 @@ def get_calendar_request( else: previous = "" - if "impact" in response[i[0]]: - impact = response[i[0]]["impact"] - else: - impact = "" + impact = response[i[0]]["impact"] if "impact" in response[i[0]] else "" l_data.append( { @@ -726,8 +724,5 @@ def get_calendar_request( "Previous": previous, } ) - if len(l_data) == 0: - df_calendar = pd.DataFrame() - else: - df_calendar = pd.DataFrame(l_data) + df_calendar = pd.DataFrame() if len(l_data) == 0 else pd.DataFrame(l_data) return df_calendar diff --git a/openbb_terminal/futures/yfinance_model.py b/openbb_terminal/futures/yfinance_model.py index cb3db40608d..d9c76af35fb 100644 --- a/openbb_terminal/futures/yfinance_model.py +++ b/openbb_terminal/futures/yfinance_model.py @@ -40,7 +40,7 @@ MONTHS = { class HiddenPrints: def __enter__(self): self._original_stdout = sys.stdout - sys.stdout = open(os.devnull, "w") + sys.stdout = open(os.devnull, "w") # noqa: SIM115 def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() diff --git a/openbb_terminal/helper_funcs.py b/openbb_terminal/helper_funcs.py index 0072347598b..ce2830c52e2 100644 --- a/openbb_terminal/helper_funcs.py +++ b/openbb_terminal/helper_funcs.py @@ -132,9 +132,8 @@ def parse_and_split_input(an_input: str, custom_filters: List) -> List[str]: Command queue as list """ # Make sure that the user can go back to the root when doing "/" - if an_input: - if an_input == "/": - an_input = "home" + if an_input and an_input == "/": + an_input = "home" # everything from ` -f ` to the next known extension file_flag = r"(\ -f |\ --file )" @@ -308,13 +307,12 @@ def print_rich_table( for column in df.columns: table.add_column(str(column)) - if isinstance(floatfmt, list): - if len(floatfmt) != len(df.columns): - log_and_raise( - ValueError( - "Length of floatfmt list does not match length of DataFrame columns." - ) + if isinstance(floatfmt, list) and len(floatfmt) != len(df.columns): + log_and_raise( + ValueError( + "Length of floatfmt list does not match length of DataFrame columns." ) + ) if isinstance(floatfmt, str): floatfmt = [floatfmt for _ in range(len(df.columns))] @@ -865,10 +863,7 @@ def is_intraday(df: pd.DataFrame) -> bool: True if data is intraday """ granularity = df.index[1] - df.index[0] - if granularity >= timedelta(days=1): - intraday = False - else: - intraday = True + intraday = not granularity >= timedelta(days=1) return intraday @@ -888,10 +883,7 @@ def reindex_dates(df: pd.DataFrame) -> pd.DataFrame: pd.DataFrame Reindexed dataframe """ - if is_intraday(df): - date_format = "%b %d %H:%M" - else: - date_format = "%Y-%m-%d" + date_format = "%b %d %H:%M" if is_intraday(df) else "%Y-%m-%d" reindexed_df = df.reset_index() reindexed_df["date"] = reindexed_df["date"].dt.strftime(date_format) return reindexed_df @@ -906,7 +898,7 @@ def get_data(tweet): "%Y-%m-%d %H:%M:%S" ) - s_text = tweet["full_text"] if "full_text" in tweet.keys() else tweet["text"] + s_text = tweet["full_text"] if "full_text" in tweet else tweet["text"] return {"created_at": s_datetime, "text": s_text} @@ -1563,10 +1555,11 @@ def is_valid_axes_count( if len(axes) == n: return True - if custom_text: - print_text = custom_text - else: - print_text = f"Expected list of {n} axis item{'s' if n>1 else ''}." + print_text = ( + custom_text + if custom_text + else f"Expected list of {n} axis item{'s' if n > 1 else ''}." + ) if prefix_text: print_text = f"{prefix_text} {print_text}" @@ -1615,10 +1608,11 @@ def check_list_values(valid_values: List[str]): """ success_values = list() - if "," in given_values: - values_found = [val.strip() for val in given_values.split(",")] - else: - values_found = [given_values] + values_found = ( + [val.strip() for val in given_values.split(",")] + if "," in given_values + else [given_values] + ) for value in values_found: # check if the value is valid diff --git a/openbb_terminal/keys_controller.py b/openbb_terminal/keys_controller.py index fd9e4059bc3..8b8ef5bb665 100644 --- a/openbb_terminal/keys_controller.py +++ b/openbb_terminal/keys_controller.py @@ -43,13 +43,12 @@ class KeysController(BaseController): # pylint: disable=too-many-public-methods ): """Constructor""" super().__init__(queue) - if menu_usage: - if session and obbff.USE_PROMPT_TOOLKIT: - choices: dict = {c: {} for c in self.controller_choices} + if menu_usage and session and obbff.USE_PROMPT_TOOLKIT: + choices: dict = {c: {} for c in self.controller_choices} - choices["support"] = self.SUPPORT_CHOICES + choices["support"] = self.SUPPORT_CHOICES - self.completer = NestedCompleter.from_nested_dict(choices) + self.completer = NestedCompleter.from_nested_dict(choices) def check_keys_status(self) -> None: """Check keys status""" diff --git a/openbb_terminal/mutual_funds/avanza_view.py b/openbb_terminal/mutual_funds/avanza_view.py index 32a7ce6c6ea..b43a6dda969 100644 --- a/openbb_terminal/mutual_funds/avanza_view.py +++ b/openbb_terminal/mutual_funds/avanza_view.py @@ -100,10 +100,11 @@ def display_info(isin: str): + f"from {fund_data['adminCompany']['name']}.\nFund currency is {fund_data['currency']}" f" and it the fund started {fund_data['startDate']}." ) - if fund_data["indexFund"]: - text = text + " It is a index fund." - else: - text = text + " It is not a index fund." + text = ( + text + " It is a index fund." + if fund_data["indexFund"] + else text + " It is not a index fund." + ) text = ( text + f" The fund manages {str(fund_data['capital'])} {fund_data['currency']}. The " diff --git a/openbb_terminal/mutual_funds/mstarpy_view.py b/openbb_terminal/mutual_funds/mstarpy_view.py index 7f8f53f8d38..94c4c36b601 100644 --- a/openbb_terminal/mutual_funds/mstarpy_view.py +++ b/openbb_terminal/mutual_funds/mstarpy_view.py @@ -172,10 +172,7 @@ def display_load( Country to filter on """ - if country: - iso_country = mapping_country[country] - else: - iso_country = "" + iso_country = mapping_country[country] if country else "" funds = mstarpy_model.load_funds(term, country=iso_country) if isinstance(funds, mstarpy.Funds): return funds @@ -200,19 +197,17 @@ def display_search( limit: int Number to show """ - if country: - iso_country = mapping_country[country] - else: - iso_country = "" + iso_country = mapping_country[country] if country else "" searches = mstarpy_model.search_funds(term, country=iso_country, pageSize=limit) if searches.empty: console.print("No matches found.") return - if country: - title = f"Mutual Funds from {country.title()} matching {term}" - else: - title = f"Mutual Funds matching {term}" + title = ( + f"Mutual Funds from {country.title()} matching {term}" + if country + else f"Mutual Funds matching {term}" + ) print_rich_table( searches, @@ -232,10 +227,7 @@ def display_sector(loaded_funds: mstarpy.Funds, asset_type: str = "equity"): asset_type: str can be equity or fixed income """ - if asset_type == "equity": - key = "EQUITY" - else: - key = "FIXEDINCOME" + key = "EQUITY" if asset_type == "equity" else "FIXEDINCOME" d = loaded_funds.sector()[key] fig, ax = plt.subplots(figsize=(10, 10)) diff --git a/openbb_terminal/mutual_funds/mutual_fund_controller.py b/openbb_terminal/mutual_funds/mutual_fund_controller.py index 3f748a7a378..dfb65c61f1d 100644 --- a/openbb_terminal/mutual_funds/mutual_fund_controller.py +++ b/openbb_terminal/mutual_funds/mutual_fund_controller.py @@ -69,10 +69,11 @@ class FundController(BaseController): def print_help(self): """Print help""" if self.fund_name: - if self.fund_symbol: - fund_string = f"{self.fund_name} ({self.fund_symbol})" - else: - fund_string = f"{self.fund_name}" + fund_string = ( + f"{self.fund_name} ({self.fund_symbol})" + if self.fund_symbol + else f"{self.fund_name}" + ) else: fund_string = "" mt = MenuText("funds/") diff --git a/openbb_terminal/parent_classes.py b/openbb_terminal/parent_classes.py index 554dc2309b9..5cdcbf58314 100644 --- a/openbb_terminal/parent_classes.py +++ b/openbb_terminal/parent_classes.py @@ -114,10 +114,11 @@ class BaseController(metaclass=ABCMeta): @property def choices_default(self): - if self.CHOICES_GENERATION: - choices = build_controller_choice_map(controller=self) - else: - choices = {} + choices = ( + build_controller_choice_map(controller=self) + if self.CHOICES_GENERATION + else {} + ) return choices @@ -585,10 +586,9 @@ class BaseController(metaclass=ABCMeta): ns_parser = self.parse_simple_args(parser, other_args) - if ns_parser: - if ns_parser.expression: - expression = " ".join(ns_parser.expression) - search_wikipedia(expression) + if ns_parser and ns_parser.expression: + expression = " ".join(ns_parser.expression) + search_wikipedia(expression) @log_start_end(log=logger) def call_record(self, other_args) -> None: @@ -1288,9 +1288,11 @@ class CryptoBaseController(BaseController, metaclass=ABCMeta): ) if ns_parser: - if ns_parser.source in ("YahooFinance", "CoinGecko"): - if ns_parser.vs == "usdt": - ns_parser.vs = "usd" + if ( + ns_parser.source in ("YahooFinance", "CoinGecko") + and ns_parser.vs == "usdt" + ): + ns_parser.vs = "usd" (self.current_df) = cryptocurrency_helpers.load( symbol=ns_parser.coin.lower(), to_symbol=ns_parser.vs, diff --git a/openbb_terminal/portfolio/portfolio_controller.py b/openbb_terminal/portfolio/portfolio_controller.py index 42b40b3f660..6c977e26fcf 100644 --- a/openbb_terminal/portfolio/portfolio_controller.py +++ b/openbb_terminal/portfolio/portfolio_controller.py @@ -466,49 +466,51 @@ class PortfolioController(BaseController): dest="tables", help="Whether to also include the assets/sectors tables of both the benchmark and the portfolio.", ) - if other_args: - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-a") + if other_args and other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-a") ns_parser = self.parse_known_args_and_warn(parser, other_args, limit=10) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - if ns_parser.agg == "assets": - portfolio_view.display_assets_allocation( - portfolio_engine=self.portfolio, - limit=ns_parser.limit, - tables=ns_parser.tables, - recalculate=self.recalculate_alloc, - ) - elif ns_parser.agg == "sectors": - portfolio_view.display_sectors_allocation( - portfolio_engine=self.portfolio, - limit=ns_parser.limit, - tables=ns_parser.tables, - recalculate=self.recalculate_alloc, - ) - elif ns_parser.agg == "countries": - portfolio_view.display_countries_allocation( - portfolio_engine=self.portfolio, - limit=ns_parser.limit, - tables=ns_parser.tables, - recalculate=self.recalculate_alloc, - ) - elif ns_parser.agg == "regions": - portfolio_view.display_regions_allocation( - portfolio_engine=self.portfolio, - limit=ns_parser.limit, - tables=ns_parser.tables, - recalculate=self.recalculate_alloc, - ) - else: - console.print( - f"{ns_parser.agg} is not an available option. The options " - f"are: {', '.join(self.AGGREGATION_METRICS)}" - ) + ) + ): + if ns_parser.agg == "assets": + portfolio_view.display_assets_allocation( + portfolio_engine=self.portfolio, + limit=ns_parser.limit, + tables=ns_parser.tables, + recalculate=self.recalculate_alloc, + ) + elif ns_parser.agg == "sectors": + portfolio_view.display_sectors_allocation( + portfolio_engine=self.portfolio, + limit=ns_parser.limit, + tables=ns_parser.tables, + recalculate=self.recalculate_alloc, + ) + elif ns_parser.agg == "countries": + portfolio_view.display_countries_allocation( + portfolio_engine=self.portfolio, + limit=ns_parser.limit, + tables=ns_parser.tables, + recalculate=self.recalculate_alloc, + ) + elif ns_parser.agg == "regions": + portfolio_view.display_regions_allocation( + portfolio_engine=self.portfolio, + limit=ns_parser.limit, + tables=ns_parser.tables, + recalculate=self.recalculate_alloc, + ) + else: + console.print( + f"{ns_parser.agg} is not an available option. The options " + f"are: {', '.join(self.AGGREGATION_METRICS)}" + ) @log_start_end(log=logger) def call_attrib(self, other_args: List[str]): @@ -549,9 +551,8 @@ class PortfolioController(BaseController): help="View raw attribution values in a table", ) - if other_args: - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-a") + if other_args and other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-a") ns_parser = self.parse_known_args_and_warn(parser, other_args, limit=10) @@ -639,14 +640,17 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_performance_vs_benchmark( - self.portfolio, - ns_parser.show_trades, - ) + ) + ): + portfolio_view.display_performance_vs_benchmark( + self.portfolio, + ns_parser.show_trades, + ) @log_start_end(log=logger) def call_holdv(self, other_args: List[str]): @@ -672,18 +676,17 @@ class PortfolioController(BaseController): raw=True, limit=10, ) - if ns_parser: - if check_portfolio_benchmark_defined( - self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_holdings_value( - self.portfolio, - ns_parser.unstack, - ns_parser.raw, - ns_parser.limit, - ns_parser.export, - ns_parser.sheet_name, - ) + if ns_parser and check_portfolio_benchmark_defined( + self.portfolio_name, self.benchmark_name + ): + portfolio_view.display_holdings_value( + self.portfolio, + ns_parser.unstack, + ns_parser.raw, + ns_parser.limit, + ns_parser.export, + ns_parser.sheet_name, + ) @log_start_end(log=logger) def call_holdp(self, other_args: List[str]): @@ -709,18 +712,17 @@ class PortfolioController(BaseController): raw=True, limit=10, ) - if ns_parser: - if check_portfolio_benchmark_defined( - self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_holdings_percentage( - self.portfolio, - ns_parser.unstack, - ns_parser.raw, - ns_parser.limit, - ns_parser.export, - ns_parser.sheet_name, - ) + if ns_parser and check_portfolio_benchmark_defined( + self.portfolio_name, self.benchmark_name + ): + portfolio_view.display_holdings_percentage( + self.portfolio, + ns_parser.unstack, + ns_parser.raw, + ns_parser.limit, + ns_parser.export, + ns_parser.sheet_name, + ) @log_start_end(log=logger) def call_var(self, other_args: List[str]): @@ -925,17 +927,20 @@ class PortfolioController(BaseController): export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES, ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_yearly_returns( - self.portfolio, - ns_parser.period, - ns_parser.raw, - ns_parser.export, - ns_parser.sheet_name, - ) + ) + ): + portfolio_view.display_yearly_returns( + self.portfolio, + ns_parser.period, + ns_parser.raw, + ns_parser.export, + ns_parser.sheet_name, + ) @log_start_end(log=logger) def call_mret(self, other_args: List[str]): @@ -990,21 +995,24 @@ class PortfolioController(BaseController): export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED, ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_monthly_returns( - self.portfolio, - ns_parser.period, - ns_parser.instrument, - ns_parser.graph, - ns_parser.show_vals, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_monthly_returns( + self.portfolio, + ns_parser.period, + ns_parser.instrument, + ns_parser.graph, + ns_parser.show_vals, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_dret(self, other_args: List[str]): @@ -1035,20 +1043,23 @@ class PortfolioController(BaseController): export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES, ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_daily_returns( - self.portfolio, - ns_parser.period, - ns_parser.raw, - ns_parser.limit, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_daily_returns( + self.portfolio, + ns_parser.period, + ns_parser.raw, + ns_parser.limit, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_maxdd(self, other_args: List[str]): @@ -1062,14 +1073,17 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_maximum_drawdown( - self.portfolio, - export=ns_parser.export, - ) + ) + ): + portfolio_view.display_maximum_drawdown( + self.portfolio, + export=ns_parser.export, + ) @log_start_end(log=logger) def call_rvol(self, other_args: List[str]): @@ -1095,18 +1109,21 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_rolling_volatility( - self.portfolio, - window=ns_parser.period, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_rolling_volatility( + self.portfolio, + window=ns_parser.period, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_rsharpe(self, other_args: List[str]): @@ -1140,19 +1157,22 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_rolling_sharpe( - self.portfolio, - risk_free_rate=ns_parser.risk_free_rate / 100, - window=ns_parser.period, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_rolling_sharpe( + self.portfolio, + risk_free_rate=ns_parser.risk_free_rate / 100, + window=ns_parser.period, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_rsort(self, other_args: List[str]): @@ -1186,19 +1206,22 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_rolling_sortino( - portfolio_engine=self.portfolio, - risk_free_rate=ns_parser.risk_free_rate / 100, - window=ns_parser.period, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_rolling_sortino( + portfolio_engine=self.portfolio, + risk_free_rate=ns_parser.risk_free_rate / 100, + window=ns_parser.period, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_rbeta(self, other_args: List[str]): @@ -1224,18 +1247,21 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_rolling_beta( - self.portfolio, - window=ns_parser.period, - export=ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_rolling_beta( + self.portfolio, + window=ns_parser.period, + export=ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_metric(self, other_args: List[str]): @@ -1269,149 +1295,148 @@ class PortfolioController(BaseController): ns_parser = self.parse_known_args_and_warn( parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED ) - if ns_parser: - if check_portfolio_benchmark_defined( - self.portfolio_name, self.benchmark_name - ): - if ns_parser.metric == "skew": - portfolio_view.display_skewness( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "kurtosis": - portfolio_view.display_kurtosis( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "volatility": - portfolio_view.display_volatility( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "sharpe": - portfolio_view.display_sharpe_ratio( - self.portfolio, - ns_parser.risk_free_rate / 100, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "sortino": - portfolio_view.display_sortino_ratio( - self.portfolio, - ns_parser.risk_free_rate / 100, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "maxdrawdown": - portfolio_view.display_maximum_drawdown_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "rsquare": - portfolio_view.display_rsquare( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "gaintopain": - portfolio_view.display_gaintopain_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "trackerr": - portfolio_view.display_tracking_error( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "information": - portfolio_view.display_information_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "tail": - portfolio_view.display_tail_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "commonsense": - portfolio_view.display_common_sense_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "jensens": - portfolio_view.display_jensens_alpha( - self.portfolio, - ns_parser.risk_free_rate / 100, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "calmar": - portfolio_view.display_calmar_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "kelly": - portfolio_view.display_kelly_criterion( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "payoff" and self.portfolio is not None: - portfolio_view.display_payoff_ratio( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) - elif ns_parser.metric == "profitfactor" and self.portfolio is not None: - portfolio_view.display_profit_factor( - self.portfolio, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + if ns_parser and check_portfolio_benchmark_defined( + self.portfolio_name, self.benchmark_name + ): + if ns_parser.metric == "skew": + portfolio_view.display_skewness( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "kurtosis": + portfolio_view.display_kurtosis( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "volatility": + portfolio_view.display_volatility( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "sharpe": + portfolio_view.display_sharpe_ratio( + self.portfolio, + ns_parser.risk_free_rate / 100, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "sortino": + portfolio_view.display_sortino_ratio( + self.portfolio, + ns_parser.risk_free_rate / 100, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "maxdrawdown": + portfolio_view.display_maximum_drawdown_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "rsquare": + portfolio_view.display_rsquare( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "gaintopain": + portfolio_view.display_gaintopain_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "trackerr": + portfolio_view.display_tracking_error( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "information": + portfolio_view.display_information_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "tail": + portfolio_view.display_tail_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "commonsense": + portfolio_view.display_common_sense_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "jensens": + portfolio_view.display_jensens_alpha( + self.portfolio, + ns_parser.risk_free_rate / 100, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "calmar": + portfolio_view.display_calmar_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "kelly": + portfolio_view.display_kelly_criterion( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "payoff" and self.portfolio is not None: + portfolio_view.display_payoff_ratio( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) + elif ns_parser.metric == "profitfactor" and self.portfolio is not None: + portfolio_view.display_profit_factor( + self.portfolio, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_distr(self, other_args: List[str]): @@ -1441,19 +1466,22 @@ class PortfolioController(BaseController): raw=True, export_allowed=EXPORT_BOTH_RAW_DATA_AND_FIGURES, ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_distribution_returns( - self.portfolio, - ns_parser.period, - ns_parser.raw, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_distribution_returns( + self.portfolio, + ns_parser.period, + ns_parser.raw, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) @log_start_end(log=logger) def call_summary(self, other_args: List[str]): @@ -1490,19 +1518,22 @@ class PortfolioController(BaseController): other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED, ) - if ns_parser and self.portfolio is not None: - if check_portfolio_benchmark_defined( + if ( + ns_parser + and self.portfolio is not None + and check_portfolio_benchmark_defined( self.portfolio_name, self.benchmark_name - ): - portfolio_view.display_summary( - self.portfolio, - ns_parser.period, - ns_parser.risk_free_rate / 100, - ns_parser.export, - sheet_name=" ".join(ns_parser.sheet_name) - if ns_parser.sheet_name - else None, - ) + ) + ): + portfolio_view.display_summary( + self.portfolio, + ns_parser.period, + ns_parser.risk_free_rate / 100, + ns_parser.export, + sheet_name=" ".join(ns_parser.sheet_name) + if ns_parser.sheet_name + else None, + ) def check_portfolio_benchmark_defined(portfolio_name: str, benchmark_name: str) -> bool: diff --git a/openbb_terminal/portfolio/portfolio_optimization/parameters/Parameter.py b/openbb_terminal/portfolio/portfolio_optimization/parameters/Parameter.py index 82c258809cc..4cdc065e48a 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/parameters/Parameter.py +++ b/openbb_terminal/portfolio/portfolio_optimization/parameters/Parameter.py @@ -48,12 +48,13 @@ class Parameter: raise TypeError( f"Default for '{self.name}' must be of type '{self.type_.__name__}'." ) - if self.choices is not None: - if not all(self.validate_type(choice) for choice in self.choices): - raise TypeError( - f"Choices must be of the same type as the parameter.\n" - f"'{self.name}': '{self.choices}' -> '{self.type_.__name__}'" - ) + if self.choices is not None and not all( + self.validate_type(choice) for choice in self.choices + ): + raise TypeError( + f"Choices must be of the same type as the parameter.\n" + f"'{self.name}': '{self.choices}' -> '{self.type_.__name__}'" + ) if self.choices is not None and self.default not in self.choices: raise ValueError( f"Parameter '{self.name}' must be one of type '{self.choices}'." diff --git a/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py index e38739fe735..13063f7fa5f 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py +++ b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_controller.py @@ -120,7 +120,7 @@ class ParametersController(BaseController): mt.add_raw("\n") mt.add_info("_parameters_") if self.current_model: - max_len = max(len(k) for k in self.params.keys()) + max_len = max(len(k) for k in self.params) for k, v in self.params.items(): v = params_helpers.booltostr(v) all_params = DEFAULT_PARAMETERS + MODEL_PARAMS[self.current_model] @@ -129,7 +129,7 @@ class ParametersController(BaseController): f" [param]{k}{' ' * (max_len - len(k))} :[/param] {v}\n" ) else: - max_len = max(len(k) for k in self.params.keys()) + max_len = max(len(k) for k in self.params) for k, v in self.params.items(): v = params_helpers.booltostr(v) mt.add_raw( @@ -306,11 +306,10 @@ class ParametersController(BaseController): argument = ns_parser.argument[0] value = ns_parser.argument[1] - if self.current_model: - if argument not in self.params: - console.print( - "[red]The parameter you are trying to access is unused in this model.[/red]\n" - ) + if self.current_model and argument not in self.params: + console.print( + "[red]The parameter you are trying to access is unused in this model.[/red]\n" + ) try: value = float(value) diff --git a/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py index 71007a80741..2b6e5840939 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py +++ b/openbb_terminal/portfolio/portfolio_optimization/parameters/params_view.py @@ -36,10 +36,7 @@ def load_file(path: str = "") -> Tuple[dict, str]: params_obj.optionxform = str # type: ignore params: dict = dict(params_obj["OPENBB"].items()) - if "technique" in params: - current_model = params["technique"] - else: - current_model = "" + current_model = params["technique"] if "technique" in params else "" elif str(path).endswith(".xlsx"): params, _ = excel_model.load_configuration(path) @@ -50,7 +47,7 @@ def load_file(path: str = "") -> Tuple[dict, str]: converted_parameters = check_convert_parameters(received_parameters=params) - max_len = max(len(k) for k in converted_parameters.keys()) + max_len = max(len(k) for k in converted_parameters) help_text = "[info]Parameters:[/info]\n" if current_model: diff --git a/openbb_terminal/portfolio/portfolio_optimization/po_controller.py b/openbb_terminal/portfolio/portfolio_optimization/po_controller.py index 17d59a0a1f2..13a273335bf 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/po_controller.py +++ b/openbb_terminal/portfolio/portfolio_optimization/po_controller.py @@ -254,18 +254,17 @@ class PortfolioOptimizationController(BaseController): self.completer = NestedCompleter.from_nested_dict(choices) def update_runtime_choices(self): - if session and obbff.USE_PROMPT_TOOLKIT: - if self.portfolios: - self.choices["show"]["--portfolios"] = { - c: {} for c in list(self.portfolios.keys()) - } - self.choices["rpf"]["--portfolios"] = { - c: {} for c in list(self.portfolios.keys()) - } - self.choices["plot"]["--portfolios"] = { - c: {} for c in list(self.portfolios.keys()) - } - self.completer = NestedCompleter.from_nested_dict(self.choices) + if session and obbff.USE_PROMPT_TOOLKIT and self.portfolios: + self.choices["show"]["--portfolios"] = { + c: {} for c in list(self.portfolios.keys()) + } + self.choices["rpf"]["--portfolios"] = { + c: {} for c in list(self.portfolios.keys()) + } + self.choices["plot"]["--portfolios"] = { + c: {} for c in list(self.portfolios.keys()) + } + self.completer = NestedCompleter.from_nested_dict(self.choices) def print_help(self): """Print help""" @@ -570,11 +569,9 @@ class PortfolioOptimizationController(BaseController): else: self.current_file = " ".join(ns_parser.file) - if self.current_file in self.optimization_file_map: - file_location = self.optimization_file_map[self.current_file] - else: - file_location = self.current_file # type: ignore - + file_location = self.optimization_file_map.get( + self.current_file, self.current_file + ) self.params, self.current_model = params_view.load_file(file_location) # type: ignore @log_start_end(log=logger) @@ -612,9 +609,8 @@ class PortfolioOptimizationController(BaseController): default=[], help="Show selected saved portfolios", ) - if other_args: - if "-" not in other_args[0]: - other_args.insert(0, "-pf") + if other_args and "-" not in other_args[0]: + other_args.insert(0, "-pf") parser = self.po_parser(parser, ct=True) ns_parser = self.parse_known_args_and_warn(parser, other_args) @@ -651,9 +647,8 @@ class PortfolioOptimizationController(BaseController): default=[], help="portfolios to be removed from the saved portfolios", ) - if other_args: - if "-" not in other_args[0]: - other_args.insert(0, "-pf") + if other_args and "-" not in other_args[0]: + other_args.insert(0, "-pf") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: @@ -819,9 +814,8 @@ class PortfolioOptimizationController(BaseController): r=True, a=True, ) - if other_args: - if "-" not in other_args[0]: - other_args.insert(0, "-pf") + if other_args and "-" not in other_args[0]: + other_args.insert(0, "-pf") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: @@ -2212,10 +2206,11 @@ class PortfolioOptimizationController(BaseController): p_views = ns_parser.p_views q_views = ns_parser.q_views - if ns_parser.benchmark is None: - benchmark = None - else: - benchmark = self.portfolios[ns_parser.benchmark.upper()] + benchmark = ( + None + if ns_parser.benchmark is None + else self.portfolios[ns_parser.benchmark.upper()] + ) table = True if "historic_period_sa" in vars(ns_parser): diff --git a/openbb_terminal/portfolio/portfolio_optimization/po_engine.py b/openbb_terminal/portfolio/portfolio_optimization/po_engine.py index 9b38705a041..5bfb2abdbb4 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/po_engine.py +++ b/openbb_terminal/portfolio/portfolio_optimization/po_engine.py @@ -104,7 +104,7 @@ class PoEngine: symbols = [] for item in symbols_categories.items(): _, values = item - for v in values.keys(): + for v in values: symbols.append(v) return list(set(symbols)) diff --git a/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py b/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py index b8eefb379ea..76865af3856 100644 --- a/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py +++ b/openbb_terminal/portfolio/portfolio_optimization/yahoo_finance_model.py @@ -178,10 +178,7 @@ def process_stocks( stock_closes = None if start_date != "": - if end_date == "": - end_ = date.today() - else: - end_ = date.fromisoformat(end_date) + end_ = date.today() if end_date == "" else date.fromisoformat(end_date) # Check if end date is on weekend if end_.weekday() >= 5: @@ -384,12 +381,13 @@ def process_returns( elif freq.upper() in ["W", "M"]: last_day = stock_returns.index[-1] stock_returns = stock_returns.resample(freq).last() - if freq.upper() == ["W"]: - if last_day.weekday() < 4: - stock_returns = stock_returns.iloc[:-1, :] - if freq.upper() == ["M"]: - if monthrange(last_day.year, last_day.month)[1] - last_day.day <= 5: - stock_returns = stock_returns.iloc[:-1, :] + if freq.upper() == ["W"] and last_day.weekday() < 4: + stock_returns = stock_returns.iloc[:-1, :] + if ( + freq.upper() == ["M"] + and monthrange(last_day.year, last_day.month)[1] - last_day.day <= 5 + ): + stock_returns = stock_returns.iloc[:-1, :] # Calculate returns if log_returns is True: diff --git a/openbb_terminal/reports/reports_model.py b/openbb_terminal/reports/reports_model.py index 602cabef263..f5ac7a370e1 100644 --- a/openbb_terminal/reports/reports_model.py +++ b/openbb_terminal/reports/reports_model.py @@ -102,9 +102,8 @@ def get_arg_choices(report_name: str, arg_name: str) -> Union[List[str], None]: """ choices = None - if report_name in ("forex", "portfolio"): - if "--" + arg_name in REPORT_CHOICES[report_name]: # type: ignore - choices = list(REPORT_CHOICES[report_name]["--" + arg_name].keys()) # type: ignore + if report_name in ("forex", "portfolio") and "--" + arg_name in REPORT_CHOICES[report_name]: # type: ignore + choices = list(REPORT_CHOICES[report_name]["--" + arg_name].keys()) # type: ignore return choices diff --git a/openbb_terminal/rich_config.py b/openbb_terminal/rich_config.py index 64c48d1526f..741f9d9b366 100644 --- a/openbb_terminal/rich_config.py +++ b/openbb_terminal/rich_config.py @@ -107,9 +107,8 @@ def get_ordered_list_sources(command_path: str): context = command_path.split("/")[1] # Grab the load source from that context if it exists, otherwise throws an error - if context in json_doc: - if "load" in json_doc[context]: - return json_doc[context]["load"] + if context in json_doc and "load" in json_doc[context]: + return json_doc[context]["load"] # We didn't find the next level, so flag that that command default source is missing # Which means that there aren't more than 1 source and therefore no selection is necessary @@ -190,10 +189,11 @@ class MenuText: column alignment for the value. This allows for a better UX experience. """ parameter_translated = i18n.t(self.menu_path + key_param) - if col_align > len(parameter_translated): - space = (col_align - len(parameter_translated)) * " " - else: - space = "" + space = ( + (col_align - len(parameter_translated)) * " " + if col_align > len(parameter_translated) + else "" + ) self.menu_text += f"[param]{parameter_translated}{space}:[/param] {value}\n" def add_cmd(self, key_command: str, condition: bool = True): @@ -216,10 +216,7 @@ class MenuText: sources = get_ordered_list_sources(f"/{self.menu_path}{key_command}") if sources: - if self.col_src > len(cmd): - space = (self.col_src - len(cmd)) * " " - else: - space = " " + space = (self.col_src - len(cmd)) * " " if self.col_src > len(cmd) else " " cmd += f"{space}[src][{', '.join(sources)}][/src]" self.menu_text += cmd + "\n" diff --git a/openbb_terminal/session/local_model.py b/openbb_terminal/session/local_model.py index ca990518e99..44190baece4 100644 --- a/openbb_terminal/session/local_model.py +++ b/openbb_terminal/session/local_model.py @@ -156,10 +156,9 @@ def update_sync_flag(settings: dict) -> bool: bool The sync flag. """ - if settings: - if settings.get("SYNC_ENABLED", "").lower() == "false": - obbff.SYNC_ENABLED = False - return False + if settings and settings.get("SYNC_ENABLED", "").lower() == "false": + obbff.SYNC_ENABLED = False + return False obbff.SYNC_ENABLED = True return True @@ -203,10 +202,11 @@ def get_routine( """ try: user_folder = USER_ROUTINES_DIRECTORY / User.get_uuid() - if os.path.exists(user_folder / file_name): - file_path = user_folder / file_name - else: - file_path = folder / file_name + file_path = ( + user_folder / file_name + if os.path.exists(user_folder / file_name) + else folder / file_name + ) with open(file_path) as f: routine = "".join(f.readlines()) diff --git a/openbb_terminal/session/user.py b/openbb_terminal/session/user.py index f53993dd45d..0abcbd2def6 100644 --- a/openbb_terminal/session/user.py +++ b/openbb_terminal/session/user.py @@ -52,10 +52,7 @@ class User: if not User.is_guest(): console.print(f"[info]email:[/info] {cls._email}") console.print(f"[info]uuid:[/info] {cls._uuid}") - if obbff.SYNC_ENABLED is True: - sync = "ON" - else: - sync = "OFF" + sync = "ON" if obbff.SYNC_ENABLED is True else "OFF" console.print(f"[info]sync:[/info] {sync}") else: User.print_guest_message() diff --git a/openbb_terminal/settings_controller.py b/openbb_terminal/settings_controller.py index e0fb778edd7..9a01dc6be1d 100644 --- a/openbb_terminal/settings_controller.py +++ b/openbb_terminal/settings_controller.py @@ -583,69 +583,64 @@ class SettingsController(BaseController): other_args.insert(0, "--folder") ns_parser = self.parse_simple_args(parser, other_args) - if ns_parser: - if other_args or self.queue: - if other_args: - userdata_path = "" + if ns_parser and (other_args or self.queue): + userdata_path = "" if other_args else "/" + + userdata_path += "/".join([ns_parser.folder] + self.queue) + self.queue = [] + + userdata_path = userdata_path.replace("'", "").replace('"', "") + + default_path = Path.home() / "OpenBBUserData" + + success_userdata = False + while not success_userdata: + if userdata_path.upper() == "DEFAULT": + console.print( + f"User data to be saved in the default folder: '{default_path}'" + ) + self.set_path_config("OPENBB_USER_DATA_DIRECTORY", default_path) + success_userdata = True else: - # Re-add the initial slash for an absolute directory provided - userdata_path = "/" - - userdata_path += "/".join([ns_parser.folder] + self.queue) - self.queue = [] - - userdata_path = userdata_path.replace("'", "").replace('"', "") - - default_path = Path.home() / "OpenBBUserData" - - success_userdata = False - while not success_userdata: - if userdata_path.upper() == "DEFAULT": - console.print( - f"User data to be saved in the default folder: '{default_path}'" + # If the path selected does not start from the user root, give relative location from root + if userdata_path[0] == "~": + userdata_path = userdata_path.replace( + "~", os.path.expanduser("~") + ) + + # Check if the directory exists + if os.path.isdir(userdata_path): + console.print( + f"User data to be saved in the selected folder: '{userdata_path}'" + ) + self.set_path_config( + "OPENBB_USER_DATA_DIRECTORY", userdata_path ) - self.set_path_config("OPENBB_USER_DATA_DIRECTORY", default_path) success_userdata = True else: - # If the path selected does not start from the user root, give relative location from root - if userdata_path[0] == "~": - userdata_path = userdata_path.replace( - "~", os.path.expanduser("~") - ) + console.print( + "[red]The path selected to user data does not exist![/red]\n" + ) + user_opt = "None" + while user_opt not in ("Y", "N"): + user_opt = input( + f"Do you wish to create folder: `{userdata_path}` ? [Y/N]\n" + ).upper() - # Check if the directory exists - if os.path.isdir(userdata_path): + if user_opt == "Y": + os.makedirs(userdata_path) console.print( - f"User data to be saved in the selected folder: '{userdata_path}'" + f"[green]Folder '{userdata_path}' successfully created.[/green]" ) self.set_path_config( "OPENBB_USER_DATA_DIRECTORY", userdata_path ) - success_userdata = True else: + # Do not update userdata_folder path since we will keep the same as before console.print( - "[red]The path selected to user data does not exist![/red]\n" + "[yellow]User data to keep being saved in " + + f"the selected folder: {str(paths.USER_DATA_DIRECTORY)}[/yellow]" ) - user_opt = "None" - while user_opt not in ("Y", "N"): - user_opt = input( - f"Do you wish to create folder: `{userdata_path}` ? [Y/N]\n" - ).upper() - - if user_opt == "Y": - os.makedirs(userdata_path) - console.print( - f"[green]Folder '{userdata_path}' successfully created.[/green]" - ) - self.set_path_config( - "OPENBB_USER_DATA_DIRECTORY", userdata_path - ) - else: - # Do not update userdata_folder path since we will keep the same as before - console.print( - "[yellow]User data to keep being saved in " - + f"the selected folder: {str(paths.USER_DATA_DIRECTORY)}[/yellow]" - ) - success_userdata = True + success_userdata = True console.print() diff --git a/openbb_terminal/stocks/comparison_analysis/ca_controller.py b/openbb_terminal/stocks/comparison_analysis/ca_controller.py index 36f114dbfbf..18aefe8ec69 100644 --- a/openbb_terminal/stocks/comparison_analysis/ca_controller.py +++ b/openbb_terminal/stocks/comparison_analysis/ca_controller.py @@ -264,10 +264,11 @@ class ComparisonAnalysisController(BaseController): if ns_parser: if self.ticker: if ns_parser.source == "Finviz": - if ns_parser.b_no_country: - compare_list = ["Sector", "Industry"] - else: - compare_list = ["Sector", "Industry", "Country"] + compare_list = ( + ["Sector", "Industry"] + if ns_parser.b_no_country + else ["Sector", "Industry", "Country"] + ) self.similar = finviz_compare_model.get_similar_companies( self.ticker, compare_list diff --git a/openbb_terminal/stocks/dark_pool_shorts/finra_model.py b/openbb_terminal/stocks/dark_pool_shorts/finra_model.py index b5d160aa6c1..46fd8a6e6a8 100644 --- a/openbb_terminal/stocks/dark_pool_shorts/finra_model.py +++ b/openbb_terminal/stocks/dark_pool_shorts/finra_model.py @@ -230,10 +230,7 @@ def getATSdata(limit: int = 1000, tier_ats: str = "T1") -> Tuple[pd.DataFrame, D Tuple[pd.DataFrame, Dict] Dark Pools (ATS) Data, Tickers from Dark Pools with better regression slope """ - if tier_ats: - tiers = [tier_ats] - else: - tiers = ["T1", "T2", "OTCE"] + tiers = [tier_ats] if tier_ats else ["T1", "T2", "OTCE"] df_ats = pd.DataFrame() for tier in tiers: diff --git a/openbb_terminal/stocks/dark_pool_shorts/quandl_model.py b/openbb_terminal/stocks/dark_pool_shorts/quandl_model.py index 291ba6c1eb9..3fe6fed270a 100644 --- a/openbb_terminal/stocks/dark_pool_shorts/quandl_model.py +++ b/openbb_terminal/stocks/dark_pool_shorts/quandl_model.py @@ -38,10 +38,11 @@ def get_short_interest(symbol: str, nyse: bool = False) -> pd.DataFrame: df = pd.DataFrame() try: - if nyse: - df = quandl.get(f"FINRA/FNYX_{symbol}") - else: - df = quandl.get(f"FINRA/FNSQ_{symbol}") + df = ( + quandl.get(f"FINRA/FNYX_{symbol}") + if nyse + else quandl.get(f"FINRA/FNSQ_{symbol}") + ) except AuthenticationError: console.print("[red]Invalid API Key[/red]\n") diff --git a/openbb_terminal/stocks/dark_pool_shorts/stockgrid_model.py b/openbb_terminal/stocks/dark_pool_shorts/stockgrid_model.py index 840be723f4d..35d40e107a1 100644 --- a/openbb_terminal/stocks/dark_pool_shorts/stockgrid_model.py +++ b/openbb_terminal/stocks/dark_pool_shorts/stockgrid_model.py @@ -46,10 +46,7 @@ def get_dark_pool_short_positions( field = d_fields_endpoints[sortby] - if ascend: - order = "asc" - else: - order = "desc" + order = "asc" if ascend else "desc" link = f"https://stockgridapp.herokuapp.com/get_dark_pool_data?top={field}&minmax={order}" diff --git a/openbb_terminal/stocks/discovery/finnhub_model.py b/openbb_terminal/stocks/discovery/finnhub_model.py index 7bedf5ac60b..e29f522223a 100644 --- a/openbb_terminal/stocks/discovery/finnhub_model.py +++ b/openbb_terminal/stocks/discovery/finnhub_model.py @@ -92,10 +92,11 @@ def get_past_ipo( """ today = datetime.now() - if start_date is None: - start = (today - timedelta(days=num_days_behind)).strftime("%Y-%m-%d") - else: - start = start_date + start = ( + (today - timedelta(days=num_days_behind)).strftime("%Y-%m-%d") + if start_date is None + else start_date + ) df_past_ipo = ( get_ipo_calendar(start, today.strftime("%Y-%m-%d")) @@ -132,10 +133,11 @@ def get_future_ipo( """ today = datetime.now() - if end_date is None: - end = (today + timedelta(days=num_days_ahead)).strftime("%Y-%m-%d") - else: - end = end_date + end = ( + (today + timedelta(days=num_days_ahead)).strftime("%Y-%m-%d") + if end_date is None + else end_date + ) df_future_ipo = ( get_ipo_calendar(today.strftime("%Y-%m-%d"), end) diff --git a/openbb_terminal/stocks/fundamental_analysis/dcf_model.py b/openbb_terminal/stocks/fundamental_analysis/dcf_model.py index 45d94682e51..dacb2d215a9 100644 --- a/openbb_terminal/stocks/fundamental_analysis/dcf_model.py +++ b/openbb_terminal/stocks/fundamental_analysis/dcf_model.py @@ -245,7 +245,7 @@ def get_fama_raw() -> pd.DataFrame: df : pd.DataFrame Fama French data """ - with urlopen( # nosec + with urlopen( # noqa: SIM117 "https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip" ) as url: # Download Zipfile and create pandas DataFrame diff --git a/openbb_terminal/stocks/fundamental_analysis/market_watch_model.py b/openbb_terminal/stocks/fundamental_analysis/market_watch_model.py index 9f752d61648..bec171d5d0b 100644 --- a/openbb_terminal/stocks/fundamental_analysis/market_watch_model.py +++ b/openbb_terminal/stocks/fundamental_analysis/market_watch_model.py @@ -63,10 +63,7 @@ def prepare_df_financials( if statement not in financial_urls: raise ValueError(f"type {statement} is not in {financial_urls.keys()}") - if quarter: - period = "quarter" - else: - period = "annual" + period = "quarter" if quarter else "annual" text_soup_financials = BeautifulSoup( request( diff --git a/openbb_terminal/stocks/fundamental_analysis/marketwatch_model.py b/openbb_terminal/stocks/fundamental_analysis/marketwatch_model.py index f998c837d16..5489e6431fa 100644 --- a/openbb_terminal/stocks/fundamental_analysis/marketwatch_model.py +++ b/openbb_terminal/stocks/fundamental_analysis/marketwatch_model.py @@ -49,23 +49,21 @@ def get_sec_filings(symbol: str) -> pd.DataFrame: a_financials = financials_info.text.split("\n") # If header has been processed and dataframe created ready to populate the SEC information - if b_ready_to_process_info: - if len(a_financials) > 1: - l_financials_info = [a_financials[2]] - l_financials_info.extend(a_financials[5:-1]) - l_financials_info.append(financials_info.a["href"]) - # Append data values to financials - df_financials.loc[len(df_financials.index)] = l_financials_info # type: ignore + if b_ready_to_process_info and len(a_financials) > 1: + l_financials_info = [a_financials[2]] + l_financials_info.extend(a_financials[5:-1]) + l_financials_info.append(financials_info.a["href"]) + # Append data values to financials + df_financials.loc[len(df_financials.index)] = l_financials_info # type: ignore - if "Filing Date" in a_financials: - if len(a_financials) > 1: - l_financials_header = [a_financials[2]] - l_financials_header.extend(a_financials[5:-1]) - l_financials_header.append("Link") + if "Filing Date" in a_financials and len(a_financials) > 1: + l_financials_header = [a_financials[2]] + l_financials_header.extend(a_financials[5:-1]) + l_financials_header.append("Link") - df_financials = pd.DataFrame(columns=l_financials_header) - df_financials.set_index("Filing Date") - b_ready_to_process_info = True + df_financials = pd.DataFrame(columns=l_financials_header) + df_financials.set_index("Filing Date") + b_ready_to_process_info = True # Set Filing Date as index df_financials = df_financials.set_index("Filing Date") # type: ignore diff --git a/openbb_terminal/stocks/insider/businessinsider_view.py b/openbb_terminal/stocks/insider/businessinsider_view.py index 97d3f2cce81..38f5f34c3d7 100644 --- a/openbb_terminal/stocks/insider/businessinsider_view.py +++ b/openbb_terminal/stocks/insider/businessinsider_view.py @@ -76,10 +76,7 @@ def insider_activity( logger.warning("The insider activity on the ticker does not exist") console.print("[red]The insider activity on the ticker does not exist.\n[/red]") else: - if start_date: - df_insider = df_ins[start_date:].copy() # type: ignore - else: - df_insider = df_ins.copy() + df_insider = df_ins[start_date:].copy() if start_date else df_ins.copy() # type: ignore if raw: df_insider.index = pd.to_datetime(df_insider.index).date @@ -148,16 +145,16 @@ def insider_activity( .sum(numeric_only=True) .index ): - if ind in data.index: - ind_dt = ind - else: - ind_dt = get_next_stock_market_days(ind, 1)[0] + ind_dt = ( + ind if ind in data.index else get_next_stock_market_days(ind, 1)[0] + ) n_stock_price = 0 - if interval == "1440min": - n_stock_price = data["Adj Close"][ind_dt] - else: - n_stock_price = data["Close"][ind_dt] + n_stock_price = ( + data["Adj Close"][ind_dt] + if interval == "1440min" + else data["Close"][ind_dt] + ) bar_1 = ax.vlines( x=ind_dt, @@ -181,16 +178,16 @@ def insider_activity( .sum(numeric_only=True) .index ): - if ind in data.index: - ind_dt = ind - else: - ind_dt = get_next_stock_market_days(ind, 1)[0] + ind_dt = ( + ind if ind in data.index else get_next_stock_market_days(ind, 1)[0] + ) n_stock_price = 0 - if interval == "1440min": - n_stock_price = data["Adj Close"][ind_dt] - else: - n_stock_price = data["Close"][ind_dt] + n_stock_price = ( + data["Adj Close"][ind_dt] + if interval == "1440min" + else data["Close"][ind_dt] + ) bar_2 = ax.vlines( x=ind_dt, diff --git a/openbb_terminal/stocks/insider/openinsider_view.py b/openbb_terminal/stocks/insider/openinsider_view.py index b2715607a4c..bc541df7d7f 100644 --- a/openbb_terminal/stocks/insider/openinsider_view.py +++ b/openbb_terminal/stocks/insider/openinsider_view.py @@ -174,10 +174,11 @@ def print_insider_filter( export : str Format to export data """ - if symbol: - link = f"http://openinsider.com/screener?s={symbol}" - else: - link = get_open_insider_link(preset) + link = ( + f"http://openinsider.com/screener?s={symbol}" + if symbol + else get_open_insider_link(preset) + ) if not link: return @@ -252,10 +253,7 @@ def print_insider_filter( console.print(d_trade_types[tradetype]) if export: - if symbol: - cmd = "stats" - else: - cmd = "filter" + cmd = "stats" if symbol else "filter" export_data( export, diff --git a/openbb_terminal/stocks/options/hedge/hedge_controller.py b/openbb_terminal/stocks/options/hedge/hedge_controller.py index 0ccd93d9b1e..85415185782 100644 --- a/openbb_terminal/stocks/options/hedge/hedge_controller.py +++ b/openbb_terminal/stocks/options/hedge/hedge_controller.py @@ -228,11 +228,7 @@ class HedgeController(BaseController): "currency": currency, } - if opt_type == "Call": - side = 1 - else: - # Implies the option type is a put - side = -1 + side = 1 if opt_type == "Call" else -1 date_obj = datetime.strptime(self.expiration, "%Y-%m-%d") days = float((date_obj - datetime.now()).days + 1) diff --git a/openbb_terminal/stocks/options/hedge/hedge_model.py b/openbb_terminal/stocks/options/hedge/hedge_model.py index b50832191f0..9f4302944a5 100644 --- a/openbb_terminal/stocks/options/hedge/hedge_model.py +++ b/openbb_terminal/stocks/options/hedge/hedge_model.py @@ -88,10 +88,9 @@ def calc_hedge( if side == "Call": # Short call position delta_multiplier = -1 - elif side == "Put": - if sign == 1: - # Long put position - delta_multiplier = -1 + elif side == "Put" and sign == 1: + # Long put position + delta_multiplier = -1 options_array = np.array( [[option_a_gamma, option_b_gamma], [option_a_vega, option_b_vega]] diff --git a/openbb_terminal/stocks/options/op_helpers.py b/openbb_terminal/stocks/options/op_helpers.py index 6274779d56d..784eae3affe 100644 --- a/openbb_terminal/stocks/options/op_helpers.py +++ b/openbb_terminal/stocks/options/op_helpers.py @@ -23,15 +23,9 @@ logger = logging.getLogger(__name__) def get_strikes( min_sp: float, max_sp: float, current_price: float ) -> Tuple[float, float]: - if min_sp == -1: - min_strike = 0.75 * current_price - else: - min_strike = min_sp + min_strike = 0.75 * current_price if min_sp == -1 else min_sp - if max_sp == -1: - max_strike = 1.25 * current_price - else: - max_strike = max_sp + max_strike = 1.25 * current_price if max_sp == -1 else max_sp return min_strike, max_strike @@ -309,13 +303,11 @@ def get_greeks( "Vega", "Theta", ] - if show_all: - columns = chain_columns + greek_columns - else: - columns = [ - "Strike", - "Implied Vol", - ] + greek_columns + columns = ( + chain_columns + greek_columns + if show_all + else ["Strike", "Implied Vol"] + greek_columns + ) if show_extra_greeks: additional_columns = ["Rho", "Phi", "Charm", "Vanna", "Vomma"] diff --git a/openbb_terminal/stocks/options/options_controller.py b/openbb_terminal/stocks/options/options_controller.py index 4f21ae699d3..f74f9a0f5ac 100644 --- a/openbb_terminal/stocks/options/options_controller.py +++ b/openbb_terminal/stocks/options/options_controller.py @@ -363,10 +363,11 @@ class OptionsController(BaseController): ) ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: - if ns_parser.min > 0 and ns_parser.max > 0: - pars = {"x_min": ns_parser.min, "x_max": ns_parser.max} - else: - pars = {} + pars = ( + {"x_min": ns_parser.min, "x_max": ns_parser.max} + if ns_parser.min > 0 and ns_parser.max > 0 + else {} + ) calculator_view.view_calculator( strike=ns_parser.strike, diff --git a/openbb_terminal/stocks/options/screen/syncretism_model.py b/openbb_terminal/stocks/options/screen/syncretism_model.py index 4d747d7c90a..676ab00d5ee 100644 --- a/openbb_terminal/stocks/options/screen/syncretism_model.py +++ b/openbb_terminal/stocks/options/screen/syncretism_model.py @@ -72,10 +72,7 @@ def get_historical_greeks( if not chain_id: options = yfinance_model.get_option_chain(symbol, expiry) - if put: - options = options.puts - else: - options = options.calls + options = options.puts if put else options.calls selection = options.loc[options.strike == strike, "contractSymbol"] try: @@ -357,9 +354,8 @@ def check_presets(preset_dict: dict) -> str: except Exception: error += f"{key} : {value} , should be integer\n" - elif key == "order-by": - if value.replace('"', "") not in accepted_orders: - error += f"{key} : {value} not accepted ordering\n" + elif key == "order-by" and value.replace('"', "") not in accepted_orders: + error += f"{key} : {value} not accepted ordering\n" if error: logging.exception(error) return error diff --git a/openbb_terminal/stocks/options/yfinance_model.py b/openbb_terminal/stocks/options/yfinance_model.py index bc46eea1542..1e5bdd251e0 100644 --- a/openbb_terminal/stocks/options/yfinance_model.py +++ b/openbb_terminal/stocks/options/yfinance_model.py @@ -350,10 +350,11 @@ def get_binom( und_vals.append(new) # Binomial tree for option values - if put: - opt_vals = [[max(strike - x, 0) for x in und_vals[-1]]] - else: - opt_vals = [[max(x - strike, 0) for x in und_vals[-1]]] + opt_vals = ( + [[max(strike - x, 0) for x in und_vals[-1]]] + if put + else [[max(x - strike, 0) for x in und_vals[-1]]] + ) j = 2 while len(opt_vals[0]) > 1: diff --git a/openbb_terminal/stocks/options/yfinance_view.py b/openbb_terminal/stocks/options/yfinance_view.py index 874350af18c..bccb2ea30df 100644 --- a/openbb_terminal/stocks/options/yfinance_view.py +++ b/openbb_terminal/stocks/options/yfinance_view.py @@ -258,10 +258,11 @@ def show_parity( if div_dts: last_div = pd.to_datetime(div_dts[-1]) - if len(div_dts) > 3: - avg_div = np.mean(div_info.to_list()[-4:]) - else: - avg_div = np.mean(div_info.to_list()) + avg_div = ( + np.mean(div_info.to_list()[-4:]) + if len(div_dts) > 3 + else np.mean(div_info.to_list()) + ) next_div = last_div + timedelta(days=91) dividends = [] @@ -360,10 +361,11 @@ def risk_neutral_vals( risk: float The risk-free rate for the asset """ - if put: - chain = get_option_chain(symbol, expiry).puts - else: - chain = get_option_chain(symbol, expiry).calls + chain = ( + get_option_chain(symbol, expiry).puts + if put + else get_option_chain(symbol, expiry).calls + ) r_date = datetime.strptime(expiry, "%Y-%m-%d").date() delta = (r_date - date.today()).days diff --git a/openbb_terminal/stocks/quantitative_analysis/beta_model.py b/openbb_terminal/stocks/quantitative_analysis/beta_model.py index dbc07a129be..18d1429124b 100644 --- a/openbb_terminal/stocks/quantitative_analysis/beta_model.py +++ b/openbb_terminal/stocks/quantitative_analysis/beta_model.py @@ -36,13 +36,11 @@ def beta_model( Tuple[pd.Series, pd.Series, float, float] Stock ticker symbols close-to-close returns, Reference ticker symbols close-to-close returns, beta, alpha """ - if data is None: - data = stocks_helper.load(symbol=symbol) - else: - # TODO: When loaded in the stocks menu, the stock df columns are all - # lowercase but when loaded via stocks_helper.load(ticker) they start - # with an uppercase char. This should be consistent. - data = data.rename({"close": "Close"}, axis=1) + data = ( + stocks_helper.load(symbol=symbol) + if data is None + else data.rename({"close": "Close"}, axis=1) + ) if ref_data is None: ref_data = stocks_helper.load( symbol=ref_symbol, diff --git a/openbb_terminal/stocks/screener/screener_controller.py b/openbb_terminal/stocks/screener/screener_controller.py index 30c69bd61af..53b6064b1ce 100644 --- a/openbb_terminal/stocks/screener/screener_controller.py +++ b/openbb_terminal/stocks/screener/screener_controller.py @@ -235,10 +235,11 @@ class ScreenerController(BaseController): parser, other_args, EXPORT_BOTH_RAW_DATA_AND_FIGURES ) if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) self.screen_tickers = yahoofinance_view.historical( preset, ns_parser.limit, @@ -307,10 +308,11 @@ class ScreenerController(BaseController): ) if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) sort_map = screener_helper.finviz_map("overview") self.screen_tickers = finviz_view.screener( @@ -384,10 +386,11 @@ class ScreenerController(BaseController): ) if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) sort_map = screener_helper.finviz_map("valuation") self.screen_tickers = finviz_view.screener( loaded_preset=preset, @@ -460,10 +463,11 @@ class ScreenerController(BaseController): ) if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) sort_map = screener_helper.finviz_map("financial") self.screen_tickers = finviz_view.screener( loaded_preset=preset, @@ -536,10 +540,11 @@ class ScreenerController(BaseController): ) if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) sort_map = screener_helper.finviz_map("ownership") self.screen_tickers = finviz_view.screener( loaded_preset=preset, @@ -613,10 +618,11 @@ class ScreenerController(BaseController): sort_map = screener_helper.finviz_map("performance") if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) self.screen_tickers = finviz_view.screener( loaded_preset=preset, data_type="performance", @@ -687,10 +693,11 @@ class ScreenerController(BaseController): ) if ns_parser: - if self.preset.strip(".ini") in finviz_model.d_signals: - preset = self.preset.strip(".ini") - else: - preset = self.preset + preset = ( + self.preset.strip(".ini") + if self.preset.strip(".ini") in finviz_model.d_signals + else self.preset + ) sort_map = screener_helper.finviz_map("technical") self.screen_tickers = finviz_view.screener( loaded_preset=preset, diff --git a/openbb_terminal/stocks/sector_industry_analysis/stockanalysis_view.py b/openbb_terminal/stocks/sector_industry_analysis/stockanalysis_view.py index 624b3c97125..175a162d94f 100644 --- a/openbb_terminal/stocks/sector_industry_analysis/stockanalysis_view.py +++ b/openbb_terminal/stocks/sector_industry_analysis/stockanalysis_view.py @@ -156,10 +156,7 @@ def display_plots_financials( (df, foundDenomination) = transform_by_denomination(df) - if currency: - denomination = f"[{currency} " - else: - denomination = "[" + denomination = f"[{currency} " if currency else "[" if denomination != "Units": denomination += f"{foundDenomination}]" diff --git a/openbb_terminal/stocks/stocks_controller.py b/openbb_terminal/stocks/stocks_controller.py index dd2bfc10f7c..f11a4386909 100644 --- a/openbb_terminal/stocks/stocks_controller.py +++ b/openbb_terminal/stocks/stocks_controller.py @@ -277,9 +277,8 @@ class StocksController(StockBaseController): dest="exchange", ) - if not self.ticker: - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-t") + if not self.ticker and other_args and "-" not in other_args[0][0]: + other_args.insert(0, "-t") ns_parser = self.parse_known_args_and_warn(parser, other_args) if ns_parser: diff --git a/openbb_terminal/stocks/stocks_helper.py b/openbb_terminal/stocks/stocks_helper.py index 7b67eda210b..5c39d7e8cba 100644 --- a/openbb_terminal/stocks/stocks_helper.py +++ b/openbb_terminal/stocks/stocks_helper.py @@ -381,10 +381,9 @@ def load( df_stock_candidate.index = df_stock_candidate.index.tz_localize(None) - if s_start_dt > start_date: - s_start = pytz.utc.localize(s_start_dt) - else: - s_start = start_date + s_start = ( + pytz.utc.localize(s_start_dt) if s_start_dt > start_date else start_date + ) df_stock_candidate.index.name = "date" @@ -442,10 +441,9 @@ def load( ) s_start_dt = df_stock_candidate.index[0] - if s_start_dt > start_date: - s_start = pytz.utc.localize(s_start_dt) - else: - s_start = start_date + s_start = ( + pytz.utc.localize(s_start_dt) if s_start_dt > start_date else start_date + ) s_interval = f"{interval}min" int_string = "Intraday" @@ -560,10 +558,9 @@ def display_candle( ) data = process_candle(data) - if add_trend: - if (data.index[1] - data.index[0]).total_seconds() >= 86400: - data = find_trendline(data, "OC_High", "high") - data = find_trendline(data, "OC_Low", "low") + if add_trend and (data.index[1] - data.index[0]).total_seconds() >= 86400: + data = find_trendline(data, "OC_High", "high") + data = find_trendline(data, "OC_Low", "low") if not raw: if use_matplotlib: diff --git a/openbb_terminal/stocks/technical_analysis/tradingview_model.py b/openbb_terminal/stocks/technical_analysis/tradingview_model.py index d87db998add..1ee2693dd68 100644 --- a/openbb_terminal/stocks/technical_analysis/tradingview_model.py +++ b/openbb_terminal/stocks/technical_analysis/tradingview_model.py @@ -83,10 +83,9 @@ def get_tradingview_recommendation( return pd.DataFrame() exchange = data["Exchange"] - if interval: - intervals = [interval] - else: - intervals = ["1M", "1W", "1d", "4h", "1h", "15m", "5m", "1m"] + intervals = ( + [interval] if interval else ["1M", "1W", "1d", "4h", "1h", "15m", "5m", "1m"] + ) df_recommendation = pd.DataFrame() index_recommendation = [] diff --git a/openbb_terminal/stocks/tradinghours/tradinghours_controller.py b/openbb_terminal/stocks/tradinghours/tradinghours_controller.py index e7d17b8936b..6831bebaefc 100644 --- a/openbb_terminal/stocks/tradinghours/tradinghours_controller.py +++ b/openbb_terminal/stocks/tradinghours/tradinghours_controller.py @@ -83,13 +83,11 @@ class TradingHoursController(BaseController): self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): - if self.symbol is not None: - if self.symbol_market_open: - exchange_opened = "OPENED" - else: - exchange_opened = "CLOSED" - else: - exchange_opened = "" + exchange_opened = ( + ("OPENED" if self.symbol_market_open else "CLOSED") + if self.symbol is not None + else "" + ) mt = MenuText("stocks/th/") mt.add_cmd("open") diff --git a/openbb_terminal/terminal_controller.py b/openbb_terminal/terminal_controller.py index af8e86cd10e..b01f9157f0c 100644 --- a/openbb_terminal/terminal_controller.py +++ b/openbb_terminal/terminal_controller.py @@ -279,10 +279,11 @@ class TerminalController(BaseController): start = time.time() console.print(f"\n[yellow]{task}[/yellow]\n") - if isinstance(session, PromptSession): - an_input = session.prompt("GUESS / $ ") - else: - an_input = "" + an_input = ( + session.prompt("GUESS / $ ") + if isinstance(session, PromptSession) + else "" + ) time_dif = time.time() - start # When there are multiple paths to same solution @@ -676,10 +677,9 @@ class TerminalController(BaseController): return full_input = " ".join(other_args) - if " " in full_input: - other_args_processed = full_input.split(" ") - else: - other_args_processed = [full_input] + other_args_processed = ( + full_input.split(" ") if " " in full_input else [full_input] + ) self.queue = [] path_routine = "" @@ -730,103 +730,98 @@ class TerminalController(BaseController): if args and "-" not in args[0][0]: args.insert(0, "--file") ns_parser_exe = self.parse_simple_args(parser_exe, args) - if ns_parser_exe: - if ns_parser_exe.path or ns_parser_exe.example: - if ns_parser_exe.example: - path = ( - MISCELLANEOUS_DIRECTORY / "routines" / "routine_example.openbb" - ) - console.print( - "[green]Executing an example, please type `about exe` " - "to learn how to create your own script.[/green]\n" - ) - time.sleep(3) - elif ns_parser_exe.path in self.ROUTINE_CHOICES["--file"]: - path = self.ROUTINE_FILES[ns_parser_exe.path] - else: - path = ns_parser_exe.path + if ns_parser_exe and (ns_parser_exe.path or ns_parser_exe.example): + if ns_parser_exe.example: + path = MISCELLANEOUS_DIRECTORY / "routines" / "routine_example.openbb" + console.print( + "[green]Executing an example, please type `about exe` " + "to learn how to create your own script.[/green]\n" + ) + time.sleep(3) + elif ns_parser_exe.path in self.ROUTINE_CHOICES["--file"]: + path = self.ROUTINE_FILES[ns_parser_exe.path] + else: + path = ns_parser_exe.path - with open(path) as fp: - raw_lines = [ - x for x in fp if (not is_reset(x)) and ("#" not in x) and x - ] - raw_lines = [ - raw_line.strip("\n") - for raw_line in raw_lines - if raw_line.strip("\n") - ] + with open(path) as fp: + raw_lines = [ + x for x in fp if (not is_reset(x)) and ("#" not in x) and x + ] + raw_lines = [ + raw_line.strip("\n") + for raw_line in raw_lines + if raw_line.strip("\n") + ] - lines = list() - for rawline in raw_lines: - templine = rawline + lines = list() + for rawline in raw_lines: + templine = rawline - # Check if dynamic parameter exists in script - if "$ARGV" in rawline: - # Check if user has provided inputs through -i or --input - if ns_parser_exe.routine_args: - for i, arg in enumerate(ns_parser_exe.routine_args): - # Check what is the location of the ARGV to be replaced - if f"$ARGV[{i}]" in templine: - templine = templine.replace(f"$ARGV[{i}]", arg) + # Check if dynamic parameter exists in script + if "$ARGV" in rawline: + # Check if user has provided inputs through -i or --input + if ns_parser_exe.routine_args: + for i, arg in enumerate(ns_parser_exe.routine_args): + # Check what is the location of the ARGV to be replaced + if f"$ARGV[{i}]" in templine: + templine = templine.replace(f"$ARGV[{i}]", arg) - # Check if all ARGV have been removed, otherwise means that there are less inputs - # when running the script than the script expects - if "$ARGV" in templine: - console.print( - "[red]Not enough inputs were provided to fill in dynamic variables. " - "E.g. --input VAR1,VAR2,VAR3[/red]\n" - ) - return - - lines.append(templine) - # The script expects a parameter that the user has not provided - else: + # Check if all ARGV have been removed, otherwise means that there are less inputs + # when running the script than the script expects + if "$ARGV" in templine: console.print( - "[red]The script expects parameters, " - "run the script again with --input defined.[/red]\n" + "[red]Not enough inputs were provided to fill in dynamic variables. " + "E.g. --input VAR1,VAR2,VAR3[/red]\n" ) return - else: + lines.append(templine) - - simulate_argv = f"/{'/'.join([line.rstrip() for line in lines])}" - file_cmds = simulate_argv.replace("//", "/home/").split() - file_cmds = ( - insert_start_slash(file_cmds) if file_cmds else file_cmds - ) - cmds_with_params = " ".join(file_cmds) - self.queue = [ - val - for val in parse_and_split_input( - an_input=cmds_with_params, custom_filters=[] - ) - if val - ] - - if "export" in self.queue[0]: - export_path = self.queue[0].split(" ")[1] - # If the path selected does not start from the user root, give relative location from root - if export_path[0] == "~": - export_path = export_path.replace( - "~", HOME_DIRECTORY.as_posix() - ) - elif export_path[0] != "/": - export_path = os.path.join( - os.path.dirname(os.path.abspath(__file__)), export_path - ) - - # Check if the directory exists - if os.path.isdir(export_path): - console.print( - f"Export data to be saved in the selected folder: '{export_path}'" - ) + # The script expects a parameter that the user has not provided else: - os.makedirs(export_path) console.print( - f"[green]Folder '{export_path}' successfully created.[/green]" + "[red]The script expects parameters, " + "run the script again with --input defined.[/red]\n" ) - obbff.EXPORT_FOLDER_PATH = export_path - self.queue = self.queue[1:] + return + else: + lines.append(templine) + + simulate_argv = f"/{'/'.join([line.rstrip() for line in lines])}" + file_cmds = simulate_argv.replace("//", "/home/").split() + file_cmds = insert_start_slash(file_cmds) if file_cmds else file_cmds + cmds_with_params = " ".join(file_cmds) + self.queue = [ + val + for val in parse_and_split_input( + an_input=cmds_with_params, custom_filters=[] + ) + if val + ] + + if "export" in self.queue[0]: + export_path = self.queue[0].split(" ")[1] + # If the path selected does not start from the user root, give relative location from root + if export_path[0] == "~": + export_path = export_path.replace( + "~", HOME_DIRECTORY.as_posix() + ) + elif export_path[0] != "/": + export_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), export_path + ) + + # Check if the directory exists + if os.path.isdir(export_path): + console.print( + f"Export data to be saved in the selected folder: '{export_path}'" + ) + else: + os.makedirs(export_path) + console.print( + f"[green]Folder '{export_path}' successfully created.[/green]" + ) + obbff.EXPORT_FOLDER_PATH = export_path + self.queue = self.queue[1:] # pylint: disable=global-statement @@ -1073,10 +1068,11 @@ def run_scripts( simulate_argv = f"/{'/'.join([line.rstrip() for line in lines])}" file_cmds = simulate_argv.replace("//", "/home/").split() file_cmds = insert_start_slash(file_cmds) if file_cmds else file_cmds - if export_folder: - file_cmds = [f"export {export_folder}{' '.join(file_cmds)}"] - else: - file_cmds = [" ".join(file_cmds)] + file_cmds = ( + [f"export {export_folder}{' '.join(file_cmds)}"] + if export_folder + else [" ".join(file_cmds)] + ) if not test_mode or verbose: terminal(file_cmds, test_mode=True) @@ -1091,9 +1087,8 @@ def run_scripts( first_cmd = file_cmds[0].split("/")[1] with open( whole_path / f"{stamp_str}_{first_cmd}_output.txt", "w" - ) as output_file: - with contextlib.redirect_stdout(output_file): - terminal(file_cmds, test_mode=True) + ) as output_file, contextlib.redirect_stdout(output_file): + terminal(file_cmds, test_mode=True) else: terminal(file_cmds, test_mode=True) diff --git a/openbb_terminal/terminal_helper.py b/openbb_terminal/terminal_helper.py index 74d831683a0..0408a37635a 100644 --- a/openbb_terminal/terminal_helper.py +++ b/openbb_terminal/terminal_helper.py @@ -158,13 +158,14 @@ def open_openbb_documentation( path = f"/guides/intros/{path}" else: # user didn't pass argument and is in a menu menu = path.split("/")[-2] - if menu in ["ta", "ba", "qa"]: - path = f"/guides/intros/common/{menu}" - else: - path = f"/guides/intros/{path}" + path = ( + f"/guides/intros/common/{menu}" + if menu in ["ta", "ba", "qa"] + else f"/guides/intros/{path}" + ) if command: - if "keys" == command: + if command == "keys": path = "/guides/advanced/api-keys" command = "" elif "settings" in path or "featflags" in path: diff --git a/pyproject.toml b/pyproject.toml index c5e4acb4d14..75e2664a9d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -167,9 +167,9 @@ 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"] +select = ["E", "W", "F", "Q", "S", "UP", "I", "PLC", "PLE", "PLR", "PLW", "SIM"] # These ignores should be seen as temporary solutions to problems that will NEED fixed -ignore = ["S105", "S106", "S107", "S110", "PLR2004", "PLR0911", "PLR0913", "PLR0912", "PLR0915"] +ignore = ["S105", "S106", "S107", "S110", "PLR2004", "PLR0911", "PLR0913", "PLR0912", "PLR0915", "SIM114", "SIM105", "SIM117"] [tool.ruff.per-file-ignores] "tests/*" = ["S101"] diff --git a/tests/helpers/tools.py b/tests/helpers/tools.py index 3de53b5a962..33304fddb80 100644 --- a/tests/helpers/tools.py +++ b/tests/helpers/tools.py @@ -39,7 +39,7 @@ def parameterize_from_file(test_namespace: str, parameter_file: str) -> Callable idlist.append(scenario) argnames = [] tempvalues = [] - for argname in parameter_data[test_namespace][scenario].keys(): + for argname in parameter_data[test_namespace][scenario]: argnames.append(argname) tempvalues.append(parameter_data[test_namespace][scenario][argname]) argvalues.append(tempvalues) diff --git a/tests/openbb_terminal/session/test_local_model.py b/tests/openbb_terminal/session/test_local_model.py index 4dfec207a3f..b57eac6937b 100644 --- a/tests/openbb_terminal/session/test_local_model.py +++ b/tests/openbb_terminal/session/test_local_model.py @@ -185,7 +185,7 @@ def test_apply_configs_sync(sync: str): assert obbff.TIMEZONE == "America/New_York" assert cfg_plot.PLOT_DPI == 100 assert cfg_plot.PLOT_HEIGHT_PERCENTAGE == 50.0 - assert paths.USER_DATA_DIRECTORY == Path("user_home/OpenBBUserData") + assert Path("user_home/OpenBBUserData") == paths.USER_DATA_DIRECTORY assert cfg.API_KEY_ALPHAVANTAGE == "REPLACE_ME" assert cfg.API_FRED_KEY == "REPLACE_ME" else: @@ -194,7 +194,7 @@ def test_apply_configs_sync(sync: str): assert obbff.TIMEZONE == "Europe/London" assert cfg_plot.PLOT_DPI == 95 assert cfg_plot.PLOT_HEIGHT_PERCENTAGE == 50.5 - assert paths.USER_DATA_DIRECTORY == Path("some/path/to/user/data") + assert Path("some/path/to/user/data") == paths.USER_DATA_DIRECTORY assert cfg.API_KEY_ALPHAVANTAGE == "test_av" assert cfg.API_FRED_KEY == "test_fred" diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 7820199cf70..ce982432747 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -6,7 +6,4 @@ def no_dfs(args: list, kwargs: dict) -> bool: for item in args: if isinstance(item, pd.DataFrame): return False - for item in kwargs.values(): - if isinstance(item, pd.DataFrame): - return False - return True + return all(not isinstance(item, pd.DataFrame) for item in kwargs.values()) diff --git a/website/controller_doc_classes.py b/website/controller_doc_classes.py index 4660097bcdc..01bc74541f5 100644 --- a/website/controller_doc_classes.py +++ b/website/controller_doc_classes.py @@ -325,7 +325,9 @@ class LoadControllersDoc: """Gets all controllers""" for trailmap, module in self._get_modules().items(): for name, obj in getmembers(module): - if name != "TerminalController" and "BaseController" not in name: + if ( # noqa: SIM102 + name != "TerminalController" and "BaseController" not in name + ): # noqa: SIM102 if isclass(obj) and issubclass(obj, BaseController): if trailmap not in self.controller_docs: ctrl = ControllerDoc(obj, trailmap) diff --git a/website/generate_sdk_markdown.py b/website/generate_sdk_markdown.py index 0f625ab8263..fbd374c3343 100644 --- a/website/generate_sdk_markdown.py +++ b/website/generate_sdk_markdown.py @@ -286,9 +286,8 @@ def generate_index_markdown( path = Path() for key in d: if isinstance(d[key], dict): - if path and path.name != key: - if key != "": - markdown += f"\n{'#' * level} {key}\n" + if path and path.name != key and key != "": + markdown += f"\n{'#' * level} {key}\n" markdown = generate_index_markdown(markdown, d[key], level + 1, path) else: markdown += f"- [{key}]({d[key]})\n"