From 64d4f227533701c3ba9635f278acf4bfe5a326a7 Mon Sep 17 00:00:00 2001 From: James Maslek Date: Tue, 26 Jul 2022 13:09:21 -0400 Subject: [PATCH] Clenow Volatility Adjusted Momentum (#2180) * Add this clenow volatility momentum thing * Hugo + FIx controller * clean up * mypy fix * Add to menu and dont show header * menu testing Co-authored-by: DidierRLopes --- i18n/en.yml | 1 + .../technical_analysis/momentum_model.py | 47 +++++++++++++ .../technical_analysis/momentum_view.py | 66 +++++++++++++++++++ openbb_terminal/helper_funcs.py | 5 +- .../technical_analysis/ta_controller.py | 34 ++++++++++ .../test_print_help[None].txt | 1 + .../test_print_help[start0].txt | 1 + .../terminal/common/ta/clenow/_index.md | 20 ++++++ website/data/menu/main.yml | 6 ++ 9 files changed, 180 insertions(+), 1 deletion(-) create mode 100644 website/content/terminal/common/ta/clenow/_index.md diff --git a/i18n/en.yml b/i18n/en.yml index 479b64c3187..44bb9e1328f 100644 --- a/i18n/en.yml +++ b/i18n/en.yml @@ -425,6 +425,7 @@ en: stocks/ta/stoch: stochastic oscillator stocks/ta/fisher: fisher transform stocks/ta/cg: centre of gravity + stocks/ta/clenow: clenow volatility adjusted momentum stocks/ta/_trend_: Trend stocks/ta/adx: average directional movement index stocks/ta/aroon: aroon indicator diff --git a/openbb_terminal/common/technical_analysis/momentum_model.py b/openbb_terminal/common/technical_analysis/momentum_model.py index f2626dbf268..4d752888fb4 100644 --- a/openbb_terminal/common/technical_analysis/momentum_model.py +++ b/openbb_terminal/common/technical_analysis/momentum_model.py @@ -2,10 +2,14 @@ __docformat__ = "numpy" import logging +from typing import Tuple +import numpy as np import pandas as pd import pandas_ta as ta +from sklearn.linear_model import LinearRegression +from openbb_terminal.rich_config import console from openbb_terminal.decorators import log_start_end logger = logging.getLogger(__name__) @@ -185,3 +189,46 @@ def cg(values: pd.Series, length: int) -> pd.DataFrame: Dataframe of technical indicator """ return pd.DataFrame(ta.cg(close=values, length=length).dropna()) + + +@log_start_end(log=logger) +def clenow_momentum( + values: pd.Series, length: int = 90 +) -> Tuple[float, float, pd.Series]: + """Gets the Clenow Volatility Adjusted Momentum. this is defined as the regression coefficient on log prices + multiplied by the R^2 value of the regression + + Parameters + ---------- + values:pd.Series + Values to perform regression for + length: int + Length of lookback period + + Returns + ------- + float: + R2 of fit to log data + float: + Coefficient of linear regression + pd.Series: + Values for best fit line + """ + if len(values) < length: + console.print( + f"[red]Calculation asks for at least last {length} days of data[/red]" + ) + return np.nan, np.nan, pd.Series() + + values = values[-length:] + + y = np.log(values) + X = np.arange(len(y)).reshape(-1, 1) + + lr = LinearRegression() + lr.fit(X, y) + + r2 = lr.score(X, y) + coef = lr.coef_[0] + + return r2, coef, pd.Series(lr.predict(X)) diff --git a/openbb_terminal/common/technical_analysis/momentum_view.py b/openbb_terminal/common/technical_analysis/momentum_view.py index 0e6ae3aff4c..eb5c87c930a 100644 --- a/openbb_terminal/common/technical_analysis/momentum_view.py +++ b/openbb_terminal/common/technical_analysis/momentum_view.py @@ -19,6 +19,7 @@ from openbb_terminal.helper_funcs import ( plot_autoscale, reindex_dates, is_valid_axes_count, + print_rich_table, ) logger = logging.getLogger(__name__) @@ -539,3 +540,68 @@ def display_cg( "cg", df_ta, ) + + +@log_start_end(log=logger) +def display_clenow_momentum( + series: pd.Series, + length: int = 90, + export: str = "", + external_axes: Optional[List[plt.Axes]] = None, +): + """ + + Parameters + ---------- + series + length + export + + Returns + ------- + + """ + r2, coef, fit_data = momentum_model.clenow_momentum(series, length) + + df = pd.DataFrame.from_dict( + { + "R^2": f"{r2:.5f}", + "Fit Coef": f"{coef:.5f}", + "Factor": f"{coef * r2:.5f}", + }, + orient="index", + ) + print_rich_table( + df, + show_index=True, + headers=[""], + title="Clenow Exponential Regression Factor", + show_header=False, + ) + + # This plot has 2 axes + if external_axes is None: + _, ax1 = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI) + + elif is_valid_axes_count(external_axes, 1): + ax1 = external_axes + else: + return + + ax1.plot(series.index, np.log(series.values)) + ax1.plot(series.index[-length:], fit_data, linewidth=2) + + ax1.set_title("Clenow Momentum Exponential Regression") + ax1.set_xlim(series.index[0], series.index[-1]) + ax1.set_ylabel("Log Price") + theme.style_primary_axis( + ax1, + ) + if external_axes is None: + theme.visualize_output() + + export_data( + export, + os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"), + "clenow", + ) diff --git a/openbb_terminal/helper_funcs.py b/openbb_terminal/helper_funcs.py index 038fd6c2728..5be8c96a177 100644 --- a/openbb_terminal/helper_funcs.py +++ b/openbb_terminal/helper_funcs.py @@ -146,6 +146,7 @@ def print_rich_table( index_name: str = "", headers: Union[List[str], pd.Index] = None, floatfmt: Union[str, List[str]] = ".2f", + show_header: bool = True, ): """Prepare a table from df in rich @@ -163,10 +164,12 @@ def print_rich_table( Titles for columns floatfmt: Union[str, List[str]] Float number formatting specs as string or list of strings. Defaults to ".2f" + show_header: bool + Whether to show the header row. """ if obbff.USE_TABULATE_DF: - table = Table(title=title, show_lines=True) + table = Table(title=title, show_lines=True, show_header=show_header) if show_index: table.add_column(index_name) diff --git a/openbb_terminal/stocks/technical_analysis/ta_controller.py b/openbb_terminal/stocks/technical_analysis/ta_controller.py index 302fb3bd70f..3af41e31964 100644 --- a/openbb_terminal/stocks/technical_analysis/ta_controller.py +++ b/openbb_terminal/stocks/technical_analysis/ta_controller.py @@ -75,6 +75,7 @@ class TechnicalAnalysisController(StockBaseController): "obv", "fib", "tv", + "clenow", ] PATH = "/stocks/ta/" @@ -135,6 +136,7 @@ class TechnicalAnalysisController(StockBaseController): mt.add_cmd("stoch") mt.add_cmd("fisher") mt.add_cmd("cg") + mt.add_cmd("clenow") mt.add_info("_trend_") mt.add_cmd("adx") mt.add_cmd("aroon") @@ -1345,3 +1347,35 @@ class TechnicalAnalysisController(StockBaseController): end_date=ns_parser.end, export=ns_parser.export, ) + + @log_start_end(log=logger) + def call_clenow(self, other_args: List[str]): + """Process clenow command""" + parser = argparse.ArgumentParser( + add_help=False, + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + prog="clenow", + description="Calculates the Clenow Volatility Adjusted Momentum.", + ) + parser.add_argument( + "-p", + "--period", + dest="period", + help="Lookback period for regression", + default=90, + type=check_positive, + ) + + if self.interval != "1440min": + console.print( + "[red]This regression should be performed with daily data and at least 90 days.[/red]" + ) + return + + ns_parser = self.parse_known_args_and_warn( + parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED + ) + if ns_parser: + momentum_view.display_clenow_momentum( + self.stock["Adj Close"], ns_parser.period, ns_parser.export + ) diff --git a/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[None].txt b/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[None].txt index 040ae294ab2..7bb08822d18 100644 --- a/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[None].txt +++ b/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[None].txt @@ -19,6 +19,7 @@ Momentum: stoch stochastic oscillator fisher fisher transform cg centre of gravity + clenow clenow volatility adjusted momentum Trend: adx average directional movement index aroon aroon indicator diff --git a/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[start0].txt b/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[start0].txt index cebc916d4f8..d64698a6e57 100644 --- a/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[start0].txt +++ b/tests/openbb_terminal/stocks/technical_analysis/txt/test_ta_controller/test_print_help[start0].txt @@ -19,6 +19,7 @@ Momentum: stoch stochastic oscillator fisher fisher transform cg centre of gravity + clenow clenow volatility adjusted momentum Trend: adx average directional movement index aroon aroon indicator diff --git a/website/content/terminal/common/ta/clenow/_index.md b/website/content/terminal/common/ta/clenow/_index.md new file mode 100644 index 00000000000..de8c7f8c225 --- /dev/null +++ b/website/content/terminal/common/ta/clenow/_index.md @@ -0,0 +1,20 @@ +``` +usage: clenow [-p PERIOD] [-h] [--export EXPORT] +``` +Calculates the Clenow Volatility Adjusted Momentum. + +This indicator is calculated by performing a regression on log prices. The factor is obtained by multiplying the +regression coefficient with the R2 of the regression. + +An example of the use of this strategy can be found at: +https://www.quant-investing.com/blog/this-easy-to-use-adjusted-slope-momentum-strategy-performed-7-times-better-than-the-market + +``` +options: + -p PERIOD, --period PERIOD + Lookback period for regression (default: 90) + -h, --help show this help message (default: False) + --export EXPORT Export figure into png, jpg, pdf, svg (default: ) + +For more information and examples, use 'about clenow' to access the related guide. +``` \ No newline at end of file diff --git a/website/data/menu/main.yml b/website/data/menu/main.yml index fe0de409227..5ea7b6b8060 100755 --- a/website/data/menu/main.yml +++ b/website/data/menu/main.yml @@ -522,6 +522,8 @@ main: ref: "/terminal/common/ta/obv" - name: fib ref: "/terminal/common/ta/fib" + - name: clenow + ref: "/terminal/common/ta/clenow" - name: behavioural analysis ref: "/terminal/common/ba" sub: @@ -915,6 +917,8 @@ main: ref: "/terminal/common/ta/obv" - name: fib ref: "/terminal/common/ta/fib" + - name: clenow + ref: "/terminal/common/ta/clenow" - name: defi ref: "/terminal/crypto/defi" sub: @@ -1155,6 +1159,8 @@ main: ref: "/terminal/common/ta/obv" - name: fib ref: "/terminal/common/ta/fib" + - name: clenow + ref: "/terminal/common/ta/clenow" - name: prediction techniques ref: "/terminal/common/pred" sub: