mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-11-26 03:02:00 +00:00
Refactor EDA -> Qa (#686)
* Ignore nft of the day test * Rename eda -> qa * Refactor rolling into view/model * Refactored commands to new convention * updated menu layout + add load * Add ra functions into qa menu + fix portfolio paths * fix menu help string * Update qa with target idea that indicates variable to do statistics on * Review changes except todos * Make qa indepedent of stock menu
This commit is contained in:
@@ -1,706 +0,0 @@
|
||||
""" Exploratory Data Analysis API """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
from typing import List
|
||||
from datetime import datetime
|
||||
from detecta import detect_cusum
|
||||
from matplotlib import pyplot as plt
|
||||
import pandas as pd
|
||||
from pandas.plotting import register_matplotlib_converters
|
||||
import numpy as np
|
||||
import seaborn as sns
|
||||
import statsmodels.api as sm
|
||||
|
||||
# pylint: disable=R0402
|
||||
import matplotlib.gridspec as gridspec
|
||||
from statsmodels.tsa.seasonal import seasonal_decompose
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
parse_known_args_and_warn,
|
||||
plot_autoscale,
|
||||
check_positive,
|
||||
)
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
|
||||
|
||||
register_matplotlib_converters()
|
||||
|
||||
|
||||
def summary(other_args: List[str], stock: pd.DataFrame):
|
||||
"""Print summary statistics
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="summary",
|
||||
description="""
|
||||
Summary statistics
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
df_stats = stock.describe(percentiles=[0.1, 0.25, 0.5, 0.75, 0.9])
|
||||
df_stats.loc["var"] = df_stats.loc["std"] ** 2
|
||||
print(df_stats.round(2).to_string())
|
||||
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def hist(other_args: List[str], ticker: str, stock: pd.DataFrame, start: datetime):
|
||||
"""Plot histogram and density
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="hist",
|
||||
description="""
|
||||
Histogram with depicted density and rug
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
sns.distplot(
|
||||
stock,
|
||||
bins=35,
|
||||
color="blue",
|
||||
hist=True,
|
||||
hist_kws={"edgecolor": "black"},
|
||||
kde=True,
|
||||
kde_kws={"color": "black", "lw": 3, "label": "KDE"},
|
||||
rug=True,
|
||||
rug_kws={"edgecolor": "orange"},
|
||||
)
|
||||
plt.title(
|
||||
f"Histogram with Density of {ticker} from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
plt.ylabel("Density")
|
||||
plt.xlabel("Share Price")
|
||||
plt.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def cumulative_distribution_function(
|
||||
other_args: List[str], ticker: str, stock: pd.DataFrame, start: datetime
|
||||
):
|
||||
"""Plot cumulative distribution function
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="cdf",
|
||||
description="""
|
||||
Cumulative distribution function
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
cdf = stock.value_counts().sort_index().div(len(stock)).cumsum()
|
||||
cdf.plot(lw=2)
|
||||
plt.title(
|
||||
f"Cumulative Distribution Function of {ticker} from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
plt.ylabel("Probability")
|
||||
plt.xlabel("Share Price")
|
||||
minVal = stock.values.min()
|
||||
q25 = np.quantile(stock.values, 0.25)
|
||||
medianVal = np.quantile(stock.values, 0.5)
|
||||
q75 = np.quantile(stock.values, 0.75)
|
||||
data = [
|
||||
(minVal, q25),
|
||||
(0.25, 0.25),
|
||||
"r",
|
||||
(q25, q25),
|
||||
(0, 0.25),
|
||||
"r",
|
||||
(minVal, medianVal),
|
||||
(0.5, 0.5),
|
||||
"r",
|
||||
(medianVal, medianVal),
|
||||
(0, 0.5),
|
||||
"r",
|
||||
(minVal, q75),
|
||||
(0.75, 0.75),
|
||||
"r",
|
||||
(q75, q75),
|
||||
(0, 0.75),
|
||||
"r",
|
||||
]
|
||||
plt.plot(*data, ls="--")
|
||||
plt.text(minVal + (q25 - minVal) / 2, 0.27, "Q1", color="r", fontweight="bold")
|
||||
plt.text(
|
||||
minVal + (medianVal - minVal) / 2,
|
||||
0.52,
|
||||
"Median",
|
||||
color="r",
|
||||
fontweight="bold",
|
||||
)
|
||||
plt.text(minVal + (q75 - minVal) / 2, 0.77, "Q3", color="r", fontweight="bold")
|
||||
plt.xlim(cdf.index[0], cdf.index[-1])
|
||||
plt.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def bwy(other_args: List[str], ticker: str, stock: pd.DataFrame, start: datetime):
|
||||
"""Box and Whisker plot yearly
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="bwy",
|
||||
description="""
|
||||
Box and Whisker plot yearly
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
sns.set(style="whitegrid")
|
||||
box_plot = sns.boxplot(x=stock.index.year, y=stock)
|
||||
box_plot.set(
|
||||
xlabel="Year",
|
||||
ylabel="Share Price",
|
||||
title=f"Box-plot per Year of {ticker} from {start.strftime('%Y-%m-%d')}",
|
||||
)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def bwm(other_args: List[str], ticker: str, stock: pd.DataFrame, start: datetime):
|
||||
"""Box and Whisker plot monthly
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="bwm",
|
||||
description="""
|
||||
Box and Whisker plot monthly
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
sns.set(style="whitegrid")
|
||||
box_plot = sns.boxplot(x=stock.index.month, y=stock)
|
||||
box_plot.set(
|
||||
xlabel="Month",
|
||||
ylabel="Share Price",
|
||||
title=f"Box-plot per Month of {ticker} from {start.strftime('%Y-%m-%d')}",
|
||||
)
|
||||
l_months = [
|
||||
"Jan",
|
||||
"Feb",
|
||||
"Mar",
|
||||
"Apr",
|
||||
"May",
|
||||
"Jun",
|
||||
"Jul",
|
||||
"Aug",
|
||||
"Sep",
|
||||
"Oct",
|
||||
"Nov",
|
||||
"Dec",
|
||||
]
|
||||
l_ticks = []
|
||||
for val in box_plot.get_xticklabels():
|
||||
l_ticks.append(l_months[int(val.get_text()) - 1])
|
||||
box_plot.set_xticklabels(l_ticks)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def rolling(other_args: List[str], ticker: str, stock: pd.DataFrame):
|
||||
"""Rolling mean and std deviation
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="rolling",
|
||||
description="""
|
||||
Rolling mean and std deviation
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w",
|
||||
"--window",
|
||||
dest="rolling_window",
|
||||
type=check_positive,
|
||||
default=10,
|
||||
help="rolling window",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
rolling_mean = stock.rolling(
|
||||
ns_parser.rolling_window, center=True, min_periods=1
|
||||
).mean()
|
||||
rolling_std = stock.rolling(
|
||||
ns_parser.rolling_window, center=True, min_periods=1
|
||||
).std()
|
||||
|
||||
_, axMean = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
axMean.plot(stock.index, stock.values, label=ticker, linewidth=2, color="black")
|
||||
axMean.plot(rolling_mean, linestyle="--", linewidth=3, color="blue")
|
||||
axMean.set_xlabel("Time")
|
||||
axMean.set_ylabel("Share Price", color="blue")
|
||||
axMean.legend(["Real values", "Rolling Mean"], loc=2)
|
||||
axMean.tick_params(axis="y", labelcolor="blue")
|
||||
axStd = axMean.twinx()
|
||||
axStd.plot(
|
||||
rolling_std, label="Rolling std", linestyle="--", color="green", linewidth=3
|
||||
)
|
||||
axStd.set_ylabel("Std Deviation")
|
||||
axStd.legend(["Rolling std"], loc=1)
|
||||
axStd.set_ylabel("Share Price standard deviation", color="green")
|
||||
axStd.tick_params(axis="y", labelcolor="green")
|
||||
axMean.set_title(
|
||||
"Rolling mean and std with window "
|
||||
+ str(ns_parser.rolling_window)
|
||||
+ " applied to "
|
||||
+ ticker
|
||||
)
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.minorticks_on()
|
||||
plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def decompose(other_args: List[str], ticker: str, stock: pd.DataFrame):
|
||||
"""Decompose time series as:
|
||||
- Additive Time Series = Level + CyclicTrend + Residual + Seasonality
|
||||
- Multiplicative Time Series = Level * CyclicTrend * Residual * Seasonality
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
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",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
seasonal_periods = 5
|
||||
# Hodrick-Prescott filter
|
||||
# See Ravn and Uhlig: http://home.uchicago.edu/~huhlig/papers/uhlig.ravn.res.2002.pdf
|
||||
lamb = 107360000000
|
||||
|
||||
fig = plt.figure(
|
||||
figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True
|
||||
)
|
||||
spec = gridspec.GridSpec(ncols=4, nrows=5, figure=fig)
|
||||
|
||||
fig.add_subplot(spec[0, :])
|
||||
plt.plot(stock)
|
||||
|
||||
plt.title(ticker + " (Time-Series)")
|
||||
|
||||
if ns_parser.multiplicative:
|
||||
resultMul = seasonal_decompose(
|
||||
stock, model="multiplicative", period=seasonal_periods
|
||||
)
|
||||
cycleMul, trendMul = sm.tsa.filters.hpfilter(
|
||||
resultMul.trend[resultMul.trend.notna().values], lamb=lamb
|
||||
)
|
||||
|
||||
# Multiplicative model
|
||||
fig.add_subplot(spec[1, :4])
|
||||
plt.plot(resultMul.trend, lw=2, c="purple")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Multiplicative Cyclic-Trend")
|
||||
|
||||
fig.add_subplot(spec[2, 0:2])
|
||||
plt.plot(trendMul, lw=2, c="tab:blue")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Multiplicative Trend component")
|
||||
|
||||
fig.add_subplot(spec[2, 2:])
|
||||
plt.plot(cycleMul, lw=2, c="green")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Multiplicative Cycle component")
|
||||
|
||||
fig.add_subplot(spec[3, :])
|
||||
plt.plot(resultMul.seasonal, lw=2, c="orange")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Multiplicative Seasonal effect")
|
||||
|
||||
fig.add_subplot(spec[4, :])
|
||||
plt.plot(resultMul.resid, lw=2, c="red")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Multiplicative Residuals")
|
||||
|
||||
else:
|
||||
resultAdd = seasonal_decompose(
|
||||
stock, model="additive", period=seasonal_periods
|
||||
)
|
||||
cycleAdd, trendAdd = sm.tsa.filters.hpfilter(
|
||||
resultAdd.trend[resultAdd.trend.notna().values], lamb=lamb
|
||||
)
|
||||
|
||||
# Additive model
|
||||
fig.add_subplot(spec[1, :4])
|
||||
plt.plot(resultAdd.trend, lw=2, c="purple")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Additive Cyclic-Trend")
|
||||
|
||||
fig.add_subplot(spec[2, 0:2])
|
||||
plt.plot(trendAdd, lw=2, c="tab:blue")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Additive Trend component")
|
||||
|
||||
fig.add_subplot(spec[2, 2:])
|
||||
plt.plot(cycleAdd, lw=2, c="green")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Additive Cycle component")
|
||||
|
||||
fig.add_subplot(spec[3, :])
|
||||
plt.plot(resultAdd.seasonal, lw=2, c="orange")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Additive Seasonal effect")
|
||||
|
||||
fig.add_subplot(spec[4, :])
|
||||
plt.plot(resultAdd.resid, lw=2, c="red")
|
||||
plt.xlim([stock.index[0], stock.index[-1]])
|
||||
plt.title("Additive Residuals")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
# From # https://otexts.com/fpp2/seasonal-strength.html
|
||||
|
||||
print("Time-Series Level is " + str(round(stock.mean(), 2)))
|
||||
|
||||
if ns_parser.multiplicative:
|
||||
FtMul = max(0, 1 - np.var(resultMul.resid)) / np.var(
|
||||
resultMul.trend + resultMul.resid
|
||||
)
|
||||
print("Strength of Trend: %.4f" % FtMul)
|
||||
FsMul = max(
|
||||
0,
|
||||
1
|
||||
- np.var(resultMul.resid)
|
||||
/ np.var(resultMul.seasonal + resultMul.resid),
|
||||
)
|
||||
print("Strength of Seasonality: %.4f" % FsMul)
|
||||
|
||||
else:
|
||||
FtAdd = max(
|
||||
0,
|
||||
1 - np.var(resultAdd.resid) / np.var(resultAdd.trend + resultAdd.resid),
|
||||
)
|
||||
print("Strength of Trend: %.4f" % FtAdd)
|
||||
FsAdd = max(
|
||||
0,
|
||||
1
|
||||
- np.var(resultAdd.resid)
|
||||
/ np.var(resultAdd.seasonal + resultAdd.resid),
|
||||
)
|
||||
print("Strength of Seasonality: %.4f" % FsAdd)
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def cusum(other_args: List[str], stock: pd.DataFrame):
|
||||
"""Cumulative sum algorithm (CUSUM) to detect abrupt changes in data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="cusum",
|
||||
description="""
|
||||
Cumulative sum algorithm (CUSUM) to detect abrupt changes in data
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-t",
|
||||
"--threshold",
|
||||
dest="threshold",
|
||||
type=float,
|
||||
default=(max(stock["Adj Close"].values) - min(stock["Adj Close"].values)) / 40,
|
||||
help="threshold",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--drift",
|
||||
dest="drift",
|
||||
type=float,
|
||||
default=(max(stock["Adj Close"].values) - min(stock["Adj Close"].values)) / 80,
|
||||
help="drift",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
detect_cusum(stock.values, ns_parser.threshold, ns_parser.drift, True, True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def acf(other_args: List[str], ticker: str, stock: pd.DataFrame, start: datetime):
|
||||
"""Auto-Correlation and Partial Auto-Correlation Functions for diff and diff diff stock data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.DataFrame
|
||||
Stock data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="acf",
|
||||
description="""
|
||||
Auto-Correlation and Partial Auto-Correlation Functions for diff and diff diff stock data
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--lags",
|
||||
dest="lags",
|
||||
type=check_positive,
|
||||
default=15,
|
||||
help="maximum lags to display in plots",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
print(stock.head())
|
||||
stock = stock["Adj Close"]
|
||||
|
||||
fig = plt.figure(
|
||||
figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True
|
||||
)
|
||||
spec = gridspec.GridSpec(ncols=2, nrows=2, figure=fig)
|
||||
|
||||
# Diff Auto-correlation function for original time series
|
||||
ax_acf = fig.add_subplot(spec[0, 0])
|
||||
sm.graphics.tsa.plot_acf(
|
||||
np.diff(np.diff(stock.values)), lags=ns_parser.lags, ax=ax_acf
|
||||
)
|
||||
plt.title(f"Diff({ticker}) Auto-Correlation from {start.strftime('%Y-%m-%d')}")
|
||||
# Diff Partial auto-correlation function for original time series
|
||||
ax_pacf = fig.add_subplot(spec[0, 1])
|
||||
sm.graphics.tsa.plot_pacf(
|
||||
np.diff(np.diff(stock.values)), lags=ns_parser.lags, ax=ax_pacf
|
||||
)
|
||||
plt.title(
|
||||
f"Diff({ticker}) Partial Auto-Correlation from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
|
||||
# Diff Diff Auto-correlation function for original time series
|
||||
ax_acf = fig.add_subplot(spec[1, 0])
|
||||
sm.graphics.tsa.plot_acf(
|
||||
np.diff(np.diff(stock.values)), lags=ns_parser.lags, ax=ax_acf
|
||||
)
|
||||
plt.title(
|
||||
f"Diff(Diff({ticker})) Auto-Correlation from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
# Diff Diff Partial auto-correlation function for original time series
|
||||
ax_pacf = fig.add_subplot(spec[1, 1])
|
||||
sm.graphics.tsa.plot_pacf(
|
||||
np.diff(np.diff(stock.values)), lags=ns_parser.lags, ax=ax_pacf
|
||||
)
|
||||
plt.title(
|
||||
f"Diff(Diff({ticker})) Partial Auto-Correlation from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
@@ -1,365 +0,0 @@
|
||||
"""Rolling Statistics"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
from typing import List
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas_ta as ta
|
||||
import pandas as pd
|
||||
from pandas.plotting import register_matplotlib_converters
|
||||
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
check_positive,
|
||||
check_proportion_range,
|
||||
parse_known_args_and_warn,
|
||||
plot_autoscale,
|
||||
)
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
|
||||
register_matplotlib_converters()
|
||||
|
||||
|
||||
def spread(
|
||||
other_args: List[str], s_ticker: str, s_interval: str, df_stock: pd.DataFrame
|
||||
):
|
||||
"""Standard Deviation & Variance
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args:List[str]
|
||||
Argparse arguments
|
||||
s_ticker: str
|
||||
Ticker
|
||||
s_interval: str
|
||||
Stock time interval
|
||||
df_stock: pd.DataFrame
|
||||
Dataframe of prices
|
||||
"""
|
||||
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="spread",
|
||||
description="""
|
||||
|
||||
""",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="length",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--offset",
|
||||
action="store",
|
||||
dest="n_offset",
|
||||
type=check_positive,
|
||||
default=0,
|
||||
help="offset",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
# Daily
|
||||
if s_interval == "1440min":
|
||||
df_ta = ta.stdev(
|
||||
close=df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
df_ta_ = ta.variance(
|
||||
close=df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
|
||||
# Intraday
|
||||
else:
|
||||
df_ta = ta.stdev(
|
||||
close=df_stock["Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
df_ta_ = ta.variance(
|
||||
close=df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
|
||||
fig, axes = plt.subplots(3, 1, figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
ax = axes[0]
|
||||
ax.set_title(f"{s_ticker} Spread")
|
||||
if s_interval == "1440min":
|
||||
ax.plot(df_stock.index, df_stock["Adj Close"].values, "fuchsia", lw=1)
|
||||
else:
|
||||
ax.plot(df_stock.index, df_stock["Close"].values, "fuchsia", lw=1)
|
||||
ax.set_xlim(df_stock.index[0], df_stock.index[-1])
|
||||
ax.set_ylabel("Share Price ($)")
|
||||
ax.yaxis.set_label_position("right")
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.minorticks_on()
|
||||
ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax1 = axes[1]
|
||||
ax1.plot(df_ta.index, df_ta.values, "b", lw=1, label="stdev")
|
||||
ax1.set_xlim(df_stock.index[0], df_stock.index[-1])
|
||||
ax1.set_ylabel("Stdev")
|
||||
ax1.yaxis.set_label_position("right")
|
||||
ax1.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax1.minorticks_on()
|
||||
ax1.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax2 = axes[2]
|
||||
ax2.plot(df_ta_.index, df_ta_.values, "g", lw=1, label="variance")
|
||||
ax2.set_xlim(df_stock.index[0], df_stock.index[-1])
|
||||
ax2.set_ylabel("Variance")
|
||||
ax2.yaxis.set_label_position("right")
|
||||
ax2.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax2.minorticks_on()
|
||||
ax2.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.gcf().autofmt_xdate()
|
||||
fig.tight_layout(pad=1)
|
||||
|
||||
plt.show()
|
||||
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def quantile(
|
||||
other_args: List[str], s_ticker: str, s_interval: str, df_stock: pd.DataFrame
|
||||
):
|
||||
"""Overlay Median & Quantile
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args: List[str]
|
||||
Argparse arguments
|
||||
s_ticker: str
|
||||
Ticker
|
||||
s_interval: str
|
||||
Data interval
|
||||
df_stock: pd.DataFrame
|
||||
Dataframe of dates and prices
|
||||
"""
|
||||
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(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="length",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--offset",
|
||||
action="store",
|
||||
dest="n_offset",
|
||||
type=check_positive,
|
||||
default=0,
|
||||
help="offset",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-q",
|
||||
"--quantile",
|
||||
action="store",
|
||||
dest="f_quantile",
|
||||
type=check_proportion_range,
|
||||
default=0.5,
|
||||
help="quantile",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
if s_interval == "1440min":
|
||||
plt.plot(df_stock.index, df_stock["Adj Close"].values, color="fuchsia")
|
||||
else:
|
||||
plt.plot(df_stock.index, df_stock["Close"].values, color="fuchsia")
|
||||
ax.set_title(f"{s_ticker} Median & Quantile")
|
||||
if s_interval == "1440min":
|
||||
df_ta_ = ta.median(
|
||||
close=df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
df_ta = ta.quantile(
|
||||
df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
q=ns_parser.f_quantile,
|
||||
).dropna()
|
||||
else:
|
||||
df_ta_ = ta.median(
|
||||
close=df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
df_ta = ta.quantile(
|
||||
df_stock["Close"],
|
||||
ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
q=ns_parser.f_quantile,
|
||||
).dropna()
|
||||
plt.plot(df_ta_.index, df_ta_.values, "g", lw=1, label="median")
|
||||
plt.plot(df_ta.index, df_ta.values, "b", lw=1, label="quantile")
|
||||
|
||||
plt.title(f"Median & Quantile on {s_ticker}")
|
||||
plt.xlim(df_stock.index[0], df_stock.index[-1])
|
||||
plt.xlabel("Time")
|
||||
plt.ylabel(f"{s_ticker} Price ($)")
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.minorticks_on()
|
||||
plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.gcf().autofmt_xdate()
|
||||
fig.tight_layout(pad=1)
|
||||
|
||||
plt.legend()
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def skew(other_args: List[str], s_ticker: str, s_interval: str, df_stock: pd.DataFrame):
|
||||
"""Skewness Indicator
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args:List[str]
|
||||
Argparse arguments
|
||||
s_ticker: str
|
||||
Ticker
|
||||
s_interval: str
|
||||
Stock time interval
|
||||
df_stock: pd.DataFrame
|
||||
Dataframe of prices
|
||||
"""
|
||||
|
||||
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(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="length",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-o",
|
||||
"--offset",
|
||||
action="store",
|
||||
dest="n_offset",
|
||||
type=check_positive,
|
||||
default=0,
|
||||
help="offset",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
# Daily
|
||||
if s_interval == "1440min":
|
||||
df_ta = ta.skew(
|
||||
close=df_stock["Adj Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
|
||||
# Intraday
|
||||
else:
|
||||
df_ta = ta.skew(
|
||||
close=df_stock["Close"],
|
||||
length=ns_parser.n_length,
|
||||
offset=ns_parser.n_offset,
|
||||
).dropna()
|
||||
|
||||
fig, axes = plt.subplots(2, 1, figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
ax = axes[0]
|
||||
ax.set_title(f"{s_ticker} Skewness Indicator")
|
||||
if s_interval == "1440min":
|
||||
ax.plot(df_stock.index, df_stock["Adj Close"].values, "fuchsia", lw=1)
|
||||
else:
|
||||
ax.plot(df_stock.index, df_stock["Close"].values, "fuchsia", lw=1)
|
||||
ax.set_xlim(df_stock.index[0], df_stock.index[-1])
|
||||
ax.set_ylabel("Share Price ($)")
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.minorticks_on()
|
||||
ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax2 = axes[1]
|
||||
ax2.plot(df_ta.index, df_ta.values, "b", lw=2, label="skew")
|
||||
|
||||
ax2.set_xlim(df_stock.index[0], df_stock.index[-1])
|
||||
ax2.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax2.minorticks_on()
|
||||
ax2.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.gcf().autofmt_xdate()
|
||||
fig.tight_layout(pad=1)
|
||||
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
156
gamestonk_terminal/common/quantitative_analysis/qa_model.py
Normal file
156
gamestonk_terminal/common/quantitative_analysis/qa_model.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""Quantitative Analysis Model"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import warnings
|
||||
from typing import Any, Tuple
|
||||
|
||||
import pandas as pd
|
||||
import statsmodels.api as sm
|
||||
from scipy import stats
|
||||
from statsmodels.tsa.seasonal import seasonal_decompose
|
||||
from statsmodels.tsa.stattools import adfuller, kpss
|
||||
|
||||
# TODO : Since these are common/ they should be independent of 'stock' info.
|
||||
# df_stock should be replaced with a generic df and a column variable
|
||||
|
||||
|
||||
def get_summary(df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Print summary statistics
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
Dataframe to get summary statistics for
|
||||
"""
|
||||
|
||||
df_stats = df.describe(percentiles=[0.1, 0.25, 0.5, 0.75, 0.9])
|
||||
df_stats.loc["var"] = df_stats.loc["std"] ** 2
|
||||
|
||||
return df_stats
|
||||
|
||||
|
||||
def get_seasonal_decomposition(
|
||||
df: pd.DataFrame, multiplicative: bool
|
||||
) -> Tuple[Any, pd.DataFrame, pd.DataFrame]:
|
||||
"""Perform seasonal decomposition
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df_stock : pd.DataFrame
|
||||
Dataframe of targeted data
|
||||
multiplicative : bool
|
||||
Boolean to indicate multiplication instead of addition
|
||||
|
||||
Returns
|
||||
-------
|
||||
result: Any
|
||||
Result of statsmodels seasonal_decompose
|
||||
cycle: pd.DataFrame
|
||||
Filtered cycle
|
||||
trend: pd.DataFrame
|
||||
Filtered Trend
|
||||
"""
|
||||
seasonal_periods = 5
|
||||
# Hodrick-Prescott filter
|
||||
# See Ravn and Uhlig: http://home.uchicago.edu/~huhlig/papers/uhlig.ravn.res.2002.pdf
|
||||
lamb = 107360000000
|
||||
|
||||
model = ["additive", "multiplicative"][multiplicative]
|
||||
|
||||
result = seasonal_decompose(df, model=model, period=seasonal_periods)
|
||||
cycle, trend = sm.tsa.filters.hpfilter(
|
||||
result.trend[result.trend.notna().values], lamb=lamb
|
||||
)
|
||||
|
||||
return result, pd.DataFrame(cycle), pd.DataFrame(trend)
|
||||
|
||||
|
||||
def get_normality(data: pd.DataFrame) -> pd.DataFrame:
|
||||
"""
|
||||
Look at the distribution of returns and generate statistics on the relation to the normal curve.
|
||||
This function calculates skew and kurtosis (the third and fourth moments) and performs both
|
||||
a Jarque-Bera and Shapiro Wilk test to determine if data is normally distributed.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
Dataframe of targeted data
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe containing statistics of normality
|
||||
"""
|
||||
# Kurtosis
|
||||
# Measures height and sharpness of the central peak relative to that of a standard bell curve
|
||||
k, kpval = stats.kurtosistest(data)
|
||||
|
||||
# Skewness
|
||||
# Measure of the asymmetry of the probability distribution of a random variable about its mean
|
||||
s, spval = stats.skewtest(data)
|
||||
|
||||
# Jarque-Bera goodness of fit test on sample data
|
||||
# Tests if the sample data has the skewness and kurtosis matching a normal distribution
|
||||
jb, jbpval = stats.jarque_bera(data)
|
||||
|
||||
# Shapiro
|
||||
# The Shapiro-Wilk test tests the null hypothesis that the data was drawn from a normal distribution.
|
||||
sh, shpval = stats.shapiro(data)
|
||||
|
||||
# Kolmogorov-Smirnov
|
||||
# The one-sample test compares the underlying distribution F(x) of a sample against a given distribution G(x).
|
||||
# Comparing to normal here.
|
||||
ks, kspval = stats.kstest(data, "norm")
|
||||
|
||||
l_statistic = [k, s, jb, sh, ks]
|
||||
l_pvalue = [kpval, spval, jbpval, shpval, kspval]
|
||||
|
||||
return pd.DataFrame(
|
||||
[l_statistic, l_pvalue],
|
||||
columns=[
|
||||
"Kurtosis",
|
||||
"Skewness",
|
||||
"Jarque-Bera",
|
||||
"Shapiro-Wilk",
|
||||
"Kolmogorov-Smirnov",
|
||||
],
|
||||
index=["Statistic", "p-value"],
|
||||
)
|
||||
|
||||
|
||||
def get_unitroot(df: pd.DataFrame, fuller_reg: str, kpss_reg: str) -> pd.DataFrame:
|
||||
"""Calculate test statistics for unit roots
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
DataFrame of target variable
|
||||
fuller_reg : str
|
||||
Type of regression of ADF test
|
||||
kpss_reg : str
|
||||
Type of regression for KPSS test
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame
|
||||
Dataframe with results of ADF test and KPSS test
|
||||
"""
|
||||
# The Augmented Dickey-Fuller test
|
||||
# Used to test for a unit root in a univariate process in the presence of serial correlation.
|
||||
result = adfuller(df, regression=fuller_reg)
|
||||
cols = ["Test Statistic", "P-Value", "NLags", "Nobs", "ICBest"]
|
||||
vals = [result[0], result[1], result[2], result[3], result[5]]
|
||||
data = pd.DataFrame(data=vals, index=cols, columns=["ADF"])
|
||||
|
||||
# Kwiatkowski-Phillips-Schmidt-Shin test
|
||||
# Test for level or trend stationarity
|
||||
# This test seems to produce an Interpolation Error which says
|
||||
# The test statistic is outside of the range of p-values available in the
|
||||
# look-up table. The actual p-value is greater than the p-value returned.
|
||||
# Wrap this in catch_warnings to prevent
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
res2 = kpss(df, regression=kpss_reg, nlags="auto")
|
||||
vals2 = [res2[0], res2[1], res2[2], "", ""]
|
||||
data["KPSS"] = vals2
|
||||
return data
|
||||
499
gamestonk_terminal/common/quantitative_analysis/qa_view.py
Normal file
499
gamestonk_terminal/common/quantitative_analysis/qa_view.py
Normal file
@@ -0,0 +1,499 @@
|
||||
"""Quantitative Analysis View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import os
|
||||
from typing import Any
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import seaborn as sns
|
||||
import statsmodels.api as sm
|
||||
from colorama import Fore, Style
|
||||
from detecta import detect_cusum
|
||||
from matplotlib import gridspec
|
||||
from pandas.plotting import register_matplotlib_converters
|
||||
from scipy import stats
|
||||
from statsmodels.graphics.gofplots import qqplot
|
||||
from tabulate import tabulate
|
||||
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.common.quantitative_analysis import qa_model
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
|
||||
|
||||
register_matplotlib_converters()
|
||||
|
||||
# TODO : Since these are common/ they should be independent of 'stock' info.
|
||||
# df_stock should be replaced with a generic df and a column variable
|
||||
|
||||
|
||||
def color_red(val: Any) -> str:
|
||||
"""Adds red to dataframe value"""
|
||||
return Fore.RED + str(val) + Style.RESET_ALL
|
||||
|
||||
|
||||
def display_summary(df: pd.DataFrame, export: str):
|
||||
"""Show summary statistics
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df_stock : pd.DataFrame
|
||||
DataFrame to get statistics of
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
summary = qa_model.get_summary(df)
|
||||
|
||||
print(
|
||||
tabulate(
|
||||
summary, headers=summary.columns, tablefmt="fancy_grid", floatfmt=".3f"
|
||||
),
|
||||
"\n",
|
||||
)
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"summary",
|
||||
summary,
|
||||
)
|
||||
|
||||
|
||||
def display_hist(
|
||||
name: str,
|
||||
df: pd.DataFrame,
|
||||
target: str,
|
||||
bins: int,
|
||||
):
|
||||
"""Generate of histogram of data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Name of dataset
|
||||
df : pd.DataFrame
|
||||
Dataframe to look at
|
||||
target : str
|
||||
Data column to get histogram of
|
||||
bins : int
|
||||
Number of bins in histogram
|
||||
"""
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
data = df[target]
|
||||
start = df.index[0]
|
||||
|
||||
sns.histplot(data, bins=bins, kde=True, ax=ax, stat="proportion")
|
||||
sns.rugplot(data, c="r", ax=ax)
|
||||
|
||||
ax.set_title(f"Histogram of {name} {target} from {start.strftime('%Y-%m-%d')}")
|
||||
ax.set_xlabel("Share Price")
|
||||
ax.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
fig.tight_layout()
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
|
||||
def display_cdf(
|
||||
name: str,
|
||||
df: pd.DataFrame,
|
||||
target: str,
|
||||
export: str = "",
|
||||
):
|
||||
"""Plot Cumulative Distribution Function
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Name of dataset
|
||||
df : pd.DataFrame
|
||||
Dataframe to look at
|
||||
target : str
|
||||
Data column
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
data = df[target]
|
||||
start = df.index[0]
|
||||
|
||||
cdf = data.value_counts().sort_index().div(len(data)).cumsum()
|
||||
cdf.plot(lw=2)
|
||||
plt.title(
|
||||
f"Cumulative Distribution Function of {name} {target} from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
plt.ylabel("Probability")
|
||||
plt.xlabel(target)
|
||||
minVal = data.values.min()
|
||||
q25 = np.quantile(data.values, 0.25)
|
||||
medianVal = np.quantile(data.values, 0.5)
|
||||
q75 = np.quantile(data.values, 0.75)
|
||||
labels = [
|
||||
(minVal, q25),
|
||||
(0.25, 0.25),
|
||||
"r",
|
||||
(q25, q25),
|
||||
(0, 0.25),
|
||||
"r",
|
||||
(minVal, medianVal),
|
||||
(0.5, 0.5),
|
||||
"r",
|
||||
(medianVal, medianVal),
|
||||
(0, 0.5),
|
||||
"r",
|
||||
(minVal, q75),
|
||||
(0.75, 0.75),
|
||||
"r",
|
||||
(q75, q75),
|
||||
(0, 0.75),
|
||||
"r",
|
||||
]
|
||||
plt.plot(*labels, ls="--")
|
||||
plt.text(minVal + (q25 - minVal) / 2, 0.27, "Q1", color="r", fontweight="bold")
|
||||
plt.text(
|
||||
minVal + (medianVal - minVal) / 2,
|
||||
0.52,
|
||||
"Median",
|
||||
color="r",
|
||||
fontweight="bold",
|
||||
)
|
||||
plt.text(minVal + (q75 - minVal) / 2, 0.77, "Q3", color="r", fontweight="bold")
|
||||
plt.xlim(cdf.index[0], cdf.index[-1])
|
||||
plt.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"cdf",
|
||||
pd.DataFrame(cdf),
|
||||
)
|
||||
|
||||
|
||||
def display_bw(
|
||||
name: str,
|
||||
df: pd.DataFrame,
|
||||
target: str,
|
||||
yearly: bool,
|
||||
):
|
||||
"""Show box and whisker plots
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Name of dataset
|
||||
df : pd.DataFrame
|
||||
Dataframe to look at
|
||||
target : str
|
||||
Data column to look at
|
||||
yearly : bool
|
||||
Flag to indicate yearly accumulation
|
||||
"""
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
data = df[target]
|
||||
start = df.index[0]
|
||||
sns.set(style="whitegrid")
|
||||
if yearly:
|
||||
box_plot = sns.boxplot(x=data.index.year, y=data)
|
||||
else:
|
||||
box_plot = sns.boxplot(x=data.index.month, y=data)
|
||||
|
||||
box_plot.set(
|
||||
xlabel=["Month", "Year"][yearly],
|
||||
ylabel=target,
|
||||
title=f"{['Month','Year'][yearly]} BoxPlot of {name} {target} from {start.strftime('%Y-%m-%d')}",
|
||||
)
|
||||
l_months = [
|
||||
"Jan",
|
||||
"Feb",
|
||||
"Mar",
|
||||
"Apr",
|
||||
"May",
|
||||
"Jun",
|
||||
"Jul",
|
||||
"Aug",
|
||||
"Sep",
|
||||
"Oct",
|
||||
"Nov",
|
||||
"Dec",
|
||||
]
|
||||
l_ticks = list()
|
||||
if not yearly:
|
||||
for val in box_plot.get_xticklabels():
|
||||
l_ticks.append(l_months[int(val.get_text()) - 1])
|
||||
box_plot.set_xticklabels(l_ticks)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
|
||||
def display_acf(name: str, df: pd.DataFrame, target: str, lags: int):
|
||||
"""Show Auto and Partial Auto Correlation of returns and change in returns
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Name of dataset
|
||||
df : pd.DataFrame
|
||||
Dataframe to look at
|
||||
target : str
|
||||
Data column to look at
|
||||
lags : int
|
||||
Max number of lags to look at
|
||||
"""
|
||||
df = df[target]
|
||||
start = df.index[0]
|
||||
fig = plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True)
|
||||
spec = gridspec.GridSpec(ncols=2, nrows=2, figure=fig)
|
||||
|
||||
# Diff Auto-correlation function for original time series
|
||||
ax_acf = fig.add_subplot(spec[0, 0])
|
||||
sm.graphics.tsa.plot_acf(np.diff(np.diff(df.values)), lags=lags, ax=ax_acf)
|
||||
plt.title(f"{name} Returns Auto-Correlation from {start.strftime('%Y-%m-%d')}")
|
||||
# Diff Partial auto-correlation function for original time series
|
||||
ax_pacf = fig.add_subplot(spec[0, 1])
|
||||
sm.graphics.tsa.plot_pacf(np.diff(np.diff(df.values)), lags=lags, ax=ax_pacf)
|
||||
plt.title(
|
||||
f"{name} Returns Partial Auto-Correlation from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
|
||||
# Diff Diff Auto-correlation function for original time series
|
||||
ax_acf = fig.add_subplot(spec[1, 0])
|
||||
sm.graphics.tsa.plot_acf(np.diff(np.diff(df.values)), lags=lags, ax=ax_acf)
|
||||
plt.title(
|
||||
f"Change in {name} Returns Auto-Correlation from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
# Diff Diff Partial auto-correlation function for original time series
|
||||
ax_pacf = fig.add_subplot(spec[1, 1])
|
||||
sm.graphics.tsa.plot_pacf(np.diff(np.diff(df.values)), lags=lags, ax=ax_pacf)
|
||||
plt.title(
|
||||
f"Change in {name}) Returns Partial Auto-Correlation from {start.strftime('%Y-%m-%d')}"
|
||||
)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
|
||||
def display_cusum(df: pd.DataFrame, target: str, threshold: float, drift: float):
|
||||
"""Cumulative sum algorithm (CUSUM) to detect abrupt changes in data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
Dataframe
|
||||
target : str
|
||||
Column of data to look at
|
||||
threshold : float
|
||||
Threshold value
|
||||
drift : float
|
||||
Drift parameter
|
||||
"""
|
||||
detect_cusum(df[target].values, threshold, drift, True, True)
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
|
||||
def display_seasonal(
|
||||
name: str,
|
||||
df: pd.DataFrame,
|
||||
target: str,
|
||||
multiplicative: bool = False,
|
||||
export: str = "",
|
||||
):
|
||||
"""Display seasonal decomposition data
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Name of dataset
|
||||
df : pd.DataFrame
|
||||
DataFrame
|
||||
target : str
|
||||
Column of data to look at
|
||||
multiplicative : bool
|
||||
Boolean to indicate multiplication instead of addition
|
||||
export : str
|
||||
Format to export trend and cycle df
|
||||
"""
|
||||
data = df[target]
|
||||
fig = plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True)
|
||||
spec = gridspec.GridSpec(ncols=4, nrows=5, figure=fig)
|
||||
fig.add_subplot(spec[0, :])
|
||||
plt.plot(data.index, data.values)
|
||||
plt.title(name + " (Time-Series)")
|
||||
|
||||
result, cycle, trend = qa_model.get_seasonal_decomposition(data, multiplicative)
|
||||
|
||||
# Multiplicative model
|
||||
fig.add_subplot(spec[1, :4])
|
||||
plt.plot(result.trend, lw=2, c="purple")
|
||||
plt.xlim([data.index[0], data.index[-1]])
|
||||
plt.title("Cyclic-Trend")
|
||||
|
||||
fig.add_subplot(spec[2, 0:2])
|
||||
plt.plot(trend, lw=2, c="tab:blue")
|
||||
plt.xlim([data.index[0], data.index[-1]])
|
||||
plt.title("Trend component")
|
||||
|
||||
fig.add_subplot(spec[2, 2:])
|
||||
plt.plot(cycle, lw=2, c="green")
|
||||
plt.xlim([data.index[0], data.index[-1]])
|
||||
plt.title("Cycle component")
|
||||
|
||||
fig.add_subplot(spec[3, :])
|
||||
plt.plot(result.seasonal, lw=2, c="orange")
|
||||
plt.xlim([data.index[0], data.index[-1]])
|
||||
plt.title("Seasonal effect")
|
||||
|
||||
fig.add_subplot(spec[4, :])
|
||||
plt.plot(result.resid, lw=2, c="red")
|
||||
plt.xlim([data.index[0], data.index[-1]])
|
||||
plt.title("Residuals")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
# From # https://otexts.com/fpp2/seasonal-strength.html
|
||||
|
||||
print("Time-Series Level is " + str(round(data.mean(), 2)))
|
||||
|
||||
Ft = max(0, 1 - np.var(result.resid)) / np.var(result.trend + result.resid)
|
||||
print("Strength of Trend: %.4f" % Ft)
|
||||
Fs = max(
|
||||
0,
|
||||
1 - np.var(result.resid) / np.var(result.seasonal + result.resid),
|
||||
)
|
||||
print("Strength of Seasonality: %.4f" % Fs, "\n")
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"summary",
|
||||
cycle.join(trend),
|
||||
)
|
||||
|
||||
|
||||
def display_normality(df: pd.DataFrame, target: str, export: str = ""):
|
||||
"""View normality statistics
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
DataFrame
|
||||
target : str
|
||||
Column in data to look at
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
data = df[target]
|
||||
normal = qa_model.get_normality(data)
|
||||
stats1 = normal.copy()
|
||||
stats1.loc[:, stats1.iloc[1, :] > 0.05] = stats1.loc[
|
||||
:, stats1.iloc[1, :] > 0.05
|
||||
].apply(lambda x: color_red(x[0]), axis=1)
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
stats1,
|
||||
showindex=True,
|
||||
headers=normal.columns,
|
||||
tablefmt="fancy_grid",
|
||||
floatfmt=".4f",
|
||||
),
|
||||
"\n",
|
||||
)
|
||||
else:
|
||||
print(normal.round(4).to_string(), "\n")
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"normality",
|
||||
normal,
|
||||
)
|
||||
|
||||
|
||||
def display_qqplot(name: str, df: pd.DataFrame, target: str):
|
||||
"""Show QQ plot for data against normal quantiles
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Stock ticker
|
||||
df : pd.DataFrame
|
||||
Dataframe
|
||||
target : str
|
||||
Column in data to look at
|
||||
"""
|
||||
data = df[target]
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
qqplot(data, stats.distributions.norm, fit=True, line="45", ax=ax)
|
||||
ax.set_title(f"Q-Q plot for {name} {target}")
|
||||
ax.set_ylabel("Sample quantiles")
|
||||
ax.set_xlabel("Theoretical quantiles")
|
||||
ax.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
fig.tight_layout(pad=1)
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
|
||||
def display_unitroot(
|
||||
df: pd.DataFrame, target: str, fuller_reg: str, kpss_reg: str, export: str = ""
|
||||
):
|
||||
"""Show unit root test calculations
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
DataFrame
|
||||
target : str
|
||||
Column of data to look at
|
||||
fuller_reg : str
|
||||
Type of regression of ADF test
|
||||
kpss_reg : str
|
||||
Type of regression for KPSS test
|
||||
export : str
|
||||
Format for exporting data
|
||||
"""
|
||||
df = df[target]
|
||||
data = qa_model.get_unitroot(df, fuller_reg, kpss_reg)
|
||||
if gtff.USE_TABULATE_DF:
|
||||
print(
|
||||
tabulate(
|
||||
data,
|
||||
showindex=True,
|
||||
headers=data.columns,
|
||||
tablefmt="fancy_grid",
|
||||
floatfmt=".4f",
|
||||
),
|
||||
"\n",
|
||||
)
|
||||
else:
|
||||
print(data.round(4).to_string(), "\n")
|
||||
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"unitroot",
|
||||
data,
|
||||
)
|
||||
107
gamestonk_terminal/common/quantitative_analysis/rolling_model.py
Normal file
107
gamestonk_terminal/common/quantitative_analysis/rolling_model.py
Normal file
@@ -0,0 +1,107 @@
|
||||
"""Rolling Statistics"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
from typing import Tuple
|
||||
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
|
||||
|
||||
def get_rolling_avg(df: pd.DataFrame, length: int) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""Return rolling mean and standard deviation
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df_stock : pd.DataFrame
|
||||
Dataframe of target data
|
||||
length : int
|
||||
Length of rolling window
|
||||
|
||||
Returns
|
||||
-------
|
||||
pd.DataFrame :
|
||||
Dataframe of rolling mean
|
||||
pd.DataFrame :
|
||||
Dataframe of rolling standard deviation
|
||||
"""
|
||||
rolling_mean = df.rolling(length, center=True, min_periods=1).mean()
|
||||
rolling_std = df.rolling(length, center=True, min_periods=1).std()
|
||||
|
||||
return pd.DataFrame(rolling_mean), pd.DataFrame(rolling_std)
|
||||
|
||||
|
||||
def get_spread(df: pd.DataFrame, length: int) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""Standard Deviation and Variance
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df_stock : pd.DataFrame
|
||||
DataFrame of targeted data
|
||||
|
||||
Returns
|
||||
-------
|
||||
df_sd : pd.DataFrame
|
||||
Dataframe of rolling standard deviation
|
||||
df_var : pd.DataFrame
|
||||
Dataframe of rolling standard deviation
|
||||
"""
|
||||
df_sd = ta.stdev(
|
||||
close=df,
|
||||
length=length,
|
||||
).dropna()
|
||||
df_var = ta.variance(
|
||||
close=df,
|
||||
length=length,
|
||||
).dropna()
|
||||
|
||||
return pd.DataFrame(df_sd), pd.DataFrame(df_var)
|
||||
|
||||
|
||||
def get_quantile(
|
||||
df: pd.DataFrame, length: int, quantile_pct: float
|
||||
) -> Tuple[pd.DataFrame, pd.DataFrame]:
|
||||
"""Overlay Median & Quantile
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df : pd.DataFrame
|
||||
Dataframe of targeted data
|
||||
length : int
|
||||
Length of window
|
||||
quantile : float
|
||||
Quantile to display
|
||||
|
||||
Returns
|
||||
-------
|
||||
df_med : pd.DataFrame
|
||||
Dataframe of median prices over window
|
||||
df_quantile : pd.DataFrame
|
||||
Dataframe of gievn quantile prices over window
|
||||
"""
|
||||
df_med = ta.median(close=df, length=length).dropna()
|
||||
df_quantile = ta.quantile(
|
||||
df,
|
||||
length=length,
|
||||
q=quantile_pct,
|
||||
).dropna()
|
||||
|
||||
return pd.DataFrame(df_med), pd.DataFrame(df_quantile)
|
||||
|
||||
|
||||
def get_skew(df: pd.DataFrame, length: int) -> pd.DataFrame:
|
||||
"""Skewness Indicator
|
||||
|
||||
Parameters
|
||||
----------
|
||||
df_stock : pd.DataFrame
|
||||
Dataframe of targeted data
|
||||
length : int
|
||||
Length of window
|
||||
|
||||
Returns
|
||||
-------
|
||||
df_skew : pd.DataFrame
|
||||
Dataframe of rolling skew
|
||||
"""
|
||||
df_skew = ta.skew(close=df, length=length).dropna()
|
||||
return df_skew
|
||||
255
gamestonk_terminal/common/quantitative_analysis/rolling_view.py
Normal file
255
gamestonk_terminal/common/quantitative_analysis/rolling_view.py
Normal file
@@ -0,0 +1,255 @@
|
||||
"""Rolling Statistics View"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import os
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
from pandas.plotting import register_matplotlib_converters
|
||||
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.common.quantitative_analysis import rolling_model
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal.helper_funcs import export_data, plot_autoscale
|
||||
|
||||
register_matplotlib_converters()
|
||||
|
||||
|
||||
def display_mean_std(
|
||||
name: str, df: pd.DataFrame, target: str, length: int, export: str = ""
|
||||
):
|
||||
"""View rolling spread
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Stock ticker
|
||||
df : pd.DataFrame
|
||||
Dataframe
|
||||
target : str
|
||||
Column in data to look at
|
||||
length : int
|
||||
Length of window
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
data = df[target]
|
||||
rolling_mean, rolling_std = rolling_model.get_rolling_avg(data, length)
|
||||
fig, axMean = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
axMean.plot(
|
||||
data.index,
|
||||
data.values,
|
||||
label=name,
|
||||
linewidth=2,
|
||||
color="black",
|
||||
)
|
||||
axMean.plot(rolling_mean, linestyle="--", linewidth=3, color="blue")
|
||||
axMean.set_xlabel("Time")
|
||||
axMean.set_ylabel("Values", color="blue")
|
||||
axMean.legend(["Real values", "Rolling Mean"], loc=2)
|
||||
axMean.tick_params(axis="y", labelcolor="blue")
|
||||
axStd = axMean.twinx()
|
||||
axStd.plot(
|
||||
rolling_std,
|
||||
label="Rolling std",
|
||||
linestyle="--",
|
||||
color="green",
|
||||
linewidth=3,
|
||||
alpha=0.6,
|
||||
)
|
||||
axStd.set_ylabel("Std Deviation")
|
||||
axStd.legend(["Rolling std"], loc=1)
|
||||
axStd.set_ylabel(f"{target} standard deviation", color="green")
|
||||
axStd.tick_params(axis="y", labelcolor="green")
|
||||
axMean.set_title(
|
||||
"Rolling mean and std with window "
|
||||
+ str(length)
|
||||
+ " applied to "
|
||||
+ name
|
||||
+ target
|
||||
)
|
||||
axMean.set_xlim([data.index[0], data.index[-1]])
|
||||
axMean.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
fig.tight_layout(pad=1)
|
||||
plt.gcf().autofmt_xdate()
|
||||
plt.show()
|
||||
print("")
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"rolling",
|
||||
rolling_mean.join(rolling_std, lsuffix="_mean", rsuffix="_sd"),
|
||||
)
|
||||
|
||||
|
||||
def display_spread(
|
||||
name: str, df: pd.DataFrame, target: str, length: int, export: str = ""
|
||||
):
|
||||
"""View rolling spread
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Stock ticker
|
||||
df : pd.DataFrame
|
||||
Dataframe
|
||||
target: str
|
||||
Column in data to look at
|
||||
length : int
|
||||
Length of window
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
data = df[target]
|
||||
df_sd, df_var = rolling_model.get_spread(data, length)
|
||||
fig, axes = plt.subplots(3, 1, figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
ax = axes[0]
|
||||
ax.set_title(f"{name} Spread")
|
||||
ax.plot(data.index, data.values, "fuchsia", lw=1)
|
||||
ax.set_xlim(data.index[0], data.index[-1])
|
||||
ax.set_ylabel("Value")
|
||||
ax.set_title(f"Spread of {name} {target}")
|
||||
ax.yaxis.set_label_position("right")
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.minorticks_on()
|
||||
ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax1 = axes[1]
|
||||
ax1.plot(df_sd.index, df_sd.values, "b", lw=1, label="stdev")
|
||||
ax1.set_xlim(data.index[0], data.index[-1])
|
||||
ax1.set_ylabel("Stdev")
|
||||
ax1.yaxis.set_label_position("right")
|
||||
ax1.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax1.minorticks_on()
|
||||
ax1.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax2 = axes[2]
|
||||
ax2.plot(df_var.index, df_var.values, "g", lw=1, label="variance")
|
||||
ax2.set_xlim(data.index[0], data.index[-1])
|
||||
ax2.set_ylabel("Variance")
|
||||
ax2.yaxis.set_label_position("right")
|
||||
ax2.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.gcf().autofmt_xdate()
|
||||
fig.tight_layout(pad=1)
|
||||
plt.show()
|
||||
print("")
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"spread",
|
||||
df_sd.join(df_var, lsuffix="_sd", rsuffix="_var"),
|
||||
)
|
||||
|
||||
|
||||
def display_quantile(
|
||||
name: str,
|
||||
df: pd.DataFrame,
|
||||
target: str,
|
||||
length: int,
|
||||
quantile: float,
|
||||
export: str = "",
|
||||
):
|
||||
"""View rolling quantile
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Stock ticker
|
||||
df : pd.DataFrame
|
||||
Dataframe
|
||||
target : str
|
||||
Column in data to look at
|
||||
length : int
|
||||
Length of window
|
||||
quantle : float
|
||||
Quantil eto get
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
data = df[target]
|
||||
df_med, df_quantile = rolling_model.get_quantile(data, length, quantile)
|
||||
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
ax.plot(data.index, data.values, color="fuchsia")
|
||||
ax.set_title(f"{name} Median & Quantile")
|
||||
ax.plot(df_med.index, df_med.values, "g", lw=1, label="median")
|
||||
ax.plot(df_quantile.index, df_quantile.values, "b", lw=1, label="quantile")
|
||||
|
||||
ax.set_title(f"Median & Quantile on {name}")
|
||||
ax.set_xlim(data.index[0], data.index[-1])
|
||||
ax.set_xlabel("Time")
|
||||
ax.set_ylabel(f"{name} Value")
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.gcf().autofmt_xdate()
|
||||
fig.tight_layout(pad=1)
|
||||
|
||||
plt.legend()
|
||||
plt.show()
|
||||
print("")
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"quantile",
|
||||
df_med.join(df_quantile),
|
||||
)
|
||||
|
||||
|
||||
def display_skew(
|
||||
name: str, df: pd.DataFrame, target: str, length: int, export: str = ""
|
||||
):
|
||||
"""View rolling skew
|
||||
|
||||
Parameters
|
||||
----------
|
||||
name : str
|
||||
Stock ticker
|
||||
df : pd.DataFrame
|
||||
Dataframe
|
||||
target : str
|
||||
Column in data to look at
|
||||
length : int
|
||||
Length of window
|
||||
export : str
|
||||
Format to export data
|
||||
"""
|
||||
data = df[target]
|
||||
df_skew = rolling_model.get_skew(data, length)
|
||||
fig, axes = plt.subplots(2, 1, figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
ax = axes[0]
|
||||
ax.set_title(f"{name} Skewness Indicator")
|
||||
ax.plot(data.index, data.values, "fuchsia", lw=1)
|
||||
ax.set_xlim(data.index[0], data.index[-1])
|
||||
ax.set_ylabel(f"{target}")
|
||||
ax.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
ax.minorticks_on()
|
||||
ax.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
ax2 = axes[1]
|
||||
ax2.plot(df_skew.index, df_skew.values, "b", lw=2, label="skew")
|
||||
|
||||
ax2.set_xlim(data.index[0], data.index[-1])
|
||||
ax2.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.gcf().autofmt_xdate()
|
||||
fig.tight_layout(pad=1)
|
||||
|
||||
plt.legend()
|
||||
plt.show()
|
||||
|
||||
print("")
|
||||
export_data(
|
||||
export,
|
||||
os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
|
||||
"skew",
|
||||
df_skew,
|
||||
)
|
||||
@@ -1,573 +0,0 @@
|
||||
""" Residuals API """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
from typing import List
|
||||
from collections import OrderedDict
|
||||
from matplotlib import pyplot as plt
|
||||
import pandas as pd
|
||||
from pandas.plotting import register_matplotlib_converters
|
||||
import seaborn as sns
|
||||
from scipy import stats
|
||||
import statsmodels.api as sm
|
||||
|
||||
# pylint: disable=R0402
|
||||
import matplotlib.gridspec as gridspec
|
||||
from statsmodels.graphics.gofplots import qqplot
|
||||
from statsmodels.tsa.stattools import adfuller, kpss, bds
|
||||
from statsmodels.stats.diagnostic import het_arch
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
parse_known_args_and_warn,
|
||||
plot_autoscale,
|
||||
check_positive,
|
||||
)
|
||||
from gamestonk_terminal.config_plot import PLOT_DPI
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
|
||||
|
||||
register_matplotlib_converters()
|
||||
|
||||
|
||||
def fit(
|
||||
other_args: List[str],
|
||||
ticker: str,
|
||||
stock: pd.Series,
|
||||
model_name: str,
|
||||
model: pd.Series,
|
||||
):
|
||||
"""Plot model fitting
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.Series
|
||||
Stock data
|
||||
model_name : str
|
||||
Model fitting name in use
|
||||
model : pd.Series
|
||||
Model fit data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="fit",
|
||||
description="""
|
||||
Plot model fitting
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
plt.plot(stock)
|
||||
plt.plot(model)
|
||||
plt.title(f"{model_name} model fit on {ticker}")
|
||||
plt.xlim(stock.index[0], stock.index[-1])
|
||||
plt.xlabel("Time")
|
||||
plt.ylabel("Share Price ($)")
|
||||
plt.legend([ticker, model_name])
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.minorticks_on()
|
||||
plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def res(
|
||||
other_args: List[str],
|
||||
ticker: str,
|
||||
stock: pd.Series,
|
||||
model_name: str,
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Plot residuals
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
stock : pd.Series
|
||||
Stock data
|
||||
model_name : str
|
||||
Model fitting name in use
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="res",
|
||||
description="""
|
||||
Plot residuals
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
|
||||
|
||||
plt.plot(stock[1:].index, residuals)
|
||||
plt.title(f"Residuals from {model_name} model fit on {ticker}")
|
||||
plt.xlim(stock[1:].index[0], stock.index[-1])
|
||||
plt.xlabel("Time")
|
||||
plt.ylabel("Share Price ($)")
|
||||
plt.grid(b=True, which="major", color="#666666", linestyle="-")
|
||||
plt.minorticks_on()
|
||||
plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def hist(
|
||||
other_args: List[str],
|
||||
ticker: str,
|
||||
model_name: str,
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Histogram and density curve
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
model_name : str
|
||||
Model fitting name in use
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="hist",
|
||||
description="""
|
||||
Histogram and density curve
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True)
|
||||
|
||||
sns.distplot(
|
||||
residuals,
|
||||
bins=35,
|
||||
color="blue",
|
||||
hist=True,
|
||||
hist_kws={"edgecolor": "black"},
|
||||
kde=True,
|
||||
kde_kws={"color": "black", "lw": 3, "label": "KDE"},
|
||||
rug=True,
|
||||
rug_kws={"edgecolor": "orange"},
|
||||
)
|
||||
plt.title(f"Histogram with Density from {model_name} fit on {ticker}")
|
||||
plt.ylabel("Density")
|
||||
plt.xlabel("Share Price")
|
||||
plt.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def plot_qqplot(
|
||||
other_args: List[str],
|
||||
ticker: str,
|
||||
model_name: str,
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Qqplot time series against a standard normal curve
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
model_name : str
|
||||
Model fitting name in use
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="qqplot",
|
||||
description="""
|
||||
Qqplot time series against a standard normal curve
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True)
|
||||
|
||||
qqplot(residuals, stats.distributions.norm, fit=True, line="45", ax=plt.gca())
|
||||
plt.title(f"Q-Q plot residuals from {model_name} on {ticker}")
|
||||
plt.ylabel("Sample quantiles")
|
||||
plt.xlabel("Theoretical quantiles")
|
||||
plt.grid(True)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def acf(
|
||||
other_args: List[str],
|
||||
ticker: str,
|
||||
model_name: str,
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Plot (partial) auto-correlation function
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
ticker : str
|
||||
Ticker of the stock
|
||||
model_name : str
|
||||
Model fitting name in use
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="acf",
|
||||
description="""
|
||||
Plot (partial) auto-correlation function
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--lags",
|
||||
dest="lags",
|
||||
type=check_positive,
|
||||
default=40,
|
||||
help="maximum lags to display in plots",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
fig = plt.figure(
|
||||
figsize=plot_autoscale(), dpi=PLOT_DPI, constrained_layout=True
|
||||
)
|
||||
spec = gridspec.GridSpec(ncols=1, nrows=2, figure=fig)
|
||||
|
||||
# Auto-correlation function for original time series
|
||||
ax_acf = fig.add_subplot(spec[0, 0])
|
||||
sm.graphics.tsa.plot_acf(residuals, lags=ns_parser.lags, ax=ax_acf)
|
||||
plt.title(
|
||||
f"Auto-Correlation function applied to Residuals from {model_name} on {ticker}"
|
||||
)
|
||||
# Partial auto-correlation function for original time series
|
||||
ax_pacf = fig.add_subplot(spec[1, 0])
|
||||
sm.graphics.tsa.plot_pacf(residuals, lags=ns_parser.lags, ax=ax_pacf)
|
||||
plt.title(
|
||||
f"Partial Auto-Correlation function applied to Residuals from {model_name} on {ticker}"
|
||||
)
|
||||
|
||||
if gtff.USE_ION:
|
||||
plt.ion()
|
||||
|
||||
plt.show()
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def normality(
|
||||
other_args: List[str],
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Normality tests
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="normality",
|
||||
description="""
|
||||
Normality tests
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
# Kurtosis
|
||||
# Measures height and sharpness of the central peak relative to that of a standard bell curve
|
||||
k, kpval = stats.kurtosistest(residuals)
|
||||
|
||||
# Skewness
|
||||
# Measure of the asymmetry of the probability distribution of a random variable about its mean
|
||||
s, spval = stats.skewtest(residuals)
|
||||
|
||||
# Jarque-Bera goodness of fit test on sample data
|
||||
# Tests if the sample data has the skewness and kurtosis matching a normal distribution
|
||||
jb, jbpval = stats.jarque_bera(residuals)
|
||||
|
||||
# Shapiro
|
||||
# The Shapiro-Wilk test tests the null hypothesis that the data was drawn from a normal distribution.
|
||||
sh, shpval = stats.shapiro(residuals)
|
||||
|
||||
l_statistic = [k, s, jb, sh]
|
||||
l_pvalue = [kpval, spval, jbpval, shpval]
|
||||
|
||||
print(
|
||||
pd.DataFrame(
|
||||
[l_statistic, l_pvalue],
|
||||
columns=["Kurtosis", "Skewness", "Jarque-Bera", "Shapiro-Wilk"],
|
||||
index=["Statistic", "p-value"],
|
||||
)
|
||||
.round(5)
|
||||
.to_string()
|
||||
)
|
||||
|
||||
print("")
|
||||
kurtosis_val = stats.kurtosis(residuals, fisher=True)
|
||||
print("Kurtosis value: %.4f" % kurtosis_val)
|
||||
skew_val = stats.skew(residuals)
|
||||
print("Skewness value: %.4f" % skew_val)
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def goodness(
|
||||
other_args: List[str],
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Goodness of fit tests
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="goodness",
|
||||
description="""
|
||||
Goodness of fit tests
|
||||
""",
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
# Kolmogorov-Smirnov Test goodness of fit test on sample data
|
||||
ks, kspval = stats.kstest(residuals, "norm")
|
||||
print("Kolmogorov-Smirnov Test")
|
||||
print("Statistic: %.4f" % ks)
|
||||
print("p-value: %.4f" % kspval)
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def arch(
|
||||
other_args: List[str],
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Autoregressive conditional heteroscedasticity with Engle's test
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="arch",
|
||||
description="""
|
||||
Autoregressive conditional heteroscedasticity with Engle's test
|
||||
""",
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
# Engle's Test for Autoregressive Conditional Heteroscedasticity (ARCH)
|
||||
lm, lmpval, fval, fpval = het_arch(residuals)
|
||||
print("Lagrange multiplier test statistic")
|
||||
print("Statistic: %.4f" % lm)
|
||||
print("p-value: %.4f" % lmpval)
|
||||
print("")
|
||||
print("fstatistic for F test")
|
||||
print("Statistic: %.4f" % fval)
|
||||
print("p-value: %.4f" % fpval)
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def unitroot(
|
||||
other_args: List[str],
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Unit root test / stationarity (ADF, KPSS)
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="arch",
|
||||
description="""
|
||||
Unit root test / stationarity (ADF, KPSS)
|
||||
""",
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
# The Augmented Dickey-Fuller test
|
||||
# Used to test for a unit root in a univariate process in the presence of serial correlation.
|
||||
# regression{‘c’,’ct’,’ctt’,’nc’} 'c' - Constant and 't'-trend order to include in regression
|
||||
# Note: 'ct' - The data is stationary around a trend
|
||||
result = adfuller(residuals, regression="c")
|
||||
print("Augmented Dickey Fuller Test")
|
||||
print("ADF Statistic: %.4f" % result[0])
|
||||
print("p-value: %.4f" % result[1])
|
||||
print("Used lags: %d" % result[2])
|
||||
print("Num obs: %d" % result[3])
|
||||
print("Critical Values:")
|
||||
d = OrderedDict(sorted(result[4].items(), key=lambda t: t[1]))
|
||||
for key, value in d.items():
|
||||
print(f"\t{key}: {value:.3f}")
|
||||
print("")
|
||||
|
||||
# Kwiatkowski-Phillips-Schmidt-Shin test
|
||||
# Test for level or trend stationarity
|
||||
# Note: regressionstr{‘c’, ‘ct’}
|
||||
# regressionstr{‘c’, ‘ct’} where:
|
||||
# ‘c’ : The data is stationary around a constant (default).
|
||||
# ‘ct’ : The data is stationary around a trend.
|
||||
# lags{None, ‘auto’, ‘legacy’}
|
||||
# see: https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.kpss.html
|
||||
print("Kwiatkowski-Phillips-Schmidt-Shin Test")
|
||||
result = kpss(residuals, regression="c", nlags="auto")
|
||||
print("KPSS Statistic: %.4f" % result[0])
|
||||
print("Critical Values:")
|
||||
d = OrderedDict(sorted(result[3].items(), key=lambda t: t[1], reverse=True))
|
||||
for key, value in d.items():
|
||||
print(f"\t{key}: {value:.3f}")
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
|
||||
|
||||
def independence(
|
||||
other_args: List[str],
|
||||
residuals: List[float],
|
||||
):
|
||||
"""Tests independent and identically distributed (i.i.d.) time series (BDS)
|
||||
|
||||
Parameters
|
||||
----------
|
||||
other_args : str
|
||||
Command line arguments to be processed with argparse
|
||||
residuals : List[float]
|
||||
Residuals data
|
||||
"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="independence",
|
||||
description="""
|
||||
Tests independent and identically distributed (i.i.d.) time series (BDS)
|
||||
""",
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
result = bds(residuals, max_dim=6)
|
||||
print("BDS Test")
|
||||
print(f"Dim 2: z-static {result[0][0]:.4f} Prob {result[1][0]:.4f}")
|
||||
print(f"Dim 3: z-static {result[0][1]:.4f} Prob {result[1][1]:.4f}")
|
||||
print(f"Dim 4: z-static {result[0][2]:.4f} Prob {result[1][2]:.4f}")
|
||||
print(f"Dim 5: z-static {result[0][3]:.4f} Prob {result[1][3]:.4f}")
|
||||
print(f"Dim 6: z-static {result[0][4]:.4f} Prob {result[1][4]:.4f}")
|
||||
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
return
|
||||
@@ -1,152 +0,0 @@
|
||||
""" Residuals Model """
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
from typing import List
|
||||
import pandas as pd
|
||||
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 "", None, list()
|
||||
|
||||
model = pd.Series(stock.values[:-1], index=stock[1:].index)
|
||||
|
||||
model_name = "Naive"
|
||||
residuals = stock[1:].values - model.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 "", None, list()
|
||||
|
||||
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()
|
||||
@@ -1,6 +1,9 @@
|
||||
import os
|
||||
from distutils.util import strtobool
|
||||
|
||||
# Use tabulate to print dataframes
|
||||
USE_TABULATE_DF = strtobool(os.getenv("GTFF_USE_CLEAR_AFTER_CMD", "True"))
|
||||
|
||||
# Use clear console after each command
|
||||
USE_CLEAR_AFTER_CMD = strtobool(os.getenv("GTFF_USE_CLEAR_AFTER_CMD", "False"))
|
||||
|
||||
|
||||
@@ -48,7 +48,11 @@ def check_valid_path(path: str) -> str:
|
||||
if not os.path.exists(
|
||||
os.path.abspath(
|
||||
os.path.join(
|
||||
"gamestonk_terminal", "portfolio_analysis", "portfolios", f"{path}.csv"
|
||||
"gamestonk_terminal",
|
||||
"portfolio",
|
||||
"portfolio_analysis",
|
||||
"portfolios",
|
||||
f"{path}.csv",
|
||||
)
|
||||
)
|
||||
):
|
||||
|
||||
@@ -71,6 +71,7 @@ def load_csv_portfolio(other_args: List[str]) -> Tuple[str, pd.DataFrame]:
|
||||
full_path = os.path.abspath(
|
||||
os.path.join(
|
||||
"gamestonk_terminal",
|
||||
"portfolio",
|
||||
"portfolio_analysis",
|
||||
"portfolios",
|
||||
f"{ns_parser.path}.csv",
|
||||
|
||||
@@ -62,7 +62,7 @@ What do you want to do?
|
||||
q quit this menu, and shows back to main menu
|
||||
quit quit to abandon the program
|
||||
|
||||
> bro brokers holdings, \t\t supports: robinhood, alpaca, ally
|
||||
> bro brokers holdings, \t\t supports: robinhood, alpaca, ally, degiro
|
||||
> pa portfolio analysis, \t\t analyses your custom portfolio
|
||||
> po portfolio optimization, \t optimal portfolio weights from pyportfolioopt
|
||||
"""
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
"""Exploratory Data Analysis Controller Module"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from typing import List
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from matplotlib import pyplot as plt
|
||||
from prompt_toolkit.completion import NestedCompleter
|
||||
from gamestonk_terminal.common.exploratory_data_analysis import eda_api, rolling
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.helper_funcs import get_flair
|
||||
from gamestonk_terminal.menu import session
|
||||
|
||||
|
||||
class EdaController:
|
||||
"""EDA Controller class"""
|
||||
|
||||
# Command choices
|
||||
CHOICES = [
|
||||
"?",
|
||||
"cls",
|
||||
"help",
|
||||
"q",
|
||||
"quit",
|
||||
"summary",
|
||||
"hist",
|
||||
"cdf",
|
||||
"bwy",
|
||||
"bwm",
|
||||
"rolling",
|
||||
"decompose",
|
||||
"cusum",
|
||||
"acf",
|
||||
"spread",
|
||||
"quantile",
|
||||
"skew",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ticker: str,
|
||||
start: datetime,
|
||||
interval: str,
|
||||
stock: pd.DataFrame,
|
||||
):
|
||||
"""Constructor"""
|
||||
self.stock = stock
|
||||
self.ticker = ticker
|
||||
self.start = start
|
||||
self.interval = interval
|
||||
self.stats_parser = argparse.ArgumentParser(add_help=False, prog="stats")
|
||||
self.stats_parser.add_argument(
|
||||
"cmd",
|
||||
choices=self.CHOICES,
|
||||
)
|
||||
|
||||
def print_help(self):
|
||||
"""Print help"""
|
||||
print(
|
||||
"https://github.com/GamestonkTerminal/"
|
||||
"GamestonkTerminal/tree/main/gamestonk_terminal/stocks/exploratory_data_analysis"
|
||||
)
|
||||
s_intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"]
|
||||
|
||||
if self.start:
|
||||
print(
|
||||
f"\n{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
|
||||
)
|
||||
else:
|
||||
print(f"\n{s_intraday} Stock: {self.ticker}")
|
||||
|
||||
print("\nExploratory Data Analysis:")
|
||||
print(" cls clear screen")
|
||||
print(" ?/help show this menu again")
|
||||
print(" q quit this menu, and shows back to main menu")
|
||||
print(" quit quit to abandon program")
|
||||
print("")
|
||||
print(" summary brief summary statistics")
|
||||
print(" hist histogram with density plot")
|
||||
print(" cdf cumulative distribution function")
|
||||
print(" bwy box and whisker yearly plot")
|
||||
print(" bwm box and whisker monthly plot")
|
||||
print("")
|
||||
print("Rolling Metrics")
|
||||
print(" rolling rolling mean and std deviation")
|
||||
print(" spread variance and std deviation")
|
||||
print(" quantile median and quantile")
|
||||
print(" skew skewness of distribution")
|
||||
print("")
|
||||
print(" decompose decomposition in cyclic-trend, season, and residuals")
|
||||
print(" cusum detects abrupt changes using cumulative sum algorithm")
|
||||
print(" acf (partial) auto-correlation function differentials")
|
||||
print("")
|
||||
return
|
||||
|
||||
def switch(self, an_input: str):
|
||||
"""Process and dispatch input
|
||||
|
||||
Returns
|
||||
-------
|
||||
True, False or None
|
||||
False - quit the menu
|
||||
True - quit the program
|
||||
None - continue in the menu
|
||||
"""
|
||||
|
||||
# Empty command
|
||||
if not an_input:
|
||||
print("")
|
||||
return None
|
||||
|
||||
(known_args, other_args) = self.stats_parser.parse_known_args(an_input.split())
|
||||
|
||||
# Help menu again
|
||||
if known_args.cmd == "?":
|
||||
self.print_help()
|
||||
return None
|
||||
|
||||
# Clear screen
|
||||
if known_args.cmd == "cls":
|
||||
os.system("cls||clear")
|
||||
return None
|
||||
|
||||
return getattr(
|
||||
self, "call_" + known_args.cmd, lambda: "Command not recognized!"
|
||||
)(other_args)
|
||||
|
||||
def call_help(self, _):
|
||||
"""Process Help command"""
|
||||
self.print_help()
|
||||
|
||||
def call_q(self, _):
|
||||
"""Process Q command - quit the menu"""
|
||||
return False
|
||||
|
||||
def call_quit(self, _):
|
||||
"""Process Quit command - quit the program"""
|
||||
return True
|
||||
|
||||
def call_summary(self, other_args: List[str]):
|
||||
"""Process summary command"""
|
||||
eda_api.summary(other_args, self.stock)
|
||||
|
||||
def call_hist(self, other_args: List[str]):
|
||||
"""Process hist command"""
|
||||
eda_api.hist(other_args, self.ticker, self.stock, self.start)
|
||||
|
||||
def call_cdf(self, other_args: List[str]):
|
||||
"""Process cdf command"""
|
||||
eda_api.cumulative_distribution_function(
|
||||
other_args, self.ticker, self.stock, self.start
|
||||
)
|
||||
|
||||
def call_bwy(self, other_args: List[str]):
|
||||
"""Process bwy command"""
|
||||
eda_api.bwy(other_args, self.ticker, self.stock, self.start)
|
||||
|
||||
def call_bwm(self, other_args: List[str]):
|
||||
"""Process bwm command"""
|
||||
eda_api.bwm(other_args, self.ticker, self.stock, self.start)
|
||||
|
||||
def call_rolling(self, other_args: List[str]):
|
||||
"""Process rolling command"""
|
||||
eda_api.rolling(other_args, self.ticker, self.stock)
|
||||
|
||||
def call_decompose(self, other_args: List[str]):
|
||||
"""Process decompose command"""
|
||||
eda_api.decompose(other_args, self.ticker, self.stock)
|
||||
|
||||
def call_cusum(self, other_args: List[str]):
|
||||
"""Process cusum command"""
|
||||
eda_api.cusum(other_args, self.stock)
|
||||
|
||||
def call_acf(self, other_args: List[str]):
|
||||
"""Process acf command"""
|
||||
eda_api.acf(other_args, self.ticker, self.stock, self.start)
|
||||
|
||||
def call_spread(self, other_args: List[str]):
|
||||
"""Process spread command"""
|
||||
rolling.spread(other_args, self.ticker, self.interval, self.stock)
|
||||
|
||||
def call_quantile(self, other_args: List[str]):
|
||||
"""Process quantile command"""
|
||||
rolling.quantile(other_args, self.ticker, self.interval, self.stock)
|
||||
|
||||
def call_skew(self, other_args: List[str]):
|
||||
"""Process skew command"""
|
||||
rolling.skew(other_args, self.ticker, self.interval, self.stock)
|
||||
|
||||
|
||||
def menu(ticker: str, start: datetime, interval: str, stock: pd.DataFrame):
|
||||
"""Statistics Menu"""
|
||||
|
||||
eda_controller = EdaController(ticker, start, interval, stock)
|
||||
eda_controller.call_help(None)
|
||||
|
||||
while True:
|
||||
# Get input command from user
|
||||
if session and gtff.USE_PROMPT_TOOLKIT:
|
||||
completer = NestedCompleter.from_nested_dict(
|
||||
{c: None for c in eda_controller.CHOICES}
|
||||
)
|
||||
an_input = session.prompt(
|
||||
f"{get_flair()} (stocks)>(eda)> ",
|
||||
completer=completer,
|
||||
)
|
||||
else:
|
||||
an_input = input(f"{get_flair()} (stocks)>(eda)> ")
|
||||
|
||||
try:
|
||||
plt.close("all")
|
||||
|
||||
process_input = eda_controller.switch(an_input)
|
||||
|
||||
if process_input is not None:
|
||||
return process_input
|
||||
|
||||
except SystemExit:
|
||||
print("The command selected doesn't exist\n")
|
||||
continue
|
||||
799
gamestonk_terminal/stocks/quantitative_analysis/qa_controller.py
Normal file
799
gamestonk_terminal/stocks/quantitative_analysis/qa_controller.py
Normal file
@@ -0,0 +1,799 @@
|
||||
"""Quantitative Analysis Controller Module"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from typing import List
|
||||
from datetime import datetime
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from matplotlib import pyplot as plt
|
||||
|
||||
from prompt_toolkit.completion import NestedCompleter
|
||||
from gamestonk_terminal.common.quantitative_analysis import (
|
||||
qa_view,
|
||||
rolling_view,
|
||||
)
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.stocks.stocks_helper import load
|
||||
from gamestonk_terminal.helper_funcs import (
|
||||
get_flair,
|
||||
check_positive,
|
||||
check_proportion_range,
|
||||
parse_known_args_and_warn,
|
||||
)
|
||||
from gamestonk_terminal.menu import session
|
||||
|
||||
|
||||
class QaController:
|
||||
"""Quantitative Analysis Controller class"""
|
||||
|
||||
# Command choices
|
||||
CHOICES = ["?", "cls", "help", "q", "quit", "load", "pick"]
|
||||
|
||||
CHOICES_COMMANDS = [
|
||||
"summary",
|
||||
"hist",
|
||||
"cdf",
|
||||
"bw",
|
||||
"rolling",
|
||||
"decompose",
|
||||
"cusum",
|
||||
"acf",
|
||||
"spread",
|
||||
"quantile",
|
||||
"skew",
|
||||
"normality",
|
||||
"qqplot",
|
||||
"unitroot",
|
||||
"goodness",
|
||||
"unitroot",
|
||||
]
|
||||
|
||||
CHOICES += CHOICES_COMMANDS
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ticker: str,
|
||||
start: datetime,
|
||||
interval: str,
|
||||
stock: pd.DataFrame,
|
||||
):
|
||||
"""Constructor"""
|
||||
stock["Returns"] = stock["Adj Close"].pct_change()
|
||||
stock["LogRet"] = np.log(stock["Adj Close"]) - np.log(
|
||||
stock["Adj Close"].shift(1)
|
||||
)
|
||||
stock = stock.rename(columns={"Adj Close": "AdjClose"})
|
||||
stock = stock.dropna()
|
||||
self.stock = stock
|
||||
self.ticker = ticker
|
||||
self.start = start
|
||||
self.interval = interval
|
||||
self.target = "Returns"
|
||||
self.qa_parser = argparse.ArgumentParser(add_help=False, prog="qa")
|
||||
self.qa_parser.add_argument(
|
||||
"cmd",
|
||||
choices=self.CHOICES,
|
||||
)
|
||||
|
||||
def print_help(self):
|
||||
"""Print help"""
|
||||
s_intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"]
|
||||
if self.start:
|
||||
stock_str = f"{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
|
||||
else:
|
||||
stock_str = f"{s_intraday} Stock: {self.ticker}"
|
||||
help_str = f"""https://github.com/GamestonkTerminal/GamestonkTerminal/tree/main/gamestonk_terminal/stocks/quantitative_analysis
|
||||
|
||||
Quantitative Analysis:
|
||||
cls clear screen
|
||||
help show this menu again
|
||||
q quit this menu, and shows back to main menu
|
||||
quit quit to abandon program
|
||||
load load new ticker
|
||||
pick pick new target variable
|
||||
|
||||
{stock_str}
|
||||
Target Column: {self.target}
|
||||
|
||||
Statistics:
|
||||
summary brief summary statistics of loaded stock.
|
||||
normality normality statistics and tests
|
||||
unitroot unit root test for stationarity (ADF, KPSS)
|
||||
Plots:
|
||||
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
|
||||
Other:
|
||||
decompose decomposition in cyclic-trend, season, and residuals of prices
|
||||
cusum detects abrupt changes using cumulative sum algorithm of prices
|
||||
"""
|
||||
print(help_str)
|
||||
|
||||
def switch(self, an_input: str):
|
||||
"""Process and dispatch input
|
||||
|
||||
Returns
|
||||
-------
|
||||
True, False or None
|
||||
False - quit the menu
|
||||
True - quit the program
|
||||
None - continue in the menu
|
||||
"""
|
||||
|
||||
# Empty command
|
||||
if not an_input:
|
||||
print("")
|
||||
return None
|
||||
|
||||
(known_args, other_args) = self.qa_parser.parse_known_args(an_input.split())
|
||||
|
||||
# Help menu again
|
||||
if known_args.cmd == "?":
|
||||
self.print_help()
|
||||
return None
|
||||
|
||||
# Clear screen
|
||||
if known_args.cmd == "cls":
|
||||
os.system("cls||clear")
|
||||
return None
|
||||
|
||||
return getattr(
|
||||
self, "call_" + known_args.cmd, lambda: "Command not recognized!"
|
||||
)(other_args)
|
||||
|
||||
def call_load(self, other_args: List[str]):
|
||||
"""Process load command"""
|
||||
self.ticker, self.start, self.interval, stock = load(
|
||||
other_args, self.ticker, self.start, self.interval, self.stock
|
||||
)
|
||||
if "." in self.ticker:
|
||||
self.ticker = self.ticker.split(".")[0]
|
||||
stock["Returns"] = stock["Adj Close"].pct_change()
|
||||
stock["LogRet"] = np.log(stock["Adj Close"]) - np.log(
|
||||
stock["Adj Close"].shift(1)
|
||||
)
|
||||
stock = stock.rename(columns={"Adj Close": "AdjClose"})
|
||||
stock = stock.dropna()
|
||||
self.stock = stock
|
||||
|
||||
def call_help(self, _):
|
||||
"""Process Help command"""
|
||||
self.print_help()
|
||||
|
||||
def call_q(self, _):
|
||||
"""Process Q command - quit the menu"""
|
||||
return False
|
||||
|
||||
def call_quit(self, _):
|
||||
"""Process Quit command - quit the program"""
|
||||
return True
|
||||
|
||||
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.stock.columns),
|
||||
help="Select variable to analyze",
|
||||
)
|
||||
try:
|
||||
if other_args:
|
||||
if "-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 not ns_parser:
|
||||
return
|
||||
self.target = ns_parser.target
|
||||
print("")
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_summary(df=self.stock, export=ns_parser.export)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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"
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_hist(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
bins=ns_parser.n_bins,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_cdf(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
qa_view.display_bw(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
yearly=ns_parser.year,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_seasonal(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
multiplicative=ns_parser.multiplicative,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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.stock[self.target].values)
|
||||
- min(self.stock[self.target].values)
|
||||
)
|
||||
/ 40,
|
||||
help="threshold",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-d",
|
||||
"--drift",
|
||||
dest="drift",
|
||||
type=float,
|
||||
default=(
|
||||
max(self.stock[self.target].values)
|
||||
- min(self.stock[self.target].values)
|
||||
)
|
||||
/ 80,
|
||||
help="drift",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_cusum(
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
threshold=ns_parser.threshold,
|
||||
drift=ns_parser.drift,
|
||||
)
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
def call_acf(self, other_args: List[str]):
|
||||
"""Process acf command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="acf",
|
||||
description="""
|
||||
Auto-Correlation and Partial Auto-Correlation Functions for diff and diff diff stock data
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--lags",
|
||||
dest="lags",
|
||||
type=check_positive,
|
||||
default=15,
|
||||
help="maximum lags to display in plots",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
if self.target != "AdjClose":
|
||||
print(
|
||||
"Target not AdjClose. For best results, use `pick AdjClose` first."
|
||||
)
|
||||
|
||||
qa_view.display_acf(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
lags=ns_parser.lags,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="Window length",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
rolling_view.display_mean_std(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
length=ns_parser.n_length,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
def call_spread(self, other_args: List[str]):
|
||||
"""Process spread command"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||
prog="spread",
|
||||
description="""
|
||||
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="Window length",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
rolling_view.display_spread(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
length=ns_parser.n_length,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="length",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"-q",
|
||||
"--quantile",
|
||||
action="store",
|
||||
dest="f_quantile",
|
||||
type=check_proportion_range,
|
||||
default=0.5,
|
||||
help="quantile",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
rolling_view.display_quantile(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
length=ns_parser.n_length,
|
||||
quantile=ns_parser.f_quantile,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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(
|
||||
"-l",
|
||||
"--length",
|
||||
action="store",
|
||||
dest="n_length",
|
||||
type=check_positive,
|
||||
default=14,
|
||||
help="length",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
rolling_view.display_skew(
|
||||
name=self.ticker,
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
length=ns_parser.n_length,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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
|
||||
""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_normality(
|
||||
df=self.stock, target=self.target, export=ns_parser.export
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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
|
||||
""",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_qqplot(name=self.ticker, df=self.stock, target=self.target)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
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",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--export",
|
||||
choices=["csv", "json", "xlsx"],
|
||||
default="",
|
||||
type=str,
|
||||
dest="export",
|
||||
help="Export dataframe data to csv,json,xlsx file",
|
||||
)
|
||||
|
||||
try:
|
||||
ns_parser = parse_known_args_and_warn(parser, other_args)
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
qa_view.display_unitroot(
|
||||
df=self.stock,
|
||||
target=self.target,
|
||||
fuller_reg=ns_parser.fuller_reg,
|
||||
kpss_reg=ns_parser.kpss_reg,
|
||||
export=ns_parser.export,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
print(e, "\n")
|
||||
|
||||
|
||||
def menu(ticker: str, start: datetime, interval: str, stock: pd.DataFrame):
|
||||
"""Statistics Menu"""
|
||||
|
||||
qa_controller = QaController(ticker, start, interval, stock)
|
||||
qa_controller.call_help(None)
|
||||
|
||||
while True:
|
||||
# Get input command from user
|
||||
if session and gtff.USE_PROMPT_TOOLKIT:
|
||||
completer = NestedCompleter.from_nested_dict(
|
||||
{c: None for c in qa_controller.CHOICES}
|
||||
)
|
||||
an_input = session.prompt(
|
||||
f"{get_flair()} (stocks)>(qa)> ",
|
||||
completer=completer,
|
||||
)
|
||||
else:
|
||||
an_input = input(f"{get_flair()} (stocks)>(qa)> ")
|
||||
|
||||
try:
|
||||
plt.close("all")
|
||||
|
||||
process_input = qa_controller.switch(an_input)
|
||||
|
||||
if process_input is not None:
|
||||
return process_input
|
||||
|
||||
except SystemExit:
|
||||
print("The command selected doesn't exist\n")
|
||||
continue
|
||||
@@ -1,146 +0,0 @@
|
||||
# RESIDUAL ANALYSIS
|
||||
|
||||
This menu aims to perform residual analysis on a pre-loaded stock in order to do statistical modeling, and the usage of the following commands along with an example will be exploited below.
|
||||
|
||||
* [pick](#pick)
|
||||
* pick one of the model fitting
|
||||
* Currently Supported: **Naive**, **ARIMA**
|
||||
* [fit](#fit)
|
||||
* show model fit against stock
|
||||
* [res](#res)
|
||||
* show residuals
|
||||
* [hist](#hist)
|
||||
* histogram and density curve
|
||||
* [qqplot](#qqplot)
|
||||
* residuals against standard normal curve
|
||||
* [acf](#acf)
|
||||
* (partial) auto-correlation function
|
||||
* [normality](#normality)
|
||||
* normality test (Kurtosis,Skewness,...)
|
||||
* [goodness](#goodness)
|
||||
* goodness of fit test (Kolmogorov-Smirnov)
|
||||
* [arch](#arch)
|
||||
* autoregressive conditional heteroscedasticity
|
||||
* [unitroot](#unitroot)
|
||||
* unit root test / stationarity (ADF, KPSS)
|
||||
* [independence](#independence)
|
||||
* tests independent and identically distributed (BDS)
|
||||
|
||||
## pick <a name="pick"></a>
|
||||
|
||||
```text
|
||||
usage: pick [-m MODEL]
|
||||
```
|
||||
|
||||
Pick model to fit to stock data.
|
||||
Currently supported: **Naive**, **ARIMA**
|
||||
|
||||
|
||||
* -m : model to fit to stock data. Default: None.
|
||||
|
||||
|
||||
## fit <a name="fit"></a>
|
||||
|
||||
```text
|
||||
usage: fit
|
||||
```
|
||||
|
||||
Plot model fitting
|
||||
|
||||

|
||||
|
||||
## res <a name="res"></a>
|
||||
|
||||
```text
|
||||
usage: res
|
||||
```
|
||||
|
||||
Plot residuals
|
||||
|
||||

|
||||
|
||||
|
||||
## hist <a name="hist"></a>
|
||||
|
||||
```text
|
||||
usage: hist
|
||||
```
|
||||
|
||||
Histogram and density curve
|
||||
|
||||

|
||||
|
||||
## qqplot <a name="qqplot"></a>
|
||||
|
||||
```text
|
||||
usage: qqplot
|
||||
```
|
||||
|
||||
Qqplot time series against a standard normal curve
|
||||
|
||||

|
||||
|
||||
## acf <a name="acf"></a>
|
||||
|
||||
```text
|
||||
usage: acf [-l LAGS]
|
||||
```
|
||||
|
||||
(partial) auto-correlation function
|
||||
|
||||
* -l : maximum lags to display in plots. Default 40.
|
||||
|
||||

|
||||
|
||||
|
||||
## normality <a name="normality"></a>
|
||||
|
||||
```text
|
||||
usage: normality
|
||||
```
|
||||
|
||||
normality test (Kurtosis,Skewness,...)
|
||||
|
||||
<img width="972" alt="normality" src="https://user-images.githubusercontent.com/25267873/112752697-3332ce00-8fcc-11eb-8b74-257284e75d3c.png">
|
||||
|
||||
|
||||
## goodness <a name="goodness"></a>
|
||||
|
||||
```text
|
||||
usage: goodness
|
||||
```
|
||||
|
||||
goodness of fit test (Kolmogorov-Smirnov)
|
||||
|
||||
<img width="966" alt="goodness" src="https://user-images.githubusercontent.com/25267873/112752696-329a3780-8fcc-11eb-8ce9-d639923880a5.png">
|
||||
|
||||
|
||||
## arch <a name="arch"></a>
|
||||
|
||||
```text
|
||||
usage: arch
|
||||
```
|
||||
|
||||
autoregressive conditional heteroscedasticity with Engle's test
|
||||
|
||||
<img width="965" alt="arch" src="https://user-images.githubusercontent.com/25267873/112752702-34fc9180-8fcc-11eb-8668-0363f1a2b6ff.png">
|
||||
|
||||
## unitroot <a name="unitroot"></a>
|
||||
|
||||
```text
|
||||
usage: unitroot
|
||||
```
|
||||
|
||||
unit root test / stationarity (ADF, KPSS)
|
||||
|
||||
<img width="982" alt="unitroot" src="https://user-images.githubusercontent.com/25267873/112752698-33cb6480-8fcc-11eb-9c4f-fd0a59a01a88.png">
|
||||
|
||||
## independence <a name="independence"></a>
|
||||
|
||||
```text
|
||||
usage: independence
|
||||
```
|
||||
|
||||
tests independent and identically distributed (i.i.d.) time series (BDS)
|
||||
|
||||
<img width="974" alt="independence" src="https://user-images.githubusercontent.com/25267873/112752695-3201a100-8fcc-11eb-9760-3fdb26bb1c16.png">
|
||||
@@ -1,282 +0,0 @@
|
||||
"""Residuals Controller Module"""
|
||||
__docformat__ = "numpy"
|
||||
|
||||
import argparse
|
||||
import os
|
||||
from typing import List
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
from matplotlib import pyplot as plt
|
||||
from prompt_toolkit.completion import NestedCompleter
|
||||
from gamestonk_terminal.common.residuals_analysis import residuals_api, residuals_model
|
||||
from gamestonk_terminal import feature_flags as gtff
|
||||
from gamestonk_terminal.helper_funcs import get_flair
|
||||
from gamestonk_terminal.menu import session
|
||||
|
||||
|
||||
class ResidualsController:
|
||||
"""Residuals Controller class"""
|
||||
|
||||
# Command choices
|
||||
CHOICES = [
|
||||
"cls",
|
||||
"?",
|
||||
"help",
|
||||
"q",
|
||||
"quit",
|
||||
"pick",
|
||||
"fit",
|
||||
"res",
|
||||
"acf",
|
||||
"qqplot",
|
||||
"hist",
|
||||
"normality",
|
||||
"goodness",
|
||||
"arch",
|
||||
"unitroot",
|
||||
"independence",
|
||||
]
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ticker: str,
|
||||
start: datetime,
|
||||
interval: str,
|
||||
stock: pd.DataFrame,
|
||||
):
|
||||
"""Constructor"""
|
||||
self.ticker = ticker
|
||||
self.start = start
|
||||
self.interval = interval
|
||||
self.stock = stock["Adj Close"]
|
||||
|
||||
self.model_name: str = "None"
|
||||
self.model: pd.Series = None
|
||||
self.residuals: List[float] = []
|
||||
|
||||
self.ra_parser = argparse.ArgumentParser(add_help=False, prog="ra")
|
||||
self.ra_parser.add_argument(
|
||||
"cmd",
|
||||
choices=self.CHOICES,
|
||||
)
|
||||
|
||||
def print_help(self):
|
||||
"""Print help"""
|
||||
print(
|
||||
"https://github.com/GamestonkTerminal/GamestonkTerminal/tree/main/gamestonk_terminal"
|
||||
"/stocks/residuals_analysis"
|
||||
)
|
||||
s_intraday = (f"Intraday {self.interval}", "Daily")[self.interval == "1440min"]
|
||||
|
||||
if self.start:
|
||||
print(
|
||||
f"\n{s_intraday} Stock: {self.ticker} (from {self.start.strftime('%Y-%m-%d')})"
|
||||
)
|
||||
else:
|
||||
print(f"\n{s_intraday} Stock: {self.ticker}")
|
||||
|
||||
print(f"\nModel fit: {self.model_name}")
|
||||
|
||||
print("\nResiduals Analysis:")
|
||||
print(" cls clear screen")
|
||||
print(" ?/help show this menu again")
|
||||
print(" q quit this menu, and shows back to main menu")
|
||||
print(" quit quit to abandon program")
|
||||
print(" pick pick one of the model fitting.")
|
||||
print(" Supports: naive, arima")
|
||||
print("")
|
||||
if self.model_name != "None":
|
||||
print(" fit show model fit against stock")
|
||||
print(" res show residuals")
|
||||
print(" hist histogram and density plot")
|
||||
print(" qqplot residuals against standard normal curve")
|
||||
print(" acf (partial) auto-correlation function")
|
||||
print(" normality normality test (Kurtosis,Skewness,...)")
|
||||
print(" goodness goodness of fit test (Kolmogorov-Smirnov)")
|
||||
print(" arch autoregressive conditional heteroscedasticity")
|
||||
print(" unitroot unit root test / stationarity (ADF, KPSS)")
|
||||
print(
|
||||
" independence tests independent and identically distributed (BDS)"
|
||||
)
|
||||
|
||||
def pick_model(self, other_args: List[str]):
|
||||
"""Pick model to fit to stock data"""
|
||||
parser = argparse.ArgumentParser(
|
||||
add_help=False,
|
||||
prog="pick",
|
||||
description="""Pick model to fit to stock data.""",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-h",
|
||||
"--help",
|
||||
action="store_true",
|
||||
dest="help",
|
||||
help="show this help message",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-m",
|
||||
"--model",
|
||||
dest="model",
|
||||
type=str,
|
||||
choices=["naive", "arima"],
|
||||
help="Model to fit",
|
||||
)
|
||||
|
||||
try:
|
||||
# For the case where a user uses: 'pick naive'
|
||||
if other_args:
|
||||
if "-" not in other_args[0]:
|
||||
other_args.insert(0, "-m")
|
||||
|
||||
(ns_parser, _) = parser.parse_known_args(other_args)
|
||||
|
||||
if ns_parser.help:
|
||||
parser.print_help()
|
||||
print("")
|
||||
return
|
||||
|
||||
if not ns_parser:
|
||||
return
|
||||
|
||||
if ns_parser.model == "naive":
|
||||
self.model_name, self.model, self.residuals = residuals_model.naive(
|
||||
other_args[2:], self.stock
|
||||
)
|
||||
|
||||
elif ns_parser.model == "arima":
|
||||
self.model_name, self.model, self.residuals = residuals_model.arima(
|
||||
other_args[2:], self.stock
|
||||
)
|
||||
|
||||
self.print_help()
|
||||
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
print("")
|
||||
|
||||
def switch(self, an_input: str):
|
||||
"""Process and dispatch input
|
||||
|
||||
Returns
|
||||
-------
|
||||
True, False or None
|
||||
False - quit the menu
|
||||
True - quit the program
|
||||
None - continue in the menu
|
||||
"""
|
||||
|
||||
# Empty command
|
||||
if not an_input:
|
||||
print("")
|
||||
return None
|
||||
|
||||
(known_args, other_args) = self.ra_parser.parse_known_args(an_input.split())
|
||||
|
||||
# Help menu again
|
||||
if known_args.cmd == "?":
|
||||
self.print_help()
|
||||
return None
|
||||
|
||||
# Clear screen
|
||||
if known_args.cmd == "cls":
|
||||
os.system("cls||clear")
|
||||
return None
|
||||
|
||||
return getattr(
|
||||
self, "call_" + known_args.cmd, lambda: "Command not recognized!"
|
||||
)(other_args)
|
||||
|
||||
def call_help(self, _):
|
||||
"""Process Help command"""
|
||||
self.print_help()
|
||||
|
||||
def call_q(self, _):
|
||||
"""Process Q command - quit the menu"""
|
||||
return False
|
||||
|
||||
def call_quit(self, _):
|
||||
"""Process Quit command - quit the program"""
|
||||
return True
|
||||
|
||||
def call_pick(self, other_args: List[str]):
|
||||
"""Process pick command"""
|
||||
self.pick_model(other_args)
|
||||
|
||||
def call_fit(self, other_args: List[str]):
|
||||
"""Process fit command"""
|
||||
residuals_api.fit(
|
||||
other_args, self.ticker, self.stock, self.model_name, self.model
|
||||
)
|
||||
|
||||
def call_res(self, other_args: List[str]):
|
||||
"""Process res command"""
|
||||
residuals_api.res(
|
||||
other_args, self.ticker, self.stock, self.model_name, self.residuals
|
||||
)
|
||||
|
||||
def call_hist(self, other_args: List[str]):
|
||||
"""Process hist command"""
|
||||
residuals_api.hist(other_args, self.ticker, self.model_name, self.residuals)
|
||||
|
||||
def call_qqplot(self, other_args: List[str]):
|
||||
"""Process qqplot command"""
|
||||
residuals_api.plot_qqplot(
|
||||
other_args, self.ticker, self.model_name, self.residuals
|
||||
)
|
||||
|
||||
def call_acf(self, other_args: List[str]):
|
||||
"""Process acf command"""
|
||||
residuals_api.acf(other_args, self.ticker, self.model_name, self.residuals)
|
||||
|
||||
def call_normality(self, other_args: List[str]):
|
||||
"""Process normality command"""
|
||||
residuals_api.normality(other_args, self.residuals)
|
||||
|
||||
def call_goodness(self, other_args: List[str]):
|
||||
"""Process goodness command"""
|
||||
residuals_api.goodness(other_args, self.residuals)
|
||||
|
||||
def call_arch(self, other_args: List[str]):
|
||||
"""Process arch command"""
|
||||
residuals_api.arch(other_args, self.residuals)
|
||||
|
||||
def call_unitroot(self, other_args: List[str]):
|
||||
"""Process unit root command"""
|
||||
residuals_api.unitroot(other_args, self.residuals)
|
||||
|
||||
def call_independence(self, other_args: List[str]):
|
||||
"""Process independence command"""
|
||||
residuals_api.independence(other_args, self.residuals)
|
||||
|
||||
|
||||
def menu(ticker: str, start: datetime, interval: str, stock: pd.DataFrame):
|
||||
"""Residuals Menu"""
|
||||
|
||||
ra_controller = ResidualsController(ticker, start, interval, stock)
|
||||
ra_controller.call_help(None)
|
||||
|
||||
while True:
|
||||
# Get input command from user
|
||||
if session and gtff.USE_PROMPT_TOOLKIT:
|
||||
completer = NestedCompleter.from_nested_dict(
|
||||
{c: None for c in ra_controller.CHOICES}
|
||||
)
|
||||
an_input = session.prompt(
|
||||
f"{get_flair()} (stocks)>(ra)> ",
|
||||
completer=completer,
|
||||
)
|
||||
else:
|
||||
an_input = input(f"{get_flair()} (stocks)>(ra)> ")
|
||||
|
||||
try:
|
||||
plt.close("all")
|
||||
|
||||
process_input = ra_controller.switch(an_input)
|
||||
|
||||
if process_input is not None:
|
||||
return process_input
|
||||
|
||||
except SystemExit:
|
||||
print("The command selected doesn't exist\n")
|
||||
continue
|
||||
@@ -22,13 +22,12 @@ from gamestonk_terminal.stocks.comparison_analysis import ca_controller
|
||||
from gamestonk_terminal.stocks.dark_pool_shorts import dps_controller
|
||||
from gamestonk_terminal.stocks.discovery import disc_controller
|
||||
from gamestonk_terminal.stocks.due_diligence import dd_controller
|
||||
from gamestonk_terminal.stocks.exploratory_data_analysis import eda_controller
|
||||
from gamestonk_terminal.stocks.quantitative_analysis import qa_controller
|
||||
from gamestonk_terminal.stocks.fundamental_analysis import fa_controller
|
||||
from gamestonk_terminal.stocks.government import gov_controller
|
||||
from gamestonk_terminal.stocks.insider import insider_controller
|
||||
from gamestonk_terminal.stocks.report import report_controller
|
||||
from gamestonk_terminal.stocks.research import res_controller
|
||||
from gamestonk_terminal.stocks.residuals_analysis import ra_controller
|
||||
from gamestonk_terminal.stocks.screener import screener_controller
|
||||
from gamestonk_terminal.stocks.stocks_helper import candle, load, quote
|
||||
from gamestonk_terminal.stocks.technical_analysis import ta_controller
|
||||
@@ -60,9 +59,8 @@ class StocksController:
|
||||
CHOICES_MENUS = [
|
||||
"ta",
|
||||
"ba",
|
||||
"eda",
|
||||
"qa",
|
||||
"pred",
|
||||
"ra",
|
||||
"disc",
|
||||
"dps",
|
||||
"scr",
|
||||
@@ -139,7 +137,7 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]}
|
||||
> bt strategy backtester, \t e.g.: simple ema, ema cross, rsi strategies
|
||||
> ta technical analysis, \t e.g.: ema, macd, rsi, adx, bbands, obv
|
||||
> ba behavioural analysis, \t from: reddit, stocktwits, twitter, google
|
||||
> eda exploratory data analysis,\t e.g.: decompose, cusum, residuals analysis
|
||||
> qa quantitative analysis, \t e.g.: decompose, cusum, residuals analysis
|
||||
> ra residuals analysis, \t e.g.: model fit, qqplot, hypothesis test
|
||||
> pred prediction techniques, \t e.g.: regression, arima, rnn, lstm
|
||||
{Style.RESET_ALL if not self.ticker else ''}"""
|
||||
@@ -418,26 +416,8 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]}
|
||||
else:
|
||||
return True
|
||||
|
||||
def call_ra(self, _):
|
||||
"""Process ra command"""
|
||||
if not self.ticker:
|
||||
print("Use 'load <ticker>' prior to this command!", "\n")
|
||||
return
|
||||
|
||||
ret = ra_controller.menu(
|
||||
self.ticker,
|
||||
self.start,
|
||||
self.interval,
|
||||
self.stock,
|
||||
)
|
||||
|
||||
if ret is False:
|
||||
self.print_help()
|
||||
else:
|
||||
return True
|
||||
|
||||
def call_eda(self, _):
|
||||
"""Process eda command"""
|
||||
def call_qa(self, _):
|
||||
"""Process qa command"""
|
||||
if not self.ticker:
|
||||
print("Use 'load <ticker>' prior to this command!", "\n")
|
||||
return
|
||||
@@ -447,7 +427,7 @@ Market {('CLOSED', 'OPEN')[b_is_stock_market_open()]}
|
||||
print("Load daily data to use this menu!", "\n")
|
||||
return
|
||||
|
||||
ret = eda_controller.menu(
|
||||
ret = qa_controller.menu(
|
||||
self.ticker,
|
||||
self.start,
|
||||
self.interval,
|
||||
|
||||
Reference in New Issue
Block a user