diff --git a/openbb_terminal/custom/__init__.py b/openbb_terminal/custom/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/openbb_terminal/custom/custom_api.py b/openbb_terminal/custom/custom_api.py deleted file mode 100644 index fc0963cd6d1..00000000000 --- a/openbb_terminal/custom/custom_api.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Custom context API.""" -# flake8: noqa -# pylint: disable=unused-import - -# Context menus -from .custom_view import custom_plot as plot -from .quantitative_analysis import qa_api as qa - -try: - from .prediction_techniques import pred_api as pred -except Exception: - # print("Prediction API is not available.") - pass diff --git a/openbb_terminal/custom/custom_controller.py b/openbb_terminal/custom/custom_controller.py deleted file mode 100644 index b7d92b71305..00000000000 --- a/openbb_terminal/custom/custom_controller.py +++ /dev/null @@ -1,257 +0,0 @@ -"""Custom Data Controller Module""" -__docformat__ = "numpy" - -import argparse -import logging -from pathlib import Path -from typing import List - -import pandas as pd -from prompt_toolkit.completion import NestedCompleter - -from openbb_terminal import feature_flags as obbff -from openbb_terminal.custom import custom_model, custom_view -from openbb_terminal.decorators import log_start_end -from openbb_terminal.helper_funcs import ( - EXPORT_ONLY_FIGURES_ALLOWED, -) -from openbb_terminal.menu import session -from openbb_terminal.parent_classes import BaseController -from openbb_terminal.rich_config import console - -logger = logging.getLogger(__name__) -# pylint:disable=import-outside-toplevel - - -class CustomDataController(BaseController): - """Alternative Controller class""" - - CHOICES_COMMANDS: List[str] = ["load", "plot", "show", "info"] - CHOICES_MENUS: List[str] = ["qa", "pred"] - pandas_plot_choices = [ - "line", - "scatter", - "bar", - "barh", - "hist", - "box", - "kde", - "area", - "pie", - "hexbin", - ] - PATH = "/custom/" - - def __init__(self, queue: List[str] = None): - """Constructor""" - super().__init__(queue) - self.data = pd.DataFrame() - self.file = "" - self.DATA_FILES = [file.name for file in Path("custom_imports").iterdir()] - - if session and obbff.USE_PROMPT_TOOLKIT: - choices: dict = {c: {} for c in self.controller_choices} - choices["load"] = {c: None for c in self.DATA_FILES} - choices["plot"]["-k"] = {c: None for c in self.pandas_plot_choices} - self.choices = choices - - choices["support"] = self.SUPPORT_CHOICES - choices["about"] = self.ABOUT_CHOICES - - self.completer = NestedCompleter.from_nested_dict(choices) - - def update_runtime_choices(self): - if session and obbff.USE_PROMPT_TOOLKIT: - self.choices["plot"] = {c: None for c in self.data.columns} - self.choices["plot"]["-y"] = {c: None for c in self.data.columns} - self.choices["plot"]["-x"] = {c: None for c in self.data.columns} - self.choices["plot"]["--vs"] = {c: None for c in self.data.columns} - self.choices["show"]["-s"] = {c: None for c in self.data.columns} - - self.completer = NestedCompleter.from_nested_dict(self.choices) - - def print_help(self): - """Print help""" - has_data_start = "" if not self.data.empty else "[unvl]" - has_data_end = "" if not self.data.empty else "[/unvl]" - help_text = f"""[cmds] - load load in custom data set[/cmds] - -[param]Current file:[/param] {self.file or None}[cmds]{has_data_start} - - show show portion of loaded data - info show data info (columns and datatypes) - plot plot data from loaded file{has_data_end}[/cmds] -[menu] -> qa quantitative analysis, \t e.g.: decompose, cusum, residuals analysis -> pred prediction techniques \t e.g.: regression, arima, rnn, lstm[/menu] -""" - console.print(text=help_text, menu="Custom") - - @log_start_end(log=logger) - def call_load(self, other_args: List[str]): - """Process load""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="load", - description="Load custom data set into a dataframe", - ) - parser.add_argument( - "-f", - "--file", - choices=self.DATA_FILES, - help="File to load in.", - default="test.csv", - type=str, - ) - - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - file = Path("custom_imports") / ns_parser.file - self.data = custom_model.load(file) - self.data.columns = self.data.columns.map(lambda x: x.lower()) - for col in self.data.columns: - if col in ["date", "time", "timestamp"]: # Could be others? - self.data[col] = pd.to_datetime(self.data[col]) - self.data = self.data.set_index(col) - self.file = ns_parser.file - self.update_runtime_choices() - console.print("") - - @log_start_end(log=logger) - def call_plot(self, other_args: List[str]): - """Process plot command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="plot", - description="Plot 2 columns of loaded data", - ) - parser.add_argument( - "-y", - help="Variable to plot along y", - dest="yvar", - type=str, - choices=list(self.data.columns), - ) - parser.add_argument( - "-x", - "--vs", - help="Variable along x axis", - dest="xvar", - type=str, - choices=list(self.data.columns), - default="", - ) - parser.add_argument( - "-k", - "--kind", - default="line", - help="Type of plot for data", - choices=self.pandas_plot_choices, - ) - if other_args and "-" not in other_args[0][0]: - other_args.insert(0, "-y") - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - if self.data.empty: - logger.error("No data loaded") - console.print("[red]No data loaded.[/red]\n") - return - custom_view.custom_plot( - self.data, - ns_parser.yvar, - ns_parser.xvar, - kind=ns_parser.kind, - export=ns_parser.export, - ) - console.print("") - - @log_start_end(log=logger) - def call_show(self, other_args: List[str]): - """Process head command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="show", - description="Show loaded dataframe", - ) - parser.add_argument( - "-s", "--sortcol", nargs="+", type=str, dest="sortcol", default="" - ) - parser.add_argument( - "-a", "--ascend", action="store_true", default=False, dest="ascend" - ) - ns_parser = self.parse_known_args_and_warn(parser, other_args, limit=5) - if ns_parser: - if self.data.empty: - logger.error("No data loaded") - console.print("[red]No data loaded.[/red]\n") - return - if ns_parser.sortcol: - sort_column = " ".join(ns_parser.sortcol) - if sort_column not in self.data.columns: - logger.warning( - "%s is not a valid column. Showing without sorting", sort_column - ) - console.print( - f"[red]{sort_column} not a valid column. Showing without sorting.\n[/red]" - ) - else: - console.print( - self.data.sort_values( - by=sort_column, ascending=ns_parser.ascend - ).head(ns_parser.limit) - ) - console.print() - return - - console.print(self.data.head(ns_parser.limit)) - console.print() - - @log_start_end(log=logger) - def call_info(self, other_args: List[str]): - """Process info command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="info", - description="Show information of custom data.", - ) - - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - if self.data.empty: - logger.error("No data loaded.") - console.print("[red]No data loaded.[/red]\n") - return - console.print(self.data.info()) - console.print() - - @log_start_end(log=logger) - def call_qa(self, _): - """Process qa command""" - from openbb_terminal.custom.quantitative_analysis import qa_controller - - self.queue = self.load_class( - qa_controller.QaController, - custom_df=self.data, - file=self.file, - queue=self.queue, - ) - - @log_start_end(log=logger) - def call_pred(self, _): - """Process pred command""" - if obbff.ENABLE_PREDICT: - from openbb_terminal.custom.prediction_techniques import pred_controller - - self.queue = self.load_class( - pred_controller.PredictionTechniquesController, - self.data, - self.file, - self.queue, - ) diff --git a/openbb_terminal/custom/custom_model.py b/openbb_terminal/custom/custom_model.py deleted file mode 100644 index 9c3ee0e11de..00000000000 --- a/openbb_terminal/custom/custom_model.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Custom Controller Model""" -__docformat__ = "numpy" - -import logging -from pathlib import Path - -import pandas as pd - -from openbb_terminal.decorators import log_start_end - -logger = logging.getLogger(__name__) - - -@log_start_end(log=logger) -def load(file: str) -> pd.DataFrame: - """Load custom file into dataframe. Currently will work with csv - - Parameters - ---------- - file: str - Path to file - - Returns - ------- - pd.DataFrame: - Dataframe with custom data - """ - if not Path(file).exists(): - return pd.DataFrame() - file_type = Path(file).suffix - # TODO More data types - if file_type != ".csv": - return pd.DataFrame() - return pd.read_csv(file) diff --git a/openbb_terminal/custom/custom_view.py b/openbb_terminal/custom/custom_view.py deleted file mode 100644 index 183fbfd2bd2..00000000000 --- a/openbb_terminal/custom/custom_view.py +++ /dev/null @@ -1,63 +0,0 @@ -"""Custom Controller View""" -__docformat__ = "numpy" - -import logging -import os -from typing import List, Optional - -import matplotlib.pyplot as plt -import pandas as pd - -from openbb_terminal.config_plot import PLOT_DPI -from openbb_terminal.decorators import log_start_end -from openbb_terminal.helper_funcs import export_data, plot_autoscale -from openbb_terminal.config_terminal import theme - -logger = logging.getLogger(__name__) - - -@log_start_end(log=logger) -def custom_plot( - data: pd.DataFrame, - y_col: str, - x_col: str = "", - kind: str = "line", - export: str = "", - external_axes: Optional[List[plt.Axes]] = None, -): - """Plot custom data - - Parameters - ---------- - data: pd.DataFrame - Dataframe of custom data - y_col: str - Column for y data - x_col: str - Column for x data. Uses index if not supplied. - kind : str - Kind of plot to pass to pandas plot function - export: str - Format to export image - external_axes: Optional[List[plt.Axes]]: - External axes for plot - """ - if external_axes is None: - _, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) - else: - ax = external_axes[0] - - if x_col: - data.plot(x=x_col, y=y_col, kind=kind, ax=ax) - else: - data.reset_index().plot(x=data.index.name, y=y_col, kind=kind, ax=ax) - - if kind in ["scatter", "line"]: - theme.style_primary_axis(ax) - theme.visualize_output() - - export_data( - export, - os.path.dirname(os.path.abspath(__file__)), - "custom_plot", - ) diff --git a/openbb_terminal/custom/prediction_techniques/__init__.py b/openbb_terminal/custom/prediction_techniques/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/openbb_terminal/custom/prediction_techniques/pred_api.py b/openbb_terminal/custom/prediction_techniques/pred_api.py deleted file mode 100644 index ea1d2fe6402..00000000000 --- a/openbb_terminal/custom/prediction_techniques/pred_api.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Pred context API.""" - -# flake8: noqa -# pylint: disable=unused-import - -# Menu commands -from openbb_terminal.common.prediction_techniques.ets_view import ( - display_exponential_smoothing as ets, -) -from openbb_terminal.common.prediction_techniques.knn_view import ( - display_k_nearest_neighbors as knn, -) -from openbb_terminal.common.prediction_techniques.regression_view import ( - display_regression as regression, -) -from openbb_terminal.common.prediction_techniques.arima_view import ( - display_arima as arima, -) -from openbb_terminal.common.prediction_techniques.neural_networks_view import ( - display_mlp as mlp, -) -from openbb_terminal.common.prediction_techniques.neural_networks_view import ( - display_rnn as rnn, -) -from openbb_terminal.common.prediction_techniques.neural_networks_view import ( - display_lstm as lstm, -) -from openbb_terminal.common.prediction_techniques.neural_networks_view import ( - display_conv1d as conv1d, -) -from openbb_terminal.common.prediction_techniques.mc_view import ( - display_mc_forecast as mc, -) diff --git a/openbb_terminal/custom/prediction_techniques/pred_controller.py b/openbb_terminal/custom/prediction_techniques/pred_controller.py deleted file mode 100644 index 132a21975c5..00000000000 --- a/openbb_terminal/custom/prediction_techniques/pred_controller.py +++ /dev/null @@ -1,745 +0,0 @@ -""" Custom Prediction Controller """ -__docformat__ = "numpy" - -import argparse -import logging -from pathlib import Path -from typing import List - -import pandas as pd -from prompt_toolkit.completion import NestedCompleter - -from openbb_terminal import feature_flags as obbff -from openbb_terminal.common.prediction_techniques import ( - arima_model, - arima_view, - ets_model, - ets_view, - knn_view, - mc_model, - mc_view, - neural_networks_view, - pred_helper, - regression_view, -) -from openbb_terminal.custom import custom_model -from openbb_terminal.decorators import log_start_end -from openbb_terminal.helper_funcs import ( - EXPORT_ONLY_FIGURES_ALLOWED, - check_positive, - get_next_stock_market_days, - valid_date, -) -from openbb_terminal.menu import session -from openbb_terminal.parent_classes import BaseController -from openbb_terminal.rich_config import console -from openbb_terminal.stocks import stocks_helper - -logger = logging.getLogger(__name__) - - -class PredictionTechniquesController(BaseController): - """Prediction Techniques Controller class""" - - CHOICES_COMMANDS = [ - "load", - "pick", - "ets", - "knn", - "regression", - "arima", - "mlp", - "rnn", - "lstm", - "conv1d", - "mc", - ] - - PATH = "/custom/pred/" - - def __init__( - self, - custom_df: pd.DataFrame, - file: str, - queue: List[str] = None, - ): - """Constructor""" - super().__init__(queue) - self.DATA_FILES = [file.name for file in Path("custom_imports").iterdir()] - - self.df = custom_df - self.ticker = file - self.file = file - self.target = custom_df.columns[2] - - if session and obbff.USE_PROMPT_TOOLKIT: - choices: dict = {c: {} for c in self.controller_choices} - choices["pick"] = {c: None for c in self.df.columns} - choices["load"]["-r"] = {c: {} for c in stocks_helper.INTERVALS} - choices["pick"] = {c: {} for c in self.df.columns} - choices["ets"]["-t"] = {c: {} for c in ets_model.TRENDS} - choices["ets"]["-s"] = {c: {} for c in ets_model.SEASONS} - choices["arima"]["-i"] = {c: {} for c in arima_model.ICS} - choices["mc"]["--dist"] = {c: {} for c in mc_model.DISTRIBUTIONS} - self.choices = choices - - choices["support"] = self.SUPPORT_CHOICES - choices["about"] = self.ABOUT_CHOICES - - self.completer = NestedCompleter.from_nested_dict(choices) - - def print_help(self): - """Print help""" - help_text = f"""[cmds] - load load new ticker - pick pick new target variable[/cmds] - -[param]File: [/param]{self.file} -[param]Target Column: [/param]{self.target} - -[info]Models:[/info][cmds] - ets exponential smoothing (e.g. Holt-Winters) - knn k-Nearest Neighbors - regression polynomial regression - arima autoregressive integrated moving average - mlp MultiLayer Perceptron - rnn Recurrent Neural Network - lstm Long-Short Term Memory - conv1d 1D Convolutional Neural Network - mc Monte-Carlo simulations[/cmds] - """ - console.print(text=help_text, menu="Custom - Prediction Techniques") - - def custom_reset(self): - """Class specific component of reset command""" - if self.ticker: - return ["custom", f"load {self.file}", "pred"] - return [] - - def update_runtime_choices(self): - """Add new columns to pick command""" - if session and obbff.USE_PROMPT_TOOLKIT: - self.choices["pick"] = {c: None for c in list(self.df.columns)} - self.completer = NestedCompleter.from_nested_dict(self.choices) - - @log_start_end(log=logger) - def call_load(self, other_args: List[str]): - """Process load""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="load", - description="Load custom data set into a dataframe", - ) - parser.add_argument( - "-f", - "--file", - choices=self.DATA_FILES, - help="File to load in.", - default="test.csv", - type=str, - ) - - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - file = Path("custom_imports") / ns_parser.file - self.df = custom_model.load(file) - self.df.columns = self.df.columns.map(lambda x: x.lower()) - for col in self.df.columns: - if col in ["date", "time", "timestamp"]: # Could be others? - self.df[col] = pd.to_datetime(self.df[col]) - self.df = self.df.set_index(col) - self.file = ns_parser.file - self.update_runtime_choices() - console.print("") - - @log_start_end(log=logger) - def call_pick(self, other_args: List[str]): - """Process pick command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="pick", - description=""" - Change target variable - """, - ) - parser.add_argument( - "-t", - "--target", - dest="target", - choices=list(self.df.columns), - help="Select variable to analyze", - ) - if other_args and "-t" not in other_args and "-h" not in other_args: - other_args.insert(0, "-t") - - ns_parser = self.parse_known_args_and_warn( - parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - self.target = ns_parser.target - console.print("") - - @log_start_end(log=logger) - def call_ets(self, other_args: List[str]): - """Process ets command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="ets", - description=""" - Exponential Smoothing, see https://otexts.com/fpp2/taxonomy.html - - Trend='N', Seasonal='N': Simple Exponential Smoothing - Trend='N', Seasonal='A': Exponential Smoothing - Trend='N', Seasonal='M': Exponential Smoothing - Trend='A', Seasonal='N': Holt’s linear method - Trend='A', Seasonal='A': Additive Holt-Winters’ method - Trend='A', Seasonal='M': Multiplicative Holt-Winters’ method - Trend='Ad', Seasonal='N': Additive damped trend method - Trend='Ad', Seasonal='A': Exponential Smoothing - Trend='Ad', Seasonal='M': Holt-Winters’ damped method - Trend component: N: None, A: Additive, Ad: Additive Damped - Seasonality component: N: None, A: Additive, M: Multiplicative - """, - ) - parser.add_argument( - "-d", - "--days", - action="store", - dest="n_days", - type=check_positive, - default=5, - help="prediction days.", - ) - parser.add_argument( - "-t", - "--trend", - action="store", - dest="trend", - choices=ets_model.TRENDS, - default="N", - help="Trend component: N: None, A: Additive, Ad: Additive Damped.", - ) - parser.add_argument( - "-s", - "--seasonal", - action="store", - dest="seasonal", - choices=ets_model.SEASONS, - default="N", - help="Seasonality component: N: None, A: Additive, M: Multiplicative.", - ) - parser.add_argument( - "-p", - "--periods", - action="store", - dest="seasonal_periods", - type=check_positive, - default=5, - help="Seasonal periods.", - ) - parser.add_argument( - "-e", - "--end", - action="store", - type=valid_date, - dest="s_end_date", - default=None, - help="The end date (format YYYY-MM-DD) to select - Backtesting", - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - - if ns_parser.s_end_date: - - if ns_parser.s_end_date < self.df.index[0]: - console.print( - "Backtesting not allowed, since End Date is older than Start Date of historical data\n" - ) - - if ( - ns_parser.s_end_date - < get_next_stock_market_days( - last_stock_day=self.df.index[0], - n_next_days=5 + ns_parser.n_days, - )[-1] - ): - console.print( - "Backtesting not allowed, since End Date is too close to Start Date to train model\n" - ) - - ets_view.display_exponential_smoothing( - dataset=self.ticker, - data=self.df[self.target], - n_predict=ns_parser.n_days, - trend=ns_parser.trend, - seasonal=ns_parser.seasonal, - seasonal_periods=ns_parser.seasonal_periods, - end_date=ns_parser.s_end_date, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_knn(self, other_args: List[str]): - """Process knn command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="knn", - description=""" - K nearest neighbors is a simple algorithm that stores all - available cases and predict the numerical target based on a similarity measure - (e.g. distance functions). - """, - ) - parser.add_argument( - "-i", - "--input", - action="store", - dest="n_inputs", - type=check_positive, - default=40, - help="number of days to use as input for prediction.", - ) - parser.add_argument( - "-d", - "--days", - action="store", - dest="n_days", - type=check_positive, - default=5, - help="prediction days.", - ) - parser.add_argument( - "-j", - "--jumps", - action="store", - dest="n_jumps", - type=check_positive, - default=1, - help="number of jumps in training data.", - ) - parser.add_argument( - "-n", - "--neighbors", - action="store", - dest="n_neighbors", - type=check_positive, - default=20, - help="number of neighbors to use on the algorithm.", - ) - parser.add_argument( - "-e", - "--end", - action="store", - type=valid_date, - dest="s_end_date", - default=None, - help="The end date (format YYYY-MM-DD) to select for testing", - ) - parser.add_argument( - "-t", - "--test_size", - default=0.2, - dest="valid_split", - type=float, - help="Percentage of data to validate in sample", - ) - parser.add_argument( - "--no_shuffle", - action="store_false", - dest="no_shuffle", - default=True, - help="Specify if shuffling validation inputs.", - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - knn_view.display_k_nearest_neighbors( - dataset=self.ticker, - data=self.df[self.target], - n_neighbors=ns_parser.n_neighbors, - n_input_days=ns_parser.n_inputs, - n_predict_days=ns_parser.n_days, - test_size=ns_parser.valid_split, - end_date=ns_parser.s_end_date, - no_shuffle=ns_parser.no_shuffle, - ) - - @log_start_end(log=logger) - def call_regression(self, other_args: List[str]): - """Process linear command""" - parser = argparse.ArgumentParser( - add_help=False, - prog="regression", - description=""" - Regression attempts to model the relationship between - two variables by fitting a linear/quadratic/cubic/other equation to - observed data. One variable is considered to be an explanatory variable, - and the other is considered to be a dependent variable. - """, - ) - - parser.add_argument( - "-i", - "--input", - action="store", - dest="n_inputs", - type=check_positive, - default=40, - help="number of days to use for prediction.", - ) - parser.add_argument( - "-d", - "--days", - action="store", - dest="n_days", - type=check_positive, - default=5, - help="prediction days.", - ) - parser.add_argument( - "-j", - "--jumps", - action="store", - dest="n_jumps", - type=check_positive, - default=1, - help="number of jumps in training data.", - ) - parser.add_argument( - "-e", - "--end", - action="store", - type=valid_date, - dest="s_end_date", - default=None, - help="The end date (format YYYY-MM-DD) to select - Backtesting", - ) - parser.add_argument( - "-p", - "--polynomial", - action="store", - dest="n_polynomial", - type=check_positive, - default=1, - help="polynomial associated with regression.", - ) - if ( - other_args - and "-h" not in other_args - and ("-p" not in other_args or "--polynomial" not in other_args) - ): - other_args.insert(0, "-p") - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - # BACKTESTING CHECK - if ns_parser.s_end_date: - if ns_parser.s_end_date < self.df.index[0]: - console.print( - "Backtesting not allowed, since End Date is older than Start Date of historical data\n" - ) - - if ( - ns_parser.s_end_date - < get_next_stock_market_days( - last_stock_day=self.df.index[0], - n_next_days=5 + ns_parser.n_days, - )[-1] - ): - console.print( - "Backtesting not allowed, since End Date is too close to Start Date to train model\n" - ) - - regression_view.display_regression( - dataset=self.ticker, - values=self.df[self.target], - poly_order=ns_parser.n_polynomial, - n_input=ns_parser.n_inputs, - n_predict=ns_parser.n_days, - n_jumps=ns_parser.n_jumps, - end_date=ns_parser.s_end_date, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_arima(self, other_args: List[str]): - """Process arima command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="arima", - description=""" - In statistics and econometrics, and in particular in time series analysis, an - autoregressive integrated moving average (ARIMA) model is a generalization of an - autoregressive moving average (ARMA) model. Both of these models are fitted to time - series data either to better understand the data or to predict future points in the - series (forecasting). ARIMA(p,d,q) where parameters p, d, and q are non-negative - integers, p is the order (number of time lags) of the autoregressive model, d is the - degree of differencing (the number of times the data have had past values subtracted), - and q is the order of the moving-average model. - """, - ) - parser.add_argument( - "-d", - "--days", - action="store", - dest="n_days", - type=check_positive, - default=5, - help="prediction days.", - ) - parser.add_argument( - "-i", - "--ic", - action="store", - dest="s_ic", - type=str, - default="aic", - choices=arima_model.ICS, - help="information criteria.", - ) - parser.add_argument( - "-s", - "--seasonal", - action="store_true", - default=False, - dest="b_seasonal", - help="Use weekly seasonal data.", - ) - parser.add_argument( - "-o", - "--order", - action="store", - dest="s_order", - default="", - type=str, - help="arima model order (p,d,q) in format: p,d,q.", - ) - parser.add_argument( - "-r", - "--results", - action="store_true", - dest="b_results", - default=False, - help="results about ARIMA summary flag.", - ) - parser.add_argument( - "-e", - "--end", - action="store", - type=valid_date, - dest="s_end_date", - default=None, - help="The end date (format YYYY-MM-DD) to select - Backtesting", - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - # BACKTESTING CHECK - if ns_parser.s_end_date: - - if ns_parser.s_end_date < self.df.index[0]: - console.print( - "Backtesting not allowed, since End Date is older than Start Date of historical data\n" - ) - - if ( - ns_parser.s_end_date - < get_next_stock_market_days( - last_stock_day=self.df.index[0], - n_next_days=5 + ns_parser.n_days, - )[-1] - ): - console.print( - "Backtesting not allowed, since End Date is too close to Start Date to train model\n" - ) - - arima_view.display_arima( - dataset=self.ticker, - values=self.df[self.target], - arima_order=ns_parser.s_order, - n_predict=ns_parser.n_days, - seasonal=ns_parser.b_seasonal, - ic=ns_parser.s_ic, - results=ns_parser.b_results, - end_date=ns_parser.s_end_date, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_mlp(self, other_args: List[str]): - """Process mlp command""" - try: - ns_parser = pred_helper.parse_args( - prog="mlp", - description="""Multi-Layered-Perceptron. """, - other_args=other_args, - ) - if ns_parser: - neural_networks_view.display_mlp( - dataset=self.ticker, - data=self.df[self.target], - n_input_days=ns_parser.n_inputs, - n_predict_days=ns_parser.n_days, - learning_rate=ns_parser.lr, - epochs=ns_parser.n_epochs, - batch_size=ns_parser.n_batch_size, - test_size=ns_parser.valid_split, - n_loops=ns_parser.n_loops, - no_shuffle=ns_parser.no_shuffle, - ) - except Exception as e: - logger.exception(str(e)) - console.print(e, "\n") - - finally: - pred_helper.restore_env() - - @log_start_end(log=logger) - def call_rnn(self, other_args: List[str]): - """Process rnn command""" - try: - ns_parser = pred_helper.parse_args( - prog="rnn", - description="""Recurrent Neural Network. """, - other_args=other_args, - ) - if ns_parser: - neural_networks_view.display_rnn( - dataset=self.ticker, - data=self.df[self.target], - n_input_days=ns_parser.n_inputs, - n_predict_days=ns_parser.n_days, - learning_rate=ns_parser.lr, - epochs=ns_parser.n_epochs, - batch_size=ns_parser.n_batch_size, - test_size=ns_parser.valid_split, - n_loops=ns_parser.n_loops, - no_shuffle=ns_parser.no_shuffle, - ) - - except Exception as e: - logger.exception(str(e)) - console.print(e, "\n") - - finally: - pred_helper.restore_env() - - @log_start_end(log=logger) - def call_lstm(self, other_args: List[str]): - """Process lstm command""" - try: - ns_parser = pred_helper.parse_args( - prog="lstm", - description="""Long-Short Term Memory. """, - other_args=other_args, - ) - if ns_parser: - neural_networks_view.display_lstm( - dataset=self.ticker, - data=self.df[self.target], - n_input_days=ns_parser.n_inputs, - n_predict_days=ns_parser.n_days, - learning_rate=ns_parser.lr, - epochs=ns_parser.n_epochs, - batch_size=ns_parser.n_batch_size, - test_size=ns_parser.valid_split, - n_loops=ns_parser.n_loops, - no_shuffle=ns_parser.no_shuffle, - ) - - except Exception as e: - logger.exception(str(e)) - console.print(e, "\n") - - finally: - pred_helper.restore_env() - - @log_start_end(log=logger) - def call_conv1d(self, other_args: List[str]): - """Process conv1d command""" - try: - ns_parser = pred_helper.parse_args( - prog="conv1d", - description="""1D CNN.""", - other_args=other_args, - ) - if ns_parser: - neural_networks_view.display_conv1d( - dataset=self.ticker, - data=self.df[self.target], - n_input_days=ns_parser.n_inputs, - n_predict_days=ns_parser.n_days, - learning_rate=ns_parser.lr, - epochs=ns_parser.n_epochs, - batch_size=ns_parser.n_batch_size, - test_size=ns_parser.valid_split, - n_loops=ns_parser.n_loops, - no_shuffle=ns_parser.no_shuffle, - ) - - except Exception as e: - logger.exception(str(e)) - console.print(e, "\n") - - finally: - pred_helper.restore_env() - - @log_start_end(log=logger) - def call_mc(self, other_args: List[str]): - """Process mc command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="mc", - description=""" - Perform Monte Carlo forecasting - """, - ) - parser.add_argument( - "-d", - "--days", - help="Days to predict", - dest="n_days", - type=check_positive, - default=30, - ) - parser.add_argument( - "-n", - "--num", - help="Number of simulations to perform", - dest="n_sims", - default=100, - type=check_positive, - ) - parser.add_argument( - "--dist", - choices=mc_model.DISTRIBUTIONS, - default="lognormal", - dest="dist", - help="Whether to model returns or log returns", - ) - - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - if self.target != "AdjClose": - console.print("MC Prediction designed for AdjClose prices\n") - - mc_view.display_mc_forecast( - data=self.df[self.target], - n_future=ns_parser.n_days, - n_sims=ns_parser.n_sims, - use_log=ns_parser.dist == "lognormal", - export=ns_parser.export, - ) diff --git a/openbb_terminal/custom/quantitative_analysis/__init__.py b/openbb_terminal/custom/quantitative_analysis/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/openbb_terminal/custom/quantitative_analysis/qa_api.py b/openbb_terminal/custom/quantitative_analysis/qa_api.py deleted file mode 100644 index 279de7ee053..00000000000 --- a/openbb_terminal/custom/quantitative_analysis/qa_api.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Pred context API.""" - -# flake8: noqa -# pylint: disable=unused-import - -# Menu commands -from openbb_terminal.common.quantitative_analysis.qa_view import display_raw as raw -from openbb_terminal.common.quantitative_analysis.qa_view import ( - display_summary as summary, -) -from openbb_terminal.common.quantitative_analysis.qa_view import display_line as line -from openbb_terminal.common.quantitative_analysis.qa_view import display_hist as hist -from openbb_terminal.common.quantitative_analysis.qa_view import display_cdf as cdf -from openbb_terminal.common.quantitative_analysis.qa_view import display_bw as bw -from openbb_terminal.common.quantitative_analysis.qa_view import ( - display_seasonal as decompose, -) -from openbb_terminal.common.quantitative_analysis.qa_view import ( - display_cusum as cumsum, -) -from openbb_terminal.common.quantitative_analysis.qa_view import display_acf as acf -from openbb_terminal.common.quantitative_analysis.rolling_view import ( - display_mean_std as rolling, -) -from openbb_terminal.common.quantitative_analysis.rolling_view import ( - display_spread as spread, -) -from openbb_terminal.common.quantitative_analysis.rolling_view import ( - display_quantile as quantile, -) -from openbb_terminal.common.quantitative_analysis.rolling_view import ( - display_skew as skew, -) -from openbb_terminal.common.quantitative_analysis.rolling_view import ( - display_kurtosis as kurtosis, -) -from openbb_terminal.common.quantitative_analysis.qa_view import ( - display_normality as normality, -) -from openbb_terminal.common.quantitative_analysis.qa_view import ( - display_qqplot as qqplot, -) -from openbb_terminal.common.quantitative_analysis.qa_view import ( - display_unitroot as unitroot, -) diff --git a/openbb_terminal/custom/quantitative_analysis/qa_controller.py b/openbb_terminal/custom/quantitative_analysis/qa_controller.py deleted file mode 100644 index e2dc133b515..00000000000 --- a/openbb_terminal/custom/quantitative_analysis/qa_controller.py +++ /dev/null @@ -1,733 +0,0 @@ -"""Custom Quantitative Analysis Controller Module""" -__docformat__ = "numpy" - -import argparse -import logging -from pathlib import Path -from typing import List - -import pandas as pd -from prompt_toolkit.completion import NestedCompleter - -from openbb_terminal import feature_flags as obbff -from openbb_terminal.common.quantitative_analysis import qa_view, rolling_view -from openbb_terminal.custom import custom_model -from openbb_terminal.decorators import log_start_end -from openbb_terminal.helper_funcs import ( - EXPORT_ONLY_FIGURES_ALLOWED, - EXPORT_ONLY_RAW_DATA_ALLOWED, - check_positive, - check_proportion_range, - check_list_dates, -) -from openbb_terminal.menu import session -from openbb_terminal.parent_classes import BaseController -from openbb_terminal.rich_config import console - -logger = logging.getLogger(__name__) - - -class QaController(BaseController): - """Quantitative Analysis Controller class""" - - CHOICES_COMMANDS = [ - "load", - "pick", - "raw", - "summary", - "line", - "hist", - "cdf", - "bw", - "rolling", - "decompose", - "cusum", - "acf", - "spread", - "quantile", - "skew", - "kurtosis", - "normality", - "qqplot", - "unitroot", - "goodness", - "unitroot", - "capm", - ] - - PATH = "/custom/qa/" - - def __init__( - self, - custom_df: pd.DataFrame, - file: str, - queue: List[str] = None, - ): - """Constructor""" - super().__init__(queue) - self.DATA_FILES = [file.name for file in Path("custom_imports").iterdir()] - - self.df = custom_df - self.ticker = file - self.target = custom_df.columns[1] - self.file = file - - if session and obbff.USE_PROMPT_TOOLKIT: - choices: dict = {c: {} for c in self.controller_choices} - choices["pick"] = {c: None for c in list(custom_df.columns)} - choices["load"] = {c: None for c in self.DATA_FILES} - self.choices = choices - - choices["support"] = self.SUPPORT_CHOICES - choices["about"] = self.ABOUT_CHOICES - - self.completer = NestedCompleter.from_nested_dict(choices) - - def custom_reset(self): - """Class specific component of reset command""" - if self.ticker: - if self.target: - return ["custom", f"load {self.file}", "qa", f"pick {self.target}"] - return ["custom", f"load {self.file}", "qa"] - return [] - - def update_runtime_choices(self): - if session and obbff.USE_PROMPT_TOOLKIT: - self.choices["pick"] = {c: None for c in list(self.df.columns)} - self.completer = NestedCompleter.from_nested_dict(self.choices) - - def print_help(self): - """Print help""" - help_text = f"""[cmds] - load load new data file - pick pick target column for analysis[/cmds] - -[param]File: [/param]{self.file} -[param]Target Column: [/param]{self.target} -[cmds] -[info]Statistics:[/info] - summary brief summary statistics of loaded stock. - normality normality statistics and tests - unitroot unit root test for stationarity (ADF, KPSS) -[info]Plots:[/info] - line line plot of selected target - hist histogram with density plot - cdf cumulative distribution function - bw box and whisker plot - acf (partial) auto-correlation function differentials of prices - qqplot residuals against standard normal curve -[info]Rolling Metrics:[/info] - rolling rolling mean and std deviation of prices - spread rolling variance and std deviation of prices - quantile rolling median and quantile of prices - skew rolling skewness of distribution of prices - kurtosis rolling kurtosis of distribution of prices -[info]Other:[/info] - raw print raw data - decompose decomposition in cyclic-trend, season, and residuals of prices - cusum detects abrupt changes using cumulative sum algorithm of prices[/cmds] - """ - console.print(text=help_text, menu="Custom - Quantitative Analysis") - - @log_start_end(log=logger) - def call_load(self, other_args: List[str]): - """Process load""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="load", - description="Load custom data set into a dataframe", - ) - parser.add_argument( - "-f", - "--file", - choices=self.DATA_FILES, - help="File to load in.", - default="test.csv", - type=str, - ) - - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - file = Path("custom_imports") / ns_parser.file - self.df = custom_model.load(file) - self.df.columns = self.df.columns.map(lambda x: x.lower()) - for col in self.df.columns: - if col in ["date", "time", "timestamp"]: # Could be others? - self.df[col] = pd.to_datetime(self.df[col]) - self.df = self.df.set_index(col) - self.file = ns_parser.file - self.update_runtime_choices() - console.print("") - - @log_start_end(log=logger) - def call_pick(self, other_args: List[str]): - """Process pick command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="pick", - description=""" - Change target variable - """, - ) - parser.add_argument( - "-t", - "--target", - dest="target", - type=lambda x: x.lower(), - choices=list(self.df.columns), - help="Select variable to analyze", - ) - if other_args and "-t" not in other_args and "-h" not in other_args: - other_args.insert(0, "-t") - - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - self.target = ns_parser.target - console.print("") - - @log_start_end(log=logger) - def call_raw(self, other_args: List[str]): - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="raw", - description=""" - Print raw data to console - """, - ) - parser.add_argument( - "-w", - "--window", - help="Number to show", - type=check_positive, - default=20, - dest="limit", - ) - parser.add_argument( - "-d", - "--descend", - action="store_true", - default=False, - dest="descend", - help="Sort in descending order", - ) - - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED - ) - if ns_parser: - qa_view.display_raw( - data=self.df[self.target], - limit=ns_parser.limit, - sortby="", - descend=ns_parser.descend, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_summary(self, other_args: List[str]): - """Process summary command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="summary", - description=""" - Summary statistics - """, - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED - ) - if ns_parser: - qa_view.display_summary(data=self.df, export=ns_parser.export) - - @log_start_end(log=logger) - def call_line(self, other_args: List[str]): - """Process line command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="line", - description="Show line plot of selected data and allow to draw lines or highlight specific datetimes.", - ) - parser.add_argument( - "--log", - help="Plot with y on log scale", - dest="log", - action="store_true", - default=False, - ) - parser.add_argument( - "-d", - "--draw", - help="Draw lines and annotate on the plot", - dest="draw", - action="store_true", - default=False, - ) - parser.add_argument( - "--ml", - help="Draw vertical line markers to highlight certain events", - dest="ml", - type=check_list_dates, - default="", - ) - parser.add_argument( - "--ms", - help="Draw scatter markers to highlight certain events", - dest="ms", - type=check_list_dates, - default="", - ) - - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED - ) - if ns_parser: - qa_view.display_line( - self.df[self.target], - title=f"{self.ticker} {self.target}", - log_y=ns_parser.log, - draw=ns_parser.draw, - markers_lines=ns_parser.ml, - markers_scatter=ns_parser.ms, - ) - - @log_start_end(log=logger) - def call_hist(self, other_args: List[str]): - """Process hist command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="hist", - description=""" - Histogram with density and rug - """, - ) - parser.add_argument( - "-b", "--bins", type=check_positive, default=15, dest="n_bins" - ) - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - qa_view.display_hist( - symbol=self.ticker, - data=self.df, - target=self.target, - bins=ns_parser.n_bins, - ) - - @log_start_end(log=logger) - def call_cdf(self, other_args: List[str]): - """Process cdf command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="cdf", - description=""" - Cumulative distribution function - """, - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED - ) - if ns_parser: - qa_view.display_cdf( - symbol=self.ticker, - data=self.df, - target=self.target, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_bw(self, other_args: List[str]): - """Process bwy command""" - parser = argparse.ArgumentParser( - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - add_help=False, - prog="bw", - description=""" - Box and Whisker plot - """, - ) - parser.add_argument( - "-y", - "--yearly", - action="store_true", - default=False, - dest="year", - help="Flag to show yearly bw plot", - ) - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - qa_view.display_bw( - symbol=self.ticker, - data=self.df, - target=self.target, - yearly=ns_parser.year, - ) - - @log_start_end(log=logger) - def call_decompose(self, other_args: List[str]): - """Process decompose command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="decompose", - description=""" - Decompose time series as: - - Additive Time Series = Level + CyclicTrend + Residual + Seasonality - - Multiplicative Time Series = Level * CyclicTrend * Residual * Seasonality - """, - ) - parser.add_argument( - "-m", - "--multiplicative", - action="store_true", - default=False, - dest="multiplicative", - help="decompose using multiplicative model instead of additive", - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED - ) - if ns_parser: - qa_view.display_seasonal( - symbol=self.ticker, - data=self.df, - target=self.target, - multiplicative=ns_parser.multiplicative, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_cusum(self, other_args: List[str]): - """Process cusum command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="cusum", - description=""" - Cumulative sum algorithm (CUSUM) to detect abrupt changes in data - """, - ) - parser.add_argument( - "-t", - "--threshold", - dest="threshold", - type=float, - default=( - max(self.df[self.target].values) - min(self.df[self.target].values) - ) - / 40, - help="threshold", - ) - parser.add_argument( - "-d", - "--drift", - dest="drift", - type=float, - default=( - max(self.df[self.target].values) - min(self.df[self.target].values) - ) - / 80, - help="drift", - ) - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - qa_view.display_cusum( - data=self.df, - target=self.target, - threshold=ns_parser.threshold, - drift=ns_parser.drift, - ) - - @log_start_end(log=logger) - def call_acf(self, other_args: List[str]): - """Process acf command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="acf", - description=""" - Auto-Correlation and Partial Auto-Correlation Functions for diff and diff diff stock data - """, - ) - parser.add_argument( - "-w", - "--window", - dest="lags", - type=check_positive, - default=15, - help="maximum lags to display in plots", - ) - ns_parser = self.parse_known_args_and_warn(parser, other_args) - if ns_parser: - qa_view.display_acf( - symbol=self.ticker, - data=self.df, - target=self.target, - lags=ns_parser.lags, - ) - - @log_start_end(log=logger) - def call_rolling(self, other_args: List[str]): - """Process rolling command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="rolling", - description=""" - Rolling mean and std deviation - """, - ) - parser.add_argument( - "-w", - "--window", - action="store", - dest="n_window", - type=check_positive, - default=14, - help="Window length", - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED - ) - if ns_parser: - rolling_view.display_mean_std( - symbol=self.ticker, - data=self.df, - target=self.target, - window=ns_parser.n_window, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_spread(self, other_args: List[str]): - """Process spread command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="spread", - description="""Shows rolling spread measurement - """, - ) - parser.add_argument( - "-w", - "--window", - action="store", - dest="n_window", - type=check_positive, - default=14, - help="Window length", - ) - ns_parser = self.parse_known_args_and_warn( - parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED - ) - if ns_parser: - rolling_view.display_spread( - symbol=self.ticker, - data=self.df, - target=self.target, - window=ns_parser.n_window, - export=ns_parser.export, - ) - - @log_start_end(log=logger) - def call_quantile(self, other_args: List[str]): - """Process quantile command""" - parser = argparse.ArgumentParser( - add_help=False, - formatter_class=argparse.ArgumentDefaultsHelpFormatter, - prog="quantile", - description=""" - The quantiles are values which divide the distribution such that - there is a given proportion of observations below the quantile. - For example, the median is a quantile. The median is the central - value of the distribution, such that half the points are less than - or equal to it and half are greater than or equal to it. - - By default, q is set at 0.5, which effectively is median. Change q to - get the desired quantile (0