Skip to content

Commit

Permalink
Add prediction to economy/fred (OpenBB-finance#1133)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmaslek authored Jan 4, 2022
1 parent 8571336 commit f5b0dc8
Show file tree
Hide file tree
Showing 23 changed files with 7,732 additions and 117 deletions.
3 changes: 3 additions & 0 deletions gamestonk_terminal/common/prediction_techniques/ets_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,9 @@ def display_exponential_smoothing(
linestyle="--",
color="k",
)
dateFmt = mdates.DateFormatter("%m/%d/%Y")
ax.xaxis.set_major_formatter(dateFmt)
ax.tick_params(axis="x", labelrotation=45)

# BACKTESTING
if s_end_date:
Expand Down
8 changes: 6 additions & 2 deletions gamestonk_terminal/common/prediction_techniques/mc_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def display_mc_forecast(
n_future: int,
n_sims: int,
use_log=True,
fig_title: str = "",
export: str = "",
time_res: str = "",
):
Expand All @@ -40,6 +41,8 @@ def display_mc_forecast(
Number of simulations to run
use_log : bool, optional
Flag to use lognormal, by default True
fig_title : str
Figure title
export: str
Format to export data
time_res : str
Expand All @@ -63,13 +66,14 @@ def display_mc_forecast(
ax[0].grid("on")

sns.histplot(predicted_values[-1, :], ax=ax[1], kde=True)
ax[1].set_xlabel("Price")
ax[1].set_xlabel("Final Value")
ax[1].axvline(x=data.values[-1], c="k", label="Last Value", lw=3, ls="-") # type: ignore
ax[1].set_title(f"Distribution of final values after {n_future} steps.")
ax[1].set_xlim(np.min(predicted_values[-1, :]), np.max(predicted_values[-1, :]))
ax[1].grid("on")
ax[1].legend()

if fig_title:
fig.suptitle(fig_title)
fig.tight_layout(pad=2)

if gtff.USE_ION:
Expand Down
48 changes: 27 additions & 21 deletions gamestonk_terminal/common/prediction_techniques/pred_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import pandas as pd
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from colorama import Fore, Style
from sklearn.metrics import (
mean_absolute_error,
Expand Down Expand Up @@ -413,8 +414,9 @@ def plot_data_predictions(
):
"""Plots data predictions for the different ML techniques"""

plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
plt.plot(
# plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI)
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
ax.plot(
data.index,
data.values,
"-ob",
Expand All @@ -430,21 +432,21 @@ def plot_data_predictions(
else:
y_pred = preds[i].ravel()
y_act = y_valid[i].ravel()
plt.plot(
ax.plot(
y_dates_valid[i],
y_pred,
"r",
lw=1,
)
plt.fill_between(
ax.fill_between(
y_dates_valid[i],
y_pred,
y_act,
where=(y_pred < y_act),
color="r",
alpha=0.2,
)
plt.fill_between(
ax.fill_between(
y_dates_valid[i],
y_pred,
y_act,
Expand All @@ -460,14 +462,14 @@ def plot_data_predictions(
else:
final_pred = preds[-1].reshape(-1, 1).ravel()
final_valid = y_valid[-1].reshape(-1, 1).ravel()
plt.plot(
ax.plot(
y_dates_valid[-1],
final_pred,
"r",
lw=2,
label="Predictions",
)
plt.fill_between(
ax.fill_between(
y_dates_valid[-1],
final_pred,
final_valid,
Expand All @@ -476,7 +478,7 @@ def plot_data_predictions(
)

_, _, ymin, ymax = plt.axis()
plt.vlines(
ax.vlines(
forecast_data.index[0],
ymin,
ymax,
Expand All @@ -486,22 +488,22 @@ def plot_data_predictions(
color="k",
)
if n_loops == 1:
plt.plot(
ax.plot(
forecast_data.index,
forecast_data.values,
"-og",
ms=3,
label="Forecast",
)
else:
plt.plot(
ax.plot(
forecast_data.index,
forecast_data.median(axis=1).values,
"-og",
ms=3,
label="Forecast",
)
plt.fill_between(
ax.fill_between(
forecast_data.index,
forecast_data.quantile(0.25, axis=1).values,
forecast_data.quantile(0.75, axis=1).values,
Expand All @@ -510,28 +512,32 @@ def plot_data_predictions(
)
# Subtracting 1 day only works nicely for daily data. For now if not daily, then start line on last point
if not time_str or time_str == "1D":
plt.axvspan(
ax.axvspan(
forecast_data.index[0] - timedelta(days=1),
forecast_data.index[-1],
facecolor="tab:orange",
alpha=0.2,
)
plt.xlim(data.index[0], forecast_data.index[-1] + timedelta(days=1))
ax.set_xlim(data.index[0], forecast_data.index[-1] + timedelta(days=1))

else:
plt.axvspan(
ax.axvspan(
forecast_data.index[0],
forecast_data.index[-1],
facecolor="tab:orange",
alpha=0.2,
)
plt.xlim(data.index[0], forecast_data.index[-1])

plt.legend(loc=0)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(b=True, which="major", color="#666666", linestyle="-")
plt.title(title)
ax.set_xlim(data.index[0], forecast_data.index[-1])

ax.legend(loc=0)
ax.set_xlabel("Time")
ax.set_ylabel("Value")
ax.grid(b=True, which="major", color="#666666", linestyle="-")
dateFmt = mdates.DateFormatter("%m/%d/%Y")
ax.xaxis.set_major_formatter(dateFmt)
ax.tick_params(axis="x", labelrotation=45)
fig.suptitle(title)
fig.tight_layout(pad=2)
if gtff.USE_ION:
plt.ion()
plt.show()
Expand Down
23 changes: 13 additions & 10 deletions gamestonk_terminal/economy/economy_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os
from typing import List, Union

from rich.console import Console
import pandas as pd
from prompt_toolkit.completion import NestedCompleter

Expand All @@ -31,6 +32,7 @@
)
from gamestonk_terminal.menu import session

t_console = Console()
# pylint: disable=R1710,R0904,C0415


Expand Down Expand Up @@ -226,7 +228,7 @@ def print_help():
> fred Federal Reserve Economic Data submenu
"""
print(help_text)
t_console.print(help_text)

def switch(self, an_input: str):
"""Process and dispatch input
Expand All @@ -238,7 +240,7 @@ def switch(self, an_input: str):
"""
# Empty command
if not an_input:
print("")
t_console.print("")
return self.queue

# Navigation slash is being used
Expand Down Expand Up @@ -290,7 +292,6 @@ def call_help(self, _):

def call_quit(self, _):
"""Process quit menu command"""
print("")
self.queue.insert(0, "quit")

def call_exit(self, _):
Expand Down Expand Up @@ -1137,7 +1138,9 @@ def call_bigmac(self, other_args: List[str]):
file = os.path.join(
os.path.dirname(__file__), "NASDAQ_CountryCodes.csv"
)
print(pd.read_csv(file, index_col=0).to_string(index=False), "\n")
t_console.print(
pd.read_csv(file, index_col=0).to_string(index=False), "\n"
)
else:
nasdaq_view.display_big_mac_index(
country_codes=ns_parser.countries,
Expand All @@ -1162,7 +1165,7 @@ def menu(queue: List[str] = None):
if econ_controller.queue and len(econ_controller.queue) > 0:
# If the command is quitting the menu we want to return in here
if econ_controller.queue[0] in ("q", "..", "quit"):
print("")
t_console.print("")
if len(econ_controller.queue) > 1:
return econ_controller.queue[1:]
return []
Expand All @@ -1173,7 +1176,7 @@ def menu(queue: List[str] = None):

# Print the current location because this was an instruction and we want user to know what was the action
if an_input and an_input.split(" ")[0] in econ_controller.CHOICES_COMMANDS:
print(f"{get_flair()} /economy/ $ {an_input}")
t_console.print(f"{get_flair()} /economy/ $ {an_input}")

# Get input command from user
else:
Expand Down Expand Up @@ -1201,7 +1204,7 @@ def menu(queue: List[str] = None):
econ_controller.queue = econ_controller.switch(an_input)

except SystemExit:
print(
t_console.print(
f"\nThe command '{an_input}' doesn't exist on the /economy menu.",
end="",
)
Expand All @@ -1219,13 +1222,13 @@ def menu(queue: List[str] = None):
if candidate_input == an_input:
an_input = ""
econ_controller.queue = []
print("\n")
t_console.print("")
continue
an_input = candidate_input
else:
an_input = similar_cmd[0]

print(f" Replacing by '{an_input}'.")
t_console.print(f" Replacing by '{an_input}'.")
econ_controller.queue.insert(0, an_input)
else:
print("\n")
t_console.print("")
Loading

0 comments on commit f5b0dc8

Please sign in to comment.