Merge branch 'main' into New-Portfolio-Optimization-Menu

This commit is contained in:
Colin Delahunty
2022-04-09 08:17:18 -04:00
committed by GitHub
22 changed files with 18807 additions and 154 deletions

View File

@@ -109,8 +109,8 @@ class CryptoController(CryptoBaseController):
> nft non-fungible tokens, e.g.: today drops{has_ticker_start}
> dd due-diligence for loaded coin, e.g.: coin information, social media, market stats
> ta technical analysis for loaded coin, e.g.: ema, macd, rsi, adx, bbands, obv
> pred prediction techniques e.g.: regression, arima, rnn, lstm, conv1d, monte carlo
> qa quantitative analysis, \t e.g.: decompose, cusum, residuals analysis[/menu]
> pred prediction techniques, e.g.: regression, arima, rnn, lstm, conv1d, monte carlo
> qa quantitative analysis e.g.: decompose, cusum, residuals analysis[/menu]
{has_ticker_end}
"""
console.print(text=help_text, menu="Cryptocurrency")
@@ -451,9 +451,7 @@ class CryptoController(CryptoBaseController):
@log_start_end(log=logger)
def call_defi(self, _):
"""Process defi command"""
from openbb_terminal.cryptocurrency.defi.defi_controller import (
DefiController,
)
from openbb_terminal.cryptocurrency.defi.defi_controller import DefiController
self.queue = self.load_class(DefiController, self.queue)

View File

@@ -29,7 +29,7 @@ class ForexController(BaseController):
"""Forex Controller class."""
CHOICES_COMMANDS = ["to", "from", "load", "quote", "candle", "resources"]
CHOICES_MENUS = ["ta", "oanda"]
CHOICES_MENUS = ["ta", "qa", "oanda", "pred"]
PATH = "/forex/"
FILE_PATH = os.path.join(os.path.dirname(__file__), "README.md")
@@ -66,6 +66,8 @@ class ForexController(BaseController):
candle show candle plot for loaded data[/cmds]
[menu]
> ta technical analysis for loaded coin, e.g.: ema, macd, rsi, adx, bbands, obv
> qa quantitative analysis, e.g.: decompose, cusum, residuals analysis
> pred prediction techniques e.g.: regression, arima, rnn, lstm, conv1d, monte carlo
[/menu]{has_symbols_end}
[info]Forex brokerages:[/info][menu]
> oanda Oanda menu[/menu][/cmds]
@@ -318,6 +320,64 @@ class ForexController(BaseController):
else:
console.print("No currency pair data is loaded. Use 'load' to load data.\n")
@log_start_end(log=logger)
def call_pred(self, _):
"""Process pred command"""
if obbff.ENABLE_PREDICT:
if self.from_symbol and self.to_symbol:
if self.data.empty:
console.print(
"No currency pair data is loaded. Use 'load' to load data.\n"
)
else:
try:
from openbb_terminal.forex.prediction_techniques import (
pred_controller,
)
self.queue = self.load_class(
pred_controller.PredictionTechniquesController,
self.from_symbol,
self.to_symbol,
self.data.index[0],
"1440min",
self.data,
self.queue,
)
except ImportError:
logger.exception("Tensorflow not available")
console.print(
"[red]Run pip install tensorflow to continue[/red]\n"
)
else:
console.print("No pair selected.\n")
else:
console.print(
"Predict is disabled. Check ENABLE_PREDICT flag on feature_flags.py",
"\n",
)
@log_start_end(log=logger)
def call_qa(self, _):
"""Process qa command"""
if self.from_symbol and self.to_symbol:
if self.data.empty:
console.print(
"No currency pair data is loaded. Use 'load' to load data.\n"
)
else:
from openbb_terminal.forex.quantitative_analysis import qa_controller
self.queue = self.load_class(
qa_controller.QaController,
self.from_symbol,
self.to_symbol,
self.data,
self.queue,
)
else:
console.print("No pair selected.\n")
# HELP WANTED!
# TODO: Add news and reddit commands back
# behavioural analysis and exploratory data analysis would be useful in the

View File

@@ -0,0 +1,33 @@
"""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,
)

View File

@@ -0,0 +1,716 @@
""" Prediction Controller """
__docformat__ = "numpy"
import argparse
import logging
from datetime import datetime
from typing import List
import numpy as np
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.decorators import log_start_end
from openbb_terminal.helper_funcs import (
EXPORT_ONLY_FIGURES_ALLOWED,
check_positive,
get_next_stock_market_days,
parse_known_args_and_warn,
valid_date,
)
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 PredictionTechniquesController(BaseController):
"""Prediction Techniques Controller class"""
CHOICES_COMMANDS = [
"pick",
"ets",
"knn",
"regression",
"arima",
"mlp",
"rnn",
"lstm",
"conv1d",
"mc",
]
PATH = "/forex/pred/"
def __init__(
self,
from_symbol: str,
to_symbol: str,
start: datetime,
interval: str,
data: pd.DataFrame,
queue: List[str] = None,
):
"""Constructor"""
super().__init__(queue)
data["Returns"] = data["Adj Close"].pct_change()
data["LogRet"] = np.log(data["Adj Close"]) - np.log(data["Adj Close"].shift(1))
data = data.rename(columns={"Adj Close": "AdjClose"})
data = data.dropna()
self.data = data
self.from_symbol = from_symbol
self.to_symbol = to_symbol
self.ticker = f"{from_symbol}/{to_symbol}"
self.start = start
self.interval = interval
self.target = "AdjClose"
if session and obbff.USE_PROMPT_TOOLKIT:
choices: dict = {c: {} for c in self.controller_choices}
choices["pick"] = {c: {} for c in self.data.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.completer = NestedCompleter.from_nested_dict(choices)
def print_help(self):
"""Print help"""
pair_info = f"{self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
help_text = f"""[cmds]
pick pick new target variable[/cmds]
[param]Pair Loaded: [/param]{pair_info}
[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="Forex - Prediction Techniques")
def custom_reset(self):
"""Class specific component of reset command"""
if self.ticker:
return [
"forex",
f"from {self.from_symbol}",
f"to {self.to_symbol}",
"load",
"pred",
]
return []
@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.data.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 = 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 = 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.data.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.data.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(
ticker=self.ticker,
values=self.data[self.target],
n_predict=ns_parser.n_days,
trend=ns_parser.trend,
seasonal=ns_parser.seasonal,
seasonal_periods=ns_parser.seasonal_periods,
s_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 = parse_known_args_and_warn(
parser, other_args, EXPORT_ONLY_FIGURES_ALLOWED
)
if ns_parser:
knn_view.display_k_nearest_neighbors(
ticker=self.ticker,
data=self.data[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 = 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.data.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.data.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.data[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,
s_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 = 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.data.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.data.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.data[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,
s_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.data[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.data[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.data[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.data[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,
)
parser.add_argument(
"--dist",
choices=mc_model.DISTRIBUTIONS,
default="lognormal",
dest="dist",
help="Whether to model returns or log returns",
)
ns_parser = 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.data[self.target],
n_future=ns_parser.n_days,
n_sims=ns_parser.n_sims,
use_log=ns_parser.dist == "lognormal",
export=ns_parser.export,
)

View File

@@ -0,0 +1,57 @@
"""Quantitative Analysis API."""
import os
from openbb_terminal.helper_classes import ModelsNamespace as _models
# 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 cusum,
)
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,
)
# Models
# NOTE: The raw function is used here to point to the commons path where all the
# qa models are expected to live
models = _models(
[
os.path.abspath(os.path.dirname(raw.__code__.co_filename)),
os.path.abspath(os.path.dirname(__file__)),
]
)

View File

@@ -0,0 +1,704 @@
"""Quantitative Analysis Controller Module"""
__docformat__ = "numpy"
import argparse
import logging
from typing import List
import numpy as np
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.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,
parse_known_args_and_warn,
check_list_dates,
)
from openbb_terminal.menu import session
from openbb_terminal.parent_classes import CryptoBaseController
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
class QaController(CryptoBaseController):
"""Quantitative Analysis Controller class"""
CHOICES_COMMANDS = [
"pick",
"raw",
"summary",
"line",
"hist",
"cdf",
"bw",
"rolling",
"decompose",
"cusum",
"acf",
"spread",
"quantile",
"skew",
"kurtosis",
"normality",
"qqplot",
"unitroot",
"goodness",
"unitroot",
]
PATH = "/forex/qa/"
def __init__(
self,
from_symbol: str,
to_symbol: str,
data: pd.DataFrame,
queue: List[str] = None,
):
"""Constructor"""
super().__init__(queue)
data["Returns"] = data["Close"].pct_change()
data["LogRet"] = np.log(data["Close"]) - np.log(data["Close"].shift(1))
data = data.dropna()
self.data = data
self.from_symbol = from_symbol
self.to_symbol = to_symbol
self.ticker = f"{from_symbol}/{to_symbol}"
self.target = "Close"
if session and obbff.USE_PROMPT_TOOLKIT:
choices: dict = {c: {} for c in self.controller_choices}
choices["pick"] = {c: None for c in list(data.columns)}
self.completer = NestedCompleter.from_nested_dict(choices)
def print_help(self):
"""Print help"""
help_text = f"""[cmds]
pick pick target column for analysis[/cmds]
[param]Pair: [/param]{self.ticker}
[param]Target Column: [/param]{self.target}
[cmds]
[info]Statistics:[/info]
summary brief summary statistics of loaded pair.
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]Risk:[/info]
var display value at risk
es display expected shortfall
[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="Forex - Quantitative Analysis")
def custom_reset(self):
"""Class specific component of reset command"""
if self.ticker:
return [
"forex",
f"from {self.from_symbol}",
f"to {self.to_symbol}",
"load",
"qa",
]
return []
@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.data.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 = 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(
"-l",
"--limit",
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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
qa_view.display_raw(
self.data[self.target],
num=ns_parser.limit,
sort="",
des=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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
qa_view.display_summary(df=self.data, 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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_FIGURES_ALLOWED
)
if ns_parser:
qa_view.display_line(
self.data[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 = parse_known_args_and_warn(parser, other_args)
if ns_parser:
qa_view.display_hist(
name=self.ticker,
df=self.data,
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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
qa_view.display_cdf(
name=self.ticker,
df=self.data,
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 = parse_known_args_and_warn(parser, other_args)
if ns_parser:
qa_view.display_bw(
name=self.ticker,
df=self.data,
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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
qa_view.display_seasonal(
name=self.ticker,
df=self.data,
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.data[self.target].values) - min(self.data[self.target].values)
)
/ 40,
help="threshold",
)
parser.add_argument(
"-d",
"--drift",
dest="drift",
type=float,
default=(
max(self.data[self.target].values) - min(self.data[self.target].values)
)
/ 80,
help="drift",
)
ns_parser = parse_known_args_and_warn(parser, other_args)
if ns_parser:
qa_view.display_cusum(
df=self.data,
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 forex data
""",
)
parser.add_argument(
"-l",
"--lags",
dest="lags",
type=check_positive,
default=15,
help="maximum lags to display in plots",
)
ns_parser = parse_known_args_and_warn(parser, other_args)
if ns_parser:
if self.target != "Close":
console.print(
"Target not Close. For best results, use `pick Close` first."
)
qa_view.display_acf(
name=self.ticker,
df=self.data,
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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
rolling_view.display_mean_std(
name=self.ticker,
df=self.data,
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 = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
rolling_view.display_spread(
name=self.ticker,
df=self.data,
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<q<1).
""",
)
parser.add_argument(
"-w",
"--window",
action="store",
dest="n_window",
type=check_positive,
default=14,
help="window length",
)
parser.add_argument(
"-q",
"--quantile",
action="store",
dest="f_quantile",
type=check_proportion_range,
default=0.5,
help="quantile",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
rolling_view.display_quantile(
name=self.ticker,
df=self.data,
target=self.target,
window=ns_parser.n_window,
quantile=ns_parser.f_quantile,
export=ns_parser.export,
)
@log_start_end(log=logger)
def call_skew(self, other_args: List[str]):
"""Process skew command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="skew",
description="""
Skewness is a measure of asymmetry or distortion of symmetric
distribution. It measures the deviation of the given distribution
of a random variable from a symmetric distribution, such as normal
distribution. A normal distribution is without any skewness, as it is
symmetrical on both sides. Hence, a curve is regarded as skewed if
it is shifted towards the right or the left.
""",
)
parser.add_argument(
"-w",
"--window",
action="store",
dest="n_window",
type=check_positive,
default=14,
help="window length",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
rolling_view.display_skew(
name=self.ticker,
df=self.data,
target=self.target,
window=ns_parser.n_window,
export=ns_parser.export,
)
@log_start_end(log=logger)
def call_kurtosis(self, other_args: List[str]):
"""Process kurtosis command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="kurtosis",
description="""
Kurtosis is a measure of the "tailedness" of the probability distribution
of a real-valued random variable. Like skewness, kurtosis describes the shape
of a probability distribution and there are different ways of quantifying it
for a theoretical distribution and corresponding ways of estimating it from
a sample from a population. Different measures of kurtosis may have different
interpretations.
""",
)
parser.add_argument(
"-w",
"--window",
action="store",
dest="n_window",
type=check_positive,
default=14,
help="window length",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
rolling_view.display_kurtosis(
name=self.ticker,
df=self.data,
target=self.target,
window=ns_parser.n_window,
export=ns_parser.export,
)
@log_start_end(log=logger)
def call_normality(self, other_args: List[str]):
"""Process normality command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="normality",
description="""
Normality tests
""",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
qa_view.display_normality(
df=self.data, target=self.target, export=ns_parser.export
)
@log_start_end(log=logger)
def call_qqplot(self, other_args: List[str]):
"""Process qqplot command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="qqplot",
description="""
Display QQ plot vs normal quantiles
""",
)
ns_parser = parse_known_args_and_warn(parser, other_args)
if ns_parser:
qa_view.display_qqplot(name=self.ticker, df=self.data, target=self.target)
@log_start_end(log=logger)
def call_unitroot(self, other_args: List[str]):
"""Process unitroot command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="unitroot",
description="""
Unit root test / stationarity (ADF, KPSS)
""",
)
parser.add_argument(
"-r",
"--fuller_reg",
help="Type of regression. Can be ‘c’,’ct’,’ctt’,’nc’ 'c' - Constant and t - trend order",
choices=["c", "ct", "ctt", "nc"],
default="c",
type=str,
dest="fuller_reg",
)
parser.add_argument(
"-k",
"--kps_reg",
help="Type of regression. Can be ‘c’,’ct'",
choices=["c", "ct"],
type=str,
dest="kpss_reg",
default="c",
)
ns_parser = parse_known_args_and_warn(
parser, other_args, export_allowed=EXPORT_ONLY_RAW_DATA_ALLOWED
)
if ns_parser:
qa_view.display_unitroot(
df=self.data,
target=self.target,
fuller_reg=ns_parser.fuller_reg,
kpss_reg=ns_parser.kpss_reg,
export=ns_parser.export,
)

View File

@@ -1,5 +1,13 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "7e02d340-956a-496d-b4e5-fd74cc85f13a",
"metadata": {},
"source": [
"## Notebook setup"
]
},
{
"cell_type": "code",
"execution_count": null,
@@ -7,21 +15,44 @@
"metadata": {},
"outputs": [],
"source": [
"# Import most generic modules\n",
"import importlib\n",
"import pathlib\n",
"import os\n",
"import sys\n",
"from datetime import datetime, timedelta\n",
"import pandas as pd\n",
"from IPython.display import display, Markdown\n",
"import io\n",
"import math\n",
"import warnings\n",
"from datetime import datetime, timedelta\n",
"\n",
"warnings.filterwarnings(\"ignore\")\n",
"module_path = os.path.abspath(os.path.join(\"../..\"))\n",
"import matplotlib.pyplot as plt\n",
"import matplotlib_inline.backend_inline\n",
"import pandas as pd\n",
"from tqdm.notebook import tqdm\n",
"\n",
"if module_path not in sys.path:\n",
" sys.path.append(module_path)"
"from openbb_terminal import api as openbb\n",
"from openbb_terminal.helper_classes import TerminalStyle\n",
"\n",
"%matplotlib inline\n",
"matplotlib_inline.backend_inline.set_matplotlib_formats(\"svg\")\n",
"warnings.filterwarnings(\"ignore\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d318a555-d1db-444e-ba8c-8427850dec59",
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" theme = TerminalStyle(\"light\", \"light\", \"light\")\n",
"except:\n",
" pass\n",
"stylesheet = openbb.widgets.html_report_stylesheet()"
]
},
{
"cell_type": "markdown",
"id": "fa5bd393-2f66-4ba3-98f8-66230636ce0e",
"metadata": {},
"source": [
"## Select Ticker"
]
},
{
@@ -36,8 +67,7 @@
"outputs": [],
"source": [
"# Parameters that will be replaced when calling this notebook\n",
"ticker = \"TSLA\"\n",
"\n",
"ticker = \"clx\"\n",
"report_name = f\"{datetime.now().strftime('%Y%m%d_%H%M%S')}_comparison_{ticker.upper()}\""
]
},
@@ -48,11 +78,11 @@
"metadata": {},
"outputs": [],
"source": [
"display(\n",
" Markdown(\n",
" f\"# {ticker.upper()} - Comparison - {datetime.now().strftime('%Y/%m/%d %H:%M:%S')}\"\n",
" )\n",
")"
"ticker = ticker.upper()\n",
"report_title = (\n",
" f\"{ticker.upper()} Comparison ({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})\"\n",
")\n",
"report_title"
]
},
{
@@ -62,15 +92,48 @@
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import (\n",
" finviz_compare_model,\n",
" yahoo_finance_model,\n",
")\n",
"\n",
"ticker = ticker.upper()\n",
"finviz_similar = finviz_compare_model.get_similar_companies(\n",
"finviz_similar = openbb.stocks.ca.models.finviz_compare.get_similar_companies(\n",
" ticker, [\"Sector\", \"Industry\", \"Country\"]\n",
")[0]"
")[0]\n",
"finviz_similar.pop(finviz_similar.index(ticker))\n",
"print(f\"Similar companies:\\n{' '.join([i for i in finviz_similar])}\")"
]
},
{
"cell_type": "markdown",
"id": "135b09f6-c22b-4cc5-b68e-d77f9e3b3a60",
"metadata": {
"tags": []
},
"source": [
"### Overview"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9907d7ea-3ad0-4123-ab2e-f03defa4eea2",
"metadata": {},
"outputs": [],
"source": [
"overview = openbb.stocks.ca.models.finviz_compare.get_comparison_data(\n",
" similar=finviz_similar,\n",
" data_type=\"overview\",\n",
")\n",
"overview = overview.sort_values(\"Volume\", ascending=False)\n",
"overview.head(4)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bc7d52a4-fbe6-4b39-a3d5-bfae841dacac",
"metadata": {},
"outputs": [],
"source": [
"# Update the list of similar companies to take up only up to 12 with top volume\n",
"finviz_similar = overview[\"Ticker\"].to_list()[:12]\n",
"print(f\"Similar companies:\\n{' '.join([i for i in finviz_similar])}\")"
]
},
{
@@ -88,28 +151,27 @@
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.fundamental_analysis import yahoo_finance_model\n",
"def get_info_as_dict(ticker):\n",
" df_info = openbb.stocks.fa.models.yahoo_finance.get_info(ticker)\n",
" if \"Long business summary\" in df_info.index:\n",
" summary = df_info.loc[\"Long business summary\"].values[0]\n",
" elif \"Long name\" in df_info.index:\n",
" summary = df_info.loc[\"Long name\"].values[0]\n",
" else:\n",
" summary = \"\"\n",
" if \"Website\" in df_info.index:\n",
" website = df_info.loc[\"Website\"].values[0]\n",
" else:\n",
" website = \"\"\n",
" return {\"summary\": summary, \"website\": website}\n",
"\n",
"df_info = yahoo_finance_model.get_info(ticker)\n",
"if \"Long business summary\" in df_info.index:\n",
" summary = df_info.loc[\"Long business summary\"].values[0]\n",
"if \"Website\" in df_info.index:\n",
" website = df_info.loc[\"Website\"].values[0]\n",
"\n",
"similar_companies = dict()\n",
"similar_companies[ticker] = get_info_as_dict(ticker)\n",
"\n",
"if finviz_similar:\n",
" print(f\"{ticker}: {website}\")\n",
" print(summary)\n",
"\n",
" for symbol in finviz_similar:\n",
" df_info = yahoo_finance_model.get_info(symbol)\n",
" if \"Long business summary\" in df_info.index:\n",
" summary = df_info.loc[\"Long business summary\"].values[0]\n",
" if \"Website\" in df_info.index:\n",
" website = df_info.loc[\"Website\"].values[0]\n",
"\n",
" print(\"\")\n",
" print(f\"{symbol}: {website}\")\n",
" print(summary)"
" for symbol in tqdm(finviz_similar):\n",
" similar_companies[symbol] = get_info_as_dict(symbol)"
]
},
{
@@ -125,20 +187,24 @@
{
"cell_type": "code",
"execution_count": null,
"id": "1fdfac4c-62cd-4bd3-b7df-41ba67263798",
"metadata": {},
"id": "5e7509a7-961a-4fb8-bd87-0df4b8c98d04",
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"import math\n",
"from openbb_terminal.stocks.comparison_analysis import yahoo_finance_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" for i in range(math.ceil(len(finviz_similar) / 4)):\n",
" yahoo_finance_view.display_historical(\n",
" similar_tickers=finviz_similar[4 * (i) : 4 * (i + 1)],\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"for c in tqdm(finviz_similar):\n",
" fig, ax = plt.subplots(figsize=(4.2, 3), dpi=150)\n",
" openbb.stocks.ca.hist(\n",
" normalize=True,\n",
" similar_tickers=[ticker, c],\n",
" external_axes=[ax],\n",
" )\n",
" ax.set_title(\"\")\n",
" fig.tight_layout()\n",
" f = io.BytesIO()\n",
" fig.savefig(f, format=\"svg\")\n",
" similar_companies[c][\"historical_price\"] = f.getvalue().decode(\"utf-8\")"
]
},
{
@@ -152,19 +218,21 @@
{
"cell_type": "code",
"execution_count": null,
"id": "eb1850dc-1d62-4ad4-971f-1bbce6209726",
"id": "2df60c41-4f87-483c-abe7-7063fa7648cf",
"metadata": {},
"outputs": [],
"source": [
"from matplotlib import pyplot as plt\n",
"fig, ax = plt.subplots(figsize=(9.5, 6), dpi=150)\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" plt.figure(figsize=(25, 10))\n",
" yahoo_finance_view.display_correlation(\n",
" similar_tickers=finviz_similar,\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"openbb.stocks.ca.hcorr(\n",
" similar_tickers=finviz_similar,\n",
" external_axes=[ax],\n",
")\n",
"\n",
"fig.tight_layout()\n",
"f = io.BytesIO()\n",
"fig.savefig(f, format=\"svg\")\n",
"historical_correlation = f.getvalue().decode(\"utf-8\")"
]
},
{
@@ -180,45 +248,34 @@
{
"cell_type": "code",
"execution_count": null,
"id": "a7bf528c-427c-4d84-8cb9-ec5656f920e1",
"id": "f84b055f-ec6d-4b61-89f3-17f06a1ca12d",
"metadata": {},
"outputs": [],
"source": [
"if finviz_similar and finviz_similar != [\"\"]:\n",
" for i in range(math.ceil(len(finviz_similar) / 4)):\n",
" yahoo_finance_view.display_volume(\n",
" similar_tickers=finviz_similar[4 * (i) : 4 * (i + 1)],\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
]
},
{
"cell_type": "markdown",
"id": "6e370470-8014-4e97-95f2-13b4f66645c5",
"metadata": {
"tags": []
},
"source": [
"### Overview"
"volume_groups = []\n",
"for i in range(math.ceil(len(finviz_similar) / 3)):\n",
" volume_groups.append(finviz_similar[3 * (i) : 3 * (i + 1)])\n",
"volume_groups"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f82b7162-f7e5-4d5c-8ca9-50466f789f48",
"id": "8812a2f6-f912-4161-a938-5e2a343d782a",
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import finviz_compare_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" finviz_compare_view.screener(\n",
" similar=finviz_similar,\n",
" data_type=\"overview\",\n",
"historical_volumes = []\n",
"for vgroup in volume_groups:\n",
" fig, ax = plt.subplots(figsize=(4, 3), dpi=150)\n",
" openbb.stocks.ca.volume(\n",
" similar_tickers=vgroup,\n",
" external_axes=[ax],\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
" ax.set_title(\" \".join([i for i in vgroup]))\n",
" f = io.BytesIO()\n",
" fig.savefig(f, format=\"svg\")\n",
" historical_volumes.append(f.getvalue().decode(\"utf-8\"))"
]
},
{
@@ -234,19 +291,15 @@
{
"cell_type": "code",
"execution_count": null,
"id": "caed21ad-a31d-4063-a4cb-f5b6fd1c63ed",
"id": "ef50e7ba-70bf-4ffc-b01c-8e28266c13b4",
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import finviz_compare_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" finviz_compare_view.screener(\n",
" similar=finviz_similar,\n",
" data_type=\"valuation\",\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"valuation = openbb.stocks.ca.models.finviz_compare.get_comparison_data(\n",
" similar=finviz_similar,\n",
" data_type=\"valuation\",\n",
")\n",
"valuation.head(4)"
]
},
{
@@ -262,19 +315,15 @@
{
"cell_type": "code",
"execution_count": null,
"id": "e98bf90d-bf2b-4eea-b533-08211e8eec47",
"id": "1fdfac4c-62cd-4bd3-b7df-41ba67263798",
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import finviz_compare_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" finviz_compare_view.screener(\n",
" similar=finviz_similar,\n",
" data_type=\"financial\",\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"financial = openbb.stocks.ca.models.finviz_compare.get_comparison_data(\n",
" similar=finviz_similar,\n",
" data_type=\"financial\",\n",
")\n",
"financial.head(4)"
]
},
{
@@ -294,15 +343,11 @@
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import finviz_compare_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" finviz_compare_view.screener(\n",
" similar=finviz_similar,\n",
" data_type=\"ownership\",\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"ownership = openbb.stocks.ca.models.finviz_compare.get_comparison_data(\n",
" similar=finviz_similar,\n",
" data_type=\"ownership\",\n",
")\n",
"ownership.head(4)"
]
},
{
@@ -322,15 +367,11 @@
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import finviz_compare_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" finviz_compare_view.screener(\n",
" similar=finviz_similar,\n",
" data_type=\"performance\",\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"performance = openbb.stocks.ca.models.finviz_compare.get_comparison_data(\n",
" similar=finviz_similar,\n",
" data_type=\"performance\",\n",
")\n",
"performance.head(4)"
]
},
{
@@ -350,26 +391,116 @@
"metadata": {},
"outputs": [],
"source": [
"from openbb_terminal.stocks.comparison_analysis import finviz_compare_view\n",
"\n",
"if finviz_similar and finviz_similar != [\"\"]:\n",
" finviz_compare_view.screener(\n",
" similar=finviz_similar,\n",
" data_type=\"technical\",\n",
" )\n",
"else:\n",
" print(\"Ticker not found in CoinGeckoAPI\")"
"technical = openbb.stocks.ca.models.finviz_compare.get_comparison_data(\n",
" similar=finviz_similar,\n",
" data_type=\"technical\",\n",
")\n",
"technical.head(4)"
]
},
{
"cell_type": "markdown",
"id": "16a5fc9a-0d9b-4589-b680-f954e4e6f78a",
"metadata": {},
"source": [
"## Render the report template to a file"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "sought-phase",
"id": "eebac826-906b-482d-a387-55cb78eb5e18",
"metadata": {},
"outputs": [],
"source": [
"!jupyter nbconvert {report_name + \".ipynb\"} --to html --no-input"
"body = \"\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "26727f90-0950-4434-97f9-6b52180e4473",
"metadata": {},
"outputs": [],
"source": [
"body += openbb.widgets.h(1, report_title)\n",
"\n",
"body += openbb.widgets.h(2, \"Overview\")\n",
"\n",
"for company in similar_companies:\n",
" if company == ticker:\n",
" continue\n",
" # widgets.append()\n",
" body += openbb.widgets.row(\n",
" [\n",
" openbb.widgets.h(3, company)\n",
" + \"<br>\"\n",
" + similar_companies[company][\"website\"]\n",
" + \"<br>\"\n",
" + \"<br>\"\n",
" + similar_companies[company][\"summary\"],\n",
" openbb.widgets.h(3, f\"{ticker} vs {company}\")\n",
" + similar_companies[company][\"historical_price\"],\n",
" ]\n",
" )\n",
"\n",
"body += openbb.widgets.h(2, \"Historical correlation\")\n",
"body += openbb.widgets.row([historical_correlation])\n",
"\n",
"body += openbb.widgets.h(2, \"Historical volumes\")\n",
"for chart in range(0, len(historical_volumes), 2):\n",
" body += openbb.widgets.row(\n",
" [historical_volumes[chart], historical_volumes[chart + 1]]\n",
" )\n",
"\n",
"\n",
"body += openbb.widgets.h(2, \"Screeners\")\n",
"\n",
"body += openbb.widgets.h(3, \"overview\")\n",
"body += openbb.widgets.row([overview.to_html()])\n",
"\n",
"body += openbb.widgets.h(3, \"valuation\")\n",
"body += openbb.widgets.row([valuation.to_html()])\n",
"\n",
"body += openbb.widgets.h(3, \"financial\")\n",
"body += openbb.widgets.row([financial.to_html()])\n",
"\n",
"body += openbb.widgets.h(3, \"ownership\")\n",
"body += openbb.widgets.row([ownership.to_html()])\n",
"\n",
"body += openbb.widgets.h(3, \"performance\")\n",
"body += openbb.widgets.row([performance.to_html()])"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f7697fa8-cc27-4bf8-b5e6-ea6ab4ec6a21",
"metadata": {},
"outputs": [],
"source": [
"report = openbb.widgets.html_report(title=report_name, stylesheet=stylesheet, body=body)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "42e6a584-b7c9-435f-98cb-ea93ac6b8812",
"metadata": {},
"outputs": [],
"source": [
"# to save the results\n",
"with open(report_name + \".html\", \"w\") as fh:\n",
" fh.write(report)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6de79d28-fc26-4bf0-bece-f823a424b4fc",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {

View File

@@ -212,13 +212,14 @@ tbody tr:nth-child(even) {
.hcontainer {
margin: 10pt;
width: 1000px;
display:flex;
}
.item {
display: inline-block;
*display: inline;
zoom: 1;
padding-left: 10pt;
padding-right: 10pt;
vertical-align: top;
flex: 1;
}

View File

@@ -216,6 +216,7 @@ def display_correlation(
cmap="RdYlGn",
linewidths=1,
annot=True,
annot_kws={"fontsize": 10},
vmin=-1,
vmax=1,
mask=mask,

6
scripts/test_forex_pred.openbb vendored Normal file
View File

@@ -0,0 +1,6 @@
forex
to eur
load
pred
rnn
exit

24
scripts/test_forex_qa.openbb vendored Normal file
View File

@@ -0,0 +1,24 @@
forex
to eur
load
qa
summary
normality
unitroot
line
hist
cdf
bw
acf
qqplot
rolling
spread
quantile
skew
kurtosis
var
es
raw
decompose
cusum
exit

View File

@@ -16,7 +16,7 @@ Source:
> nft non-fungible tokens, e.g.: today drops[unvl]
> dd due-diligence for loaded coin, e.g.: coin information, social media, market stats
> ta technical analysis for loaded coin, e.g.: ema, macd, rsi, adx, bbands, obv
> pred prediction techniques e.g.: regression, arima, rnn, lstm, conv1d, monte carlo
> qa quantitative analysis, e.g.: decompose, cusum, residuals analysis
> pred prediction techniques, e.g.: regression, arima, rnn, lstm, conv1d, monte carlo
> qa quantitative analysis e.g.: decompose, cusum, residuals analysis
[/unvl]

View File

@@ -0,0 +1,11 @@
# IMPORTATION STANDARD
# IMPORTATION THIRDPARTY
# IMPORTATION INTERNAL
from openbb_terminal.helper_classes import ModelsNamespace as _models
from openbb_terminal.forex.quantitative_analysis import qa_api
def test_models():
assert isinstance(qa_api.models, _models)

View File

@@ -0,0 +1,551 @@
# IMPORTATION STANDARD
import os
# IMPORTATION THIRDPARTY
import pandas as pd
import pytest
# IMPORTATION INTERNAL
from openbb_terminal.forex.quantitative_analysis import qa_controller
DF_PAIR = pd.DataFrame.from_dict(
data={
pd.Timestamp("2020-11-30 00:00:00"): {
"Open": 75.69999694824219,
"High": 76.08999633789062,
"Low": 75.41999816894531,
"Close": 75.75,
"Adj Close": 71.90919494628906,
"Volume": 5539100,
"date_id": 1,
"OC_High": 75.75,
"OC_Low": 75.69999694824219,
},
pd.Timestamp("2020-12-01 00:00:00"): {
"Open": 76.0199966430664,
"High": 77.12999725341797,
"Low": 75.69000244140625,
"Close": 77.02999877929688,
"Adj Close": 73.1242904663086,
"Volume": 6791700,
"date_id": 2,
"OC_High": 77.02999877929688,
"OC_Low": 76.0199966430664,
},
},
orient="index",
)
EMPTY_DF = pd.DataFrame()
QA_CONTROLLER = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
)
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_headers": [("User-Agent", None)],
"filter_query_parameters": [
("period1", "MOCK_PERIOD_1"),
("period2", "MOCK_PERIOD_2"),
("date", "MOCK_DATE"),
],
}
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"queue, expected",
[
(["load", "help"], []),
(["quit", "help"], ["help"]),
],
)
def test_menu_with_queue(expected, mocker, queue):
mocker.patch(
target=(
"openbb_terminal.forex.quantitative_analysis.qa_controller."
"QaController.switch"
),
return_value=["quit"],
)
result_menu = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
queue=queue,
).menu()
assert result_menu == expected
@pytest.mark.vcr(record_mode="none")
def test_menu_without_queue_completion(mocker):
# ENABLE AUTO-COMPLETION : HELPER_FUNCS.MENU
mocker.patch(
target="openbb_terminal.feature_flags.USE_PROMPT_TOOLKIT",
new=True,
)
mocker.patch(
target="openbb_terminal.parent_classes.session",
)
mocker.patch(
target="openbb_terminal.parent_classes.session.prompt",
return_value="quit",
)
# DISABLE AUTO-COMPLETION : CONTROLLER.COMPLETER
mocker.patch.object(
target=qa_controller.obbff,
attribute="USE_PROMPT_TOOLKIT",
new=True,
)
mocker.patch(
target="openbb_terminal.forex.quantitative_analysis.qa_controller.session",
)
mocker.patch(
target="openbb_terminal.forex.quantitative_analysis.qa_controller.session.prompt",
return_value="quit",
)
result_menu = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
queue=None,
).menu()
assert result_menu == []
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"mock_input",
["help", "homee help", "home help", "mock"],
)
def test_menu_without_queue_sys_exit(mock_input, mocker):
# DISABLE AUTO-COMPLETION
mocker.patch.object(
target=qa_controller.obbff,
attribute="USE_PROMPT_TOOLKIT",
new=False,
)
mocker.patch(
target="openbb_terminal.forex.quantitative_analysis.qa_controller.session",
return_value=None,
)
# MOCK USER INPUT
mocker.patch("builtins.input", return_value=mock_input)
# MOCK SWITCH
class SystemExitSideEffect:
def __init__(self):
self.first_call = True
def __call__(self, *args, **kwargs):
if self.first_call:
self.first_call = False
raise SystemExit()
return ["quit"]
mock_switch = mocker.Mock(side_effect=SystemExitSideEffect())
mocker.patch(
target=(
"openbb_terminal.forex.quantitative_analysis.qa_controller."
"QaController.switch"
),
new=mock_switch,
)
result_menu = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
queue=None,
).menu()
assert result_menu == []
@pytest.mark.vcr(record_mode="none")
@pytest.mark.record_stdout
def test_print_help():
controller = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
)
controller.print_help()
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"an_input, expected_queue",
[
("", []),
("/help", ["home", "help"]),
("help/help", ["help", "help"]),
("q", ["quit"]),
("h", []),
(
"r",
[
"quit",
"quit",
"reset",
"forex",
"from MOCK_TICKER",
"to MOCK_TICKER",
"load",
"qa",
],
),
],
)
def test_switch(an_input, expected_queue):
controller = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
queue=None,
)
queue = controller.switch(an_input=an_input)
assert queue == expected_queue
@pytest.mark.vcr(record_mode="none")
def test_call_cls(mocker):
mocker.patch("os.system")
controller = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
)
controller.call_cls([])
assert controller.queue == []
os.system.assert_called_once_with("cls||clear")
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"func, queue, expected_queue",
[
(
"call_exit",
[],
[
"quit",
"quit",
"quit",
],
),
("call_exit", ["help"], ["quit", "quit", "quit", "help"]),
("call_home", [], ["quit", "quit"]),
("call_help", [], []),
("call_quit", [], ["quit"]),
("call_quit", ["help"], ["quit", "help"]),
(
"call_reset",
[],
[
"quit",
"quit",
"reset",
"forex",
"from MOCK_TICKER",
"to MOCK_TICKER",
"load",
"qa",
],
),
(
"call_reset",
["help"],
[
"quit",
"quit",
"reset",
"forex",
"from MOCK_TICKER",
"to MOCK_TICKER",
"load",
"qa",
"help",
],
),
],
)
def test_call_func_expect_queue(expected_queue, queue, func):
controller = qa_controller.QaController(
from_symbol="MOCK_TICKER",
to_symbol="MOCK_TICKER",
data=DF_PAIR.copy(),
queue=queue,
)
result = getattr(controller, func)([])
assert result is None
assert controller.queue == expected_queue
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"tested_func, other_args, mocked_func, called_args, called_kwargs",
[
(
"call_pick",
[QA_CONTROLLER.target],
"",
[],
dict(),
),
(
"call_raw",
["--limit=1", "--descend", "--export=csv"],
"qa_view.display_raw",
[QA_CONTROLLER.data[QA_CONTROLLER.target]],
dict(
num=1,
sort="",
des=True,
export="csv",
),
),
(
"call_summary",
["--export=csv"],
"qa_view.display_summary",
[],
dict(
df=QA_CONTROLLER.data,
export="csv",
),
),
(
"call_hist",
["--bins=1"],
"qa_view.display_hist",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
bins=1,
),
),
(
"call_cdf",
["--export=csv"],
"qa_view.display_cdf",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
export="csv",
),
),
(
"call_bw",
["--yearly"],
"qa_view.display_bw",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
yearly=True,
),
),
(
"call_rolling",
["--window=1", "--export=csv"],
"rolling_view.display_mean_std",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
window=1,
export="csv",
),
),
(
"call_decompose",
["--multiplicative", "--export=csv"],
"qa_view.display_seasonal",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
multiplicative=True,
export="csv",
),
),
(
"call_cusum",
["--threshold=1", "--drift=2"],
"qa_view.display_cusum",
[],
dict(
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
threshold=1,
drift=2,
),
),
(
"call_acf",
["--lags=1"],
"qa_view.display_acf",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
lags=1,
),
),
(
"call_spread",
["--window=1", "--export=csv"],
"rolling_view.display_spread",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
window=1,
export="csv",
),
),
(
"call_quantile",
["--window=1", "--quantile=0.1", "--export=csv"],
"rolling_view.display_quantile",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
window=1,
quantile=0.1,
export="csv",
),
),
(
"call_skew",
["--window=1", "--export=csv"],
"rolling_view.display_skew",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
window=1,
export="csv",
),
),
(
"call_kurtosis",
["--window=1", "--export=csv"],
"rolling_view.display_kurtosis",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
window=1,
export="csv",
),
),
(
"call_normality",
["--export=csv"],
"qa_view.display_normality",
[],
dict(
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
export="csv",
),
),
(
"call_qqplot",
[],
"qa_view.display_qqplot",
[],
dict(
name=QA_CONTROLLER.ticker,
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
),
),
(
"call_unitroot",
["--fuller_reg=ctt", "--kps_reg=ct", "--export=csv"],
"qa_view.display_unitroot",
[],
dict(
df=QA_CONTROLLER.data,
target=QA_CONTROLLER.target,
fuller_reg="ctt",
kpss_reg="ct",
export="csv",
),
),
],
)
def test_call_func(
tested_func, mocked_func, other_args, called_args, called_kwargs, mocker
):
if mocked_func:
mock = mocker.Mock()
mocker.patch(
"openbb_terminal.forex.quantitative_analysis.qa_controller." + mocked_func,
new=mock,
)
getattr(QA_CONTROLLER, tested_func)(other_args=other_args)
if called_args or called_kwargs:
mock.assert_called_once_with(*called_args, **called_kwargs)
else:
mock.assert_called_once()
else:
getattr(QA_CONTROLLER, tested_func)(other_args=other_args)
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"from_symbol, to_symbol, expected",
[
(None, None, ["forex", "from None", "to None", "load", "qa"]),
("MOCK_FROM", None, ["forex", "from MOCK_FROM", "to None", "load", "qa"]),
(None, "MOCK_TO", ["forex", "from None", "to MOCK_TO", "load", "qa"]),
(
"MOCK_FROM",
"MOCK_TO",
["forex", "from MOCK_FROM", "to MOCK_TO", "load", "qa"],
),
],
)
def test_custom_reset(expected, from_symbol, to_symbol):
controller = qa_controller.QaController(
from_symbol=None,
to_symbol=None,
data=DF_PAIR.copy(),
)
controller.from_symbol = from_symbol
controller.to_symbol = to_symbol
result = controller.custom_reset()
assert result == expected

View File

@@ -0,0 +1,31 @@
pick pick target column for analysis
Pair: MOCK_TICKER/MOCK_TICKER
Target Column: Close
Statistics:
summary brief summary statistics of loaded pair.
normality normality statistics and tests
unitroot unit root test for stationarity (ADF, KPSS)
Plots:
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
Rolling Metrics:
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
Risk:
var display value at risk
es display expected shortfall
Other:
raw print raw data
decompose decomposition in cyclic-trend, season, and residuals of prices
cusum detects abrupt changes using cumulative sum algorithm of prices

View File

@@ -329,8 +329,8 @@ def test_call_func_no_parser(func, mocker):
[
"call_candle",
"call_ta",
# "call_qa",
# "call_pred",
"call_qa",
"call_pred",
],
)
def test_call_func_no_ticker(func, mocker):

View File

@@ -11,6 +11,8 @@ Source: YahooFinance[dim]
candle show candle plot for loaded data
> ta technical analysis for loaded coin, e.g.: ema, macd, rsi, adx, bbands, obv
> qa quantitative analysis, e.g.: decompose, cusum, residuals analysis
> pred prediction techniques e.g.: regression, arima, rnn, lstm, conv1d, monte carlo
[/dim]
Forex brokerages:
> oanda Oanda menu

View File

@@ -64,6 +64,7 @@ def test_display_chains(calls_only, max_sp, min_sp, mocker, puts_only):
)
@pytest.mark.linux
@pytest.mark.default_cassette("test_plot_oi")
@pytest.mark.vcr
@pytest.mark.parametrize(