mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-29 20:53:54 +00:00
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 <dro.lopes@campus.fct.unl.pt>
This commit is contained in:
1
i18n/en.yml
vendored
1
i18n/en.yml
vendored
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
20
website/content/terminal/common/ta/clenow/_index.md
vendored
Normal file
20
website/content/terminal/common/ta/clenow/_index.md
vendored
Normal file
@@ -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.
|
||||
```
|
||||
6
website/data/menu/main.yml
vendored
6
website/data/menu/main.yml
vendored
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user