From bedf414172ef16f716c3f11ba8657c7068000bb0 Mon Sep 17 00:00:00 2001 From: didier Date: Sun, 28 Mar 2021 12:36:01 +0100 Subject: [PATCH] refactor residual models to have naive and arima --- .../residuals_analysis/ra_controller.py | 21 ++- .../residuals_analysis/residuals_model.py | 153 ++++++++++++++++++ 2 files changed, 162 insertions(+), 12 deletions(-) create mode 100644 gamestonk_terminal/residuals_analysis/residuals_model.py diff --git a/gamestonk_terminal/residuals_analysis/ra_controller.py b/gamestonk_terminal/residuals_analysis/ra_controller.py index 1c0ab52d9a0..dfa7fb60662 100644 --- a/gamestonk_terminal/residuals_analysis/ra_controller.py +++ b/gamestonk_terminal/residuals_analysis/ra_controller.py @@ -7,6 +7,7 @@ from datetime import datetime import pandas as pd from matplotlib import pyplot as plt from gamestonk_terminal.residuals_analysis import residuals_api +from gamestonk_terminal.residuals_analysis import residuals_model from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import get_flair from gamestonk_terminal.menu import session @@ -73,7 +74,6 @@ class ResidualsController: print("\nCurrently supported:") print(" naive naive method") print(" arima autoregressive integrated moving average") - print(" regression regression") print("\nResiduals Analysis:") print(" help show this comparison analysis menu again") @@ -117,7 +117,7 @@ class ResidualsController: "--model", dest="model", type=str, - choices=["naive", "regression"], + choices=["naive", "arima"], help="Model to fit", ) @@ -138,17 +138,14 @@ class ResidualsController: return if ns_parser.model == "naive": - if other_args[2:]: - print(f"Unknown args: {other_args[2:]}") + self.model_name, self.model, self.residuals = residuals_model.naive( + other_args[2:], self.stock + ) - naive = pd.Series(self.stock.values[:-1], index=self.stock[1:].index) - - self.model_name = "Naive" - self.model = naive - self.residuals = self.stock[1:].values - naive.values - - elif ns_parser.model == "regression": - print(other_args[2:]) + elif ns_parser.model == "arima": + self.model_name, self.model, self.residuals = residuals_model.arima( + other_args[2:], self.stock + ) except Exception as e: print(e) diff --git a/gamestonk_terminal/residuals_analysis/residuals_model.py b/gamestonk_terminal/residuals_analysis/residuals_model.py new file mode 100644 index 00000000000..751d7378875 --- /dev/null +++ b/gamestonk_terminal/residuals_analysis/residuals_model.py @@ -0,0 +1,153 @@ +""" Residuals Model """ +__docformat__ = "numpy" + +import argparse +import pandas as pd +from typing import List +import pmdarima +from statsmodels.tsa.arima.model import ARIMA +from gamestonk_terminal.helper_funcs import parse_known_args_and_warn + + +def naive( + other_args: List[str], + stock: pd.Series, +): + """Naive model + + Parameters + ---------- + other_args : str + Command line arguments to be processed with argparse + stock : pd.Series + Stock data + + Returns + ---------- + model_name : str + Command line arguments to be processed with argparse + model : pd.Series + Model series + residuals : List[float] + Residuals from model fitting stock data + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="naive", + description=""" + Naive model + """, + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + naive = pd.Series(stock.values[:-1], index=stock[1:].index) + + model_name = "Naive" + model = naive + residuals = stock[1:].values - naive.values + + return model_name, model, residuals + + except Exception as e: + print(e, "\n") + return "", None, list() + + +def arima( + other_args: List[str], + stock: pd.Series, +): + """Arima model + + Parameters + ---------- + other_args : str + Command line arguments to be processed with argparse + stock : pd.Series + Stock data + + Returns + ---------- + model_name : str + Command line arguments to be processed with argparse + model : pd.Series + Model series + residuals : List[float] + Residuals from model fitting stock data + """ + parser = argparse.ArgumentParser( + add_help=False, + prog="arima", + description=""" + ARIMA model + """, + ) + parser.add_argument( + "-i", + "--ic", + action="store", + dest="s_ic", + type=str, + default="aic", + choices=["aic", "aicc", "bic", "hqic", "oob"], + 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", + type=str, + help="arima model order (p,d,q) in format: pdq.", + ) + + try: + ns_parser = parse_known_args_and_warn(parser, other_args) + if not ns_parser: + return + + if ns_parser.s_order: + t_order = tuple([int(ord) for ord in list(ns_parser.s_order)]) + model_fit = ARIMA(stock.values, order=t_order).fit() + model = pd.Series(model_fit.fittedvalues[1:], index=stock.index[1:]) + model_name = f"ARIMA {t_order}" + residuals = model_fit.resid + + else: + if ns_parser.b_seasonal: + model_fit = pmdarima.auto_arima( + stock.values, + error_action="ignore", + seasonal=True, + m=5, + information_criteria=ns_parser.s_ic, + ) + else: + model_fit = pmdarima.auto_arima( + stock.values, + error_action="ignore", + seasonal=False, + information_criteria=ns_parser.s_ic, + ) + + model = pd.Series(model_fit.predict_in_sample()[1:], index=stock.index[1:]) + model_name = f"ARIMA {model_fit.order}" + residuals = model_fit.resid() + + return model_name, model, residuals + + except Exception as e: + print(e, "\n") + return "", None, list()