Files
OpenBB/openbb_terminal/dashboards/voila/forecast.ipynb
Pratyush Shukla dd41b8461d Fixed crypto, economy, forex commands inreports menu (#4717) (#4729)
* Fixed `crypto`, `economy`, `forex` commands  in`reports` menu

* Modified sdk.py to use Feedparser API to get news
* Made `basic_info` and `trading_pair_info` tables look prettier in `crypto` template
* Fixed news dataframe by modifying the columns in `economy` and `forex`

* Modified `trail_maps.csv` and generated `sdk.py`

* fixing forecast dashboard

---------

Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt>
2023-04-12 09:57:05 +00:00

378 lines
14 KiB
Plaintext
Vendored

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "e9ad60bc",
"metadata": {},
"outputs": [],
"source": [
"from datetime import datetime, timedelta\n",
"from typing import Callable, Any\n",
"from inspect import signature\n",
"import warnings, logging\n",
"\n",
"import ipywidgets as widgets\n",
"import yfinance as yf\n",
"import pandas as pd\n",
"from IPython.display import display\n",
"\n",
"from openbb_terminal import OpenBBFigure, theme\n",
"\n",
"theme.apply_style(\"light\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "404cb982",
"metadata": {},
"outputs": [],
"source": [
"# Suppressing sdk logs\n",
"from openbb_terminal.core.session.current_system import set_system_variable\n",
"\n",
"set_system_variable(\"LOGGING_SUPPRESS\", True)\n",
"\n",
"# Import the OpenBB SDK\n",
"from openbb_terminal.sdk import openbb"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "beb36881",
"metadata": {},
"outputs": [],
"source": [
"try:\n",
" has_forecast = True\n",
" model_opts = {\n",
" \"expo\": openbb.forecast.expo_chart,\n",
" \"theta\": openbb.forecast.theta_chart,\n",
" \"linregr\": openbb.forecast.linregr_chart,\n",
" \"regr\": openbb.forecast.regr_chart,\n",
" \"rnn\": openbb.forecast.rnn_chart,\n",
" \"brnn\": openbb.forecast.brnn_chart,\n",
" \"nbeats\": openbb.forecast.nbeats_chart,\n",
" \"tcn\": openbb.forecast.tcn_chart,\n",
" \"trans\": openbb.forecast.trans_chart,\n",
" \"tft\": openbb.forecast.tft_chart,\n",
" \"nhits\": openbb.forecast.nhits_chart,\n",
" }\n",
"\n",
" feat_engs = {\n",
" \"ema\": openbb.forecast.ema,\n",
" \"sto\": openbb.forecast.sto,\n",
" \"rsi\": openbb.forecast.rsi,\n",
" \"roc\": openbb.forecast.roc,\n",
" \"mom\": openbb.forecast.mom,\n",
" \"atr\": openbb.forecast.atr,\n",
" \"delta\": openbb.forecast.delta,\n",
" \"signal\": openbb.forecast.signal,\n",
" }\n",
"except AttributeError as e:\n",
" print(e)\n",
" has_forecast = False\n",
" model_opts = {}\n",
" feat_engs = {}\n",
"\n",
"interval_opts = [\n",
" \"1m\",\n",
" \"2m\",\n",
" \"5m\",\n",
" \"15m\",\n",
" \"30m\",\n",
" \"60m\",\n",
" \"90m\",\n",
" \"1h\",\n",
" \"1d\",\n",
" \"5d\",\n",
" \"1wk\",\n",
" \"1mo\",\n",
" \"3mo\",\n",
"]\n",
"\n",
"\n",
"def format_df(df: pd.DataFrame) -> pd.DataFrame:\n",
" if len(df.columns) != 6:\n",
" df.columns = [\"_\".join(col).strip() for col in df.columns.values]\n",
" df.reset_index(inplace=True)\n",
" df.columns = [x.lower() for x in df.columns]\n",
" return df\n",
"\n",
"\n",
"def has_parameter(func: Callable[..., Any], parameter: str) -> bool:\n",
" params = signature(func).parameters\n",
" parameters = params.keys()\n",
" return parameter in parameters"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f8c2f65c",
"metadata": {
"tags": [
"parameters"
]
},
"outputs": [],
"source": [
"class Chart:\n",
" def __init__(self):\n",
" self.last_tickers = \"\"\n",
" self.last_interval = \"1d\"\n",
" self.df = pd.DataFrame()\n",
" self.result = pd.DataFrame()\n",
" self.infos = {}\n",
"\n",
" def handle_changes(\n",
" self,\n",
" past_covariates,\n",
" start,\n",
" end,\n",
" interval,\n",
" tickers,\n",
" target_column,\n",
" model,\n",
" naive,\n",
" forecast_only,\n",
" ):\n",
" ticker_list = tickers.split(\",\")\n",
" if ticker_list:\n",
" if tickers != self.last_tickers or interval != self.last_interval:\n",
" if interval in [\"1d\", \"5d\", \"1wk\", \"1mo\", \"3mo\"]:\n",
" self.df = yf.download(\n",
" tickers, period=\"max\", interval=interval, progress=False\n",
" )\n",
" else:\n",
" end_date = end + timedelta(days=1)\n",
" self.df = yf.download(\n",
" tickers,\n",
" start=start,\n",
" end=end_date,\n",
" interval=interval,\n",
" progress=False,\n",
" )\n",
" self.df = format_df(self.df)\n",
" self.last_tickers = tickers\n",
" self.last_interval = interval\n",
" forecast_model = model_opts[model]\n",
" self.forecast_model = forecast_model\n",
" contains_covariates = has_parameter(forecast_model, \"past_covariates\")\n",
"\n",
" # Update Inputs\n",
" if list(target_widget.options) != [\n",
" x for x in self.df.columns if x != \"date\"\n",
" ]:\n",
" target_widget.options = [x for x in self.df.columns if x != \"date\"]\n",
" return\n",
" if list(past_covs_widget.options) != [\n",
" x for x in self.df.columns if x != \"date\"\n",
" ]:\n",
" past_covs_widget.options = [x for x in self.df.columns if x != \"date\"]\n",
" past_covs_widget.disabled = not contains_covariates\n",
" return\n",
" if past_covs_widget.disabled == contains_covariates:\n",
" past_covs_widget.disabled = not contains_covariates\n",
" column_widget.options = [x for x in self.df.columns if x != \"date\"]\n",
"\n",
" start_n = datetime(start.year, start.month, start.day)\n",
" end_n = datetime(end.year, end.month, end.day)\n",
" calcs = self.df\n",
" if interval in [\"1d\", \"5d\", \"1wk\", \"1mo\", \"3mo\"]:\n",
" result = calcs.loc[\n",
" (calcs[\"date\"] >= start_n) & (calcs[\"date\"] <= end_n)\n",
" ]\n",
" else:\n",
" result = calcs\n",
" if not target_column:\n",
" target_column = self.df.columns[0]\n",
" kwargs = {}\n",
" if contains_covariates and past_covariates != ():\n",
" kwargs[\"past_covariates\"] = \",\".join(past_covariates)\n",
" if has_parameter(forecast_model, \"naive\"):\n",
" kwargs[\"naive\"] = naive\n",
" if has_parameter(forecast_model, \"forecast_only\"):\n",
" kwargs[\"forecast_only\"] = forecast_only\n",
" # This sets up everything to run the function on button click\n",
"\n",
" self.result = result\n",
" self.target_column = target_column\n",
" self.n_predict = 5\n",
" self.kwargs = kwargs\n",
"\n",
" def handle_click(self, to_run):\n",
" if to_run:\n",
" run_widget.value = False\n",
" else:\n",
" df = self.result.dropna()\n",
" if not df.empty:\n",
" self.forecast_model(\n",
" self.result,\n",
" target_column=self.target_column,\n",
" n_predict=5,\n",
" **self.kwargs\n",
" )\n",
"\n",
" def handle_eng(self, target, feature):\n",
" self.feature_target = target\n",
" self.feature_model = feat_engs[feature]\n",
"\n",
" def handle_click2(self, to_run):\n",
" if to_run:\n",
" add_widget.value = False\n",
" else:\n",
" kwargs = {}\n",
" if has_parameter(self.feature_model, \"target_column\"):\n",
" kwargs[\"target_column\"] = self.feature_target\n",
" self.df = self.feature_model(self.df, **kwargs)\n",
" past_covs_widget.options = self.df.columns"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e0d4de31-1b4f-4c1f-8467-ca314a578d56",
"metadata": {},
"outputs": [],
"source": [
"w_auto = widgets.Layout(width=\"auto\")\n",
"model_value = list(model_opts)[0] if model_opts else None\n",
"model_widget = widgets.Select(\n",
" options=list(model_opts),\n",
" value=model_value,\n",
" layout=widgets.Layout(\n",
" width=\"8%\",\n",
" ),\n",
")\n",
"past_covs_widget = widgets.SelectMultiple(\n",
" options=[\"\"],\n",
" value=[\"\"],\n",
" layout=widgets.Layout(\n",
" width=\"8%\",\n",
" ),\n",
")\n",
"\n",
"base_date = (datetime.today() - timedelta(days=365)).date()\n",
"start_widget = widgets.DatePicker(value=base_date, layout=w_auto, description=\"Start\")\n",
"end_widget = widgets.DatePicker(\n",
" value=datetime.today().date(), layout=w_auto, description=\"End\"\n",
")\n",
"\n",
"target_widget = widgets.Dropdown(options=[\"\"], value=\"\", description=\"Target\")\n",
"interval_widget = widgets.Dropdown(\n",
" options=interval_opts, value=\"1d\", layout=w_auto, description=\"Interval\"\n",
")\n",
"tickers_widget = widgets.Textarea(\n",
" value=\"TSLA,\", layout=widgets.Layout(width=\"auto\", height=\"100%\")\n",
")\n",
"\n",
"# Output box\n",
"naive_widget = widgets.ToggleButton(value=False, description=\"Show Naive\")\n",
"forecast_only_widget = widgets.ToggleButton(value=False, description=\"Forecast Only\")\n",
"run_widget = widgets.ToggleButton(value=False, description=\"Run Model\")\n",
"\n",
"# feat_box\n",
"feat_value = list(feat_engs.keys())[0] if feat_engs else None\n",
"column_widget = widgets.Dropdown(options=[\"\"], value=\"\", description=\"Target\")\n",
"feat_widget = widgets.Dropdown(\n",
" options=list(feat_engs.keys()), value=feat_value, description=\"Feature\"\n",
")\n",
"add_widget = widgets.ToggleButton(\n",
" value=False, description=\"Add Feature\", layout=widgets.Layout(align=\"flex_end\")\n",
") # get this to work\n",
"\n",
"selection_box = widgets.VBox([tickers_widget, target_widget])\n",
"date_box = widgets.VBox([start_widget, end_widget, interval_widget])\n",
"output_box = widgets.VBox([naive_widget, forecast_only_widget, run_widget])\n",
"feat_box = widgets.VBox([column_widget, feat_widget, add_widget])\n",
"controls = widgets.HBox(\n",
" [selection_box, model_widget, past_covs_widget, date_box, output_box, feat_box],\n",
")\n",
"if has_forecast:\n",
" chart = Chart()\n",
" widgets.interactive_output(\n",
" chart.handle_changes,\n",
" {\n",
" \"past_covariates\": past_covs_widget,\n",
" \"start\": start_widget,\n",
" \"end\": end_widget,\n",
" \"interval\": interval_widget,\n",
" \"tickers\": tickers_widget,\n",
" \"target_column\": target_widget,\n",
" \"model\": model_widget,\n",
" \"naive\": naive_widget,\n",
" \"forecast_only\": forecast_only_widget,\n",
" },\n",
" )\n",
"\n",
" widgets.interactive_output(\n",
" chart.handle_eng, {\"target\": column_widget, \"feature\": feat_widget}\n",
" )\n",
" widgets.interactive_output(chart.handle_click2, {\"to_run\": add_widget})\n",
"\n",
" stocks_view = widgets.interactive_output(chart.handle_click, {\"to_run\": run_widget})\n",
"\n",
" title_html = \"<h1>Timeseries Forecasting Dashboard</h1>\"\n",
" warning_html = '<p style=\"color:red\"=>Use a comma after EVERY stock typed.</p>'\n",
"\n",
" app_contents = [\n",
" widgets.HTML(title_html),\n",
" controls,\n",
" widgets.HTML(warning_html),\n",
" stocks_view,\n",
" ]\n",
" app = widgets.VBox(app_contents)\n",
"else:\n",
" title_html = \"<h1>Timeseries Forecasting Dashboard</h1>\"\n",
" warning_html = (\n",
" '<p style=\"color:red\"=>The forecasting dependencies are not installed.</p>'\n",
" )\n",
" app = widgets.VBox([widgets.HTML(title_html), widgets.HTML(warning_html)])\n",
"display(app)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9dbf43a2-70e1-44e9-a524-be3e97008b58",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.13"
},
"metadata": {
"interpreter": {
"hash": "e896a00ead8b521528d79ac9ef24990696f2b751eb283ab8e0d078c9c4971ffc"
}
},
"vscode": {
"interpreter": {
"hash": "bd3088e2ce83c7406a082a5b650cfc74fd1480320510d276c9fa5780b96e5fae"
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}