From 8b1ac6c8585c9d0f0fca7b0343043a889279c440 Mon Sep 17 00:00:00 2001 From: DidierRLopes Date: Mon, 12 Dec 2022 19:23:06 -0500 Subject: [PATCH] Add parameter to automatically color a table based on positive and negative numbers (#3603) * automatically color table based on values - parameter added to print_help_text * fix act cmd * disable warning * improve code for coloring + allow row/col select coloring * update timestamp date * cleanup * start implementing tests * ignore branches * pylint disable * pylint * remove tests * remove unused imports * remove .txt files * type ignore Co-authored-by: James Maslek Co-authored-by: Henrique Joaquim --- openbb_terminal/helper_funcs.py | 85 ++++++++++++++++++- .../stocks/fundamental_analysis/fmp_model.py | 2 + .../stocks/fundamental_analysis/fmp_view.py | 1 - tests/openbb_terminal/test_helper_funcs.py | 1 + .../test_print_rich_table.txt | 4 + .../test_print_rich_table[data0].txt | 4 + .../test_print_rich_table[data1].txt | 4 + 7 files changed, 96 insertions(+), 5 deletions(-) create mode 100644 tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table.txt create mode 100644 tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data0].txt create mode 100644 tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data1].txt diff --git a/openbb_terminal/helper_funcs.py b/openbb_terminal/helper_funcs.py index e0e70f70beb..1d1d4bda75b 100644 --- a/openbb_terminal/helper_funcs.py +++ b/openbb_terminal/helper_funcs.py @@ -12,8 +12,8 @@ from datetime import date as d import types from collections.abc import Iterable import os -import random import re +import random import sys from difflib import SequenceMatcher import webbrowser @@ -67,6 +67,8 @@ MENU_RESET = 2 command_location = "" +# pylint: disable=R0912 + # pylint: disable=global-statement def set_command_location(cmd_loc: str): """Set command location. @@ -218,6 +220,37 @@ def similar(a: str, b: str) -> float: return SequenceMatcher(None, a, b).ratio() +def return_colored_value(value: str): + """Return the string value with green, yellow, red or white color based on + whether the number is positive, negative, zero or other, respectively. + + Parameters + ---------- + value: str + string to be checked + + Returns + ------- + value: str + string with color based on value of number if it exists + """ + values = re.findall(r"[-+]?(?:\d*\.\d+|\d+)", value) + + # Finds exactly 1 number in the string + if len(values) == 1: + if float(values[0]) > 0: + return f"[green]{value}[/green]" + + if float(values[0]) < 0: + return f"[red]{value}[/red]" + + if float(values[0]) == 0: + return f"[yellow]{value}[/yellow]" + + return f"{value}" + + +# pylint: disable=too-many-arguments def print_rich_table( df: pd.DataFrame, show_index: bool = False, @@ -226,6 +259,9 @@ def print_rich_table( headers: Union[List[str], pd.Index] = None, floatfmt: Union[str, List[str]] = ".2f", show_header: bool = True, + automatic_coloring: bool = False, + columns_to_auto_color: List[str] = None, + rows_to_auto_color: List[str] = None, ): """Prepare a table from df in rich. @@ -245,10 +281,33 @@ def print_rich_table( Float number formatting specs as string or list of strings. Defaults to ".2f" show_header: bool Whether to show the header row. + automatic_coloring: bool + Automatically color a table based on positive and negative values + columns_to_auto_color: List[str] + Columns to automatically color + rows_to_auto_color: List[str] + Rows to automatically color """ if obbff.USE_TABULATE_DF: table = Table(title=title, show_lines=True, show_header=show_header) + if obbff.USE_COLOR and automatic_coloring: + if columns_to_auto_color: + for col in columns_to_auto_color: + # checks whether column exists + if col in df.columns: + df[col] = df[col].apply(lambda x: return_colored_value(str(x))) + if rows_to_auto_color: + for row in rows_to_auto_color: + # checks whether row exists + if row in df.index: + df.loc[row] = df.loc[row].apply( + lambda x: return_colored_value(str(x)) + ) + + if columns_to_auto_color is None and rows_to_auto_color is None: + df = df.applymap(lambda x: return_colored_value(str(x))) + if show_index: table.add_column(index_name) @@ -277,8 +336,8 @@ def print_rich_table( for idx, values in zip(df.index.tolist(), df.values.tolist()): # remove hour/min/sec from timestamp index - Format: YYYY-MM-DD # make better - row = [str(idx)] if show_index else [] - row += [ + row_idx = [str(idx)] if show_index else [] + row_idx += [ str(x) if not isinstance(x, float) and not isinstance(x, np.float64) else ( @@ -290,9 +349,27 @@ def print_rich_table( ) for idx, x in enumerate(values) ] - table.add_row(*row) + table.add_row(*row_idx) console.print(table) else: + + if obbff.USE_COLOR and automatic_coloring: + if columns_to_auto_color: + for col in columns_to_auto_color: + # checks whether column exists + if col in df.columns: + df[col] = df[col].apply(lambda x: return_colored_value(str(x))) + if rows_to_auto_color: + for row in rows_to_auto_color: + # checks whether row exists + if row in df.index: + df.loc[row] = df.loc[row].apply( + lambda x: return_colored_value(str(x)) + ) + + if columns_to_auto_color is None and rows_to_auto_color is None: + df = df.applymap(lambda x: return_colored_value(str(x))) + console.print(df.to_string(col_space=0)) diff --git a/openbb_terminal/stocks/fundamental_analysis/fmp_model.py b/openbb_terminal/stocks/fundamental_analysis/fmp_model.py index 3cad2cc0016..3b653b28356 100644 --- a/openbb_terminal/stocks/fundamental_analysis/fmp_model.py +++ b/openbb_terminal/stocks/fundamental_analysis/fmp_model.py @@ -535,6 +535,8 @@ def get_financial_growth( ) df_fa = clean_metrics_df(df_fa, num=limit) + + df_fa = df_fa[df_fa.columns[::-1]] # Invalid API Keys except ValueError as e: console.print(e) diff --git a/openbb_terminal/stocks/fundamental_analysis/fmp_view.py b/openbb_terminal/stocks/fundamental_analysis/fmp_view.py index 9644213ff50..341e794fe6e 100644 --- a/openbb_terminal/stocks/fundamental_analysis/fmp_view.py +++ b/openbb_terminal/stocks/fundamental_analysis/fmp_view.py @@ -512,7 +512,6 @@ def display_financial_statement_growth( growth = fmp_model.get_financial_growth(symbol, limit, quarterly) if not growth.empty: - growth = growth[growth.columns[::-1]] print_rich_table( growth, headers=list(growth.columns), diff --git a/tests/openbb_terminal/test_helper_funcs.py b/tests/openbb_terminal/test_helper_funcs.py index 35a34dd66c0..02f3d89e879 100644 --- a/tests/openbb_terminal/test_helper_funcs.py +++ b/tests/openbb_terminal/test_helper_funcs.py @@ -13,6 +13,7 @@ from openbb_terminal.helper_funcs import export_data # pylint: disable=E1111 # pylint: disable=W0621 # pylint: disable=W0613 +# pylint: disable=R0912 @pytest.fixture diff --git a/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table.txt b/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table.txt new file mode 100644 index 00000000000..8426c1cc923 --- /dev/null +++ b/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table.txt @@ -0,0 +1,4 @@ + A B +0 1 4 +1 2 5 +2 3 6 diff --git a/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data0].txt b/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data0].txt new file mode 100644 index 00000000000..8426c1cc923 --- /dev/null +++ b/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data0].txt @@ -0,0 +1,4 @@ + A B +0 1 4 +1 2 5 +2 3 6 diff --git a/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data1].txt b/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data1].txt new file mode 100644 index 00000000000..84450c57c95 --- /dev/null +++ b/tests/openbb_terminal/txt/test_helper_funcs/test_print_rich_table[data1].txt @@ -0,0 +1,4 @@ + A B +0 1 0 sd +1 hello -5 +2 0 6