From 65f345bc7b69aae944095c74158cd1450d78cdf3 Mon Sep 17 00:00:00 2001 From: didier Date: Thu, 11 Feb 2021 21:54:23 +0000 Subject: [PATCH] Add fbprophet to prediction_techniques --- gamestonk.py | 7 ++-- prediction_techniques/fbprophet.py | 61 ++++++++++++++++++++++++++++++ prediction_techniques/pred_menu.py | 8 +++- 3 files changed, 72 insertions(+), 4 deletions(-) create mode 100644 prediction_techniques/fbprophet.py diff --git a/gamestonk.py b/gamestonk.py index 559483cc179..8bcff342c04 100644 --- a/gamestonk.py +++ b/gamestonk.py @@ -1,7 +1,6 @@ """ Example or something """ - import argparse import pandas as pd from helper_funcs import * @@ -61,6 +60,7 @@ def load(l_args, s_ticker, s_start, s_interval, df_stock): else: print(f"Loading {s_intraday} {s_ticker} stock for analysis.") + print("") return [s_ticker, s_start, s_interval, df_stock] @@ -184,10 +184,11 @@ def main(): s_interval = "1440min" # Set stock by default to speed up testing - s_ticker = "AMZN" + s_ticker = "NIO" s_start = datetime.strptime("2020-06-04", "%Y-%m-%d") ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format='pandas') - df_stock, d_stock_metadata = ts.get_daily_adjusted(symbol=s_ticker, outputsize='full') + df_stock, d_stock_metadata = ts.get_daily_adjusted(symbol=s_ticker, outputsize='full') + df_stock = df_stock.sort_index(ascending=True) df_stock = df_stock[s_start:] # Delete above in the future diff --git a/prediction_techniques/fbprophet.py b/prediction_techniques/fbprophet.py new file mode 100644 index 00000000000..293b4d22075 --- /dev/null +++ b/prediction_techniques/fbprophet.py @@ -0,0 +1,61 @@ +import argparse +import numpy as np +import pandas as pd +import matplotlib.pyplot as plt +from pandas.plotting import register_matplotlib_converters +register_matplotlib_converters() +import datetime +from datetime import datetime +from alpha_vantage.timeseries import TimeSeries +from helper_funcs import * +from fbprophet import Prophet +import warnings +warnings.simplefilter("ignore") + +# ----------------------------------------------------- FBPROPHET ----------------------------------------------------- +def fbprophet(l_args, s_ticker, s_interval, df_stock): + parser = argparse.ArgumentParser(prog='fbprophet', + description="""Facebook Prophet is a forecasting procedure that is fast and provides + completely automated forecasts that can be tuned by hand by data scientists and analysts. + It was developed by Facebook's data science team and is open source. """) + + parser.add_argument('-d', "--days", action="store", dest="n_days", type=check_positive, default=5, help='prediction days') + + try: + (ns_parser, l_unknown_args) = parser.parse_known_args(l_args) + + if l_unknown_args: + print(f"The following args couldn't be interpreted: {l_unknown_args}\n") + return + + df_stock = df_stock.sort_index(ascending=True) + df_stock.reset_index(level=0, inplace=True) + df_stock = df_stock[['date', '5. adjusted close']] + df_stock = df_stock.rename(columns={"date": "ds", "5. adjusted close": "y"}) + df_stock['ds'] = pd.to_datetime(df_stock['ds']) + + model = Prophet(yearly_seasonality=False, daily_seasonality=False) + model.fit(df_stock) + + l_pred_days = get_next_stock_market_days(last_stock_day=pd.to_datetime(df_stock['ds'].values[-1]), n_next_days=ns_parser.n_days) + close_prices = model.make_future_dataframe(periods=ns_parser.n_days) + forecast = model.predict(close_prices) + + fig, ax = plt.subplots() + model.plot(forecast, ax=ax, xlabel='Time', ylabel='Share Price ($)') + xmin, xmax, ymin, ymax = ax.axis() + ax.vlines(df_stock['ds'].values[-1], ymin, ymax, linewidth=2, linestyle='--', color='k') + plt.axvspan(l_pred_days[0], l_pred_days[-1], facecolor='tab:orange', alpha=0.2) + plt.ylim(ymin, ymax) + plt.xlim(df_stock['ds'].values[0], get_next_stock_market_days(last_stock_day=l_pred_days[-1], n_next_days=1)) + plt.title(f"Fb Prophet on {s_ticker} - {ns_parser.n_days} days prediction") + plt.show() + + print("") + print("Prediction prices:") + df_pred = forecast['yhat'][-ns_parser.n_days:].apply(lambda x: f"{x:.2f} $") + print(df_pred.to_string(index=False)) + print("") + + except: + print("") diff --git a/prediction_techniques/pred_menu.py b/prediction_techniques/pred_menu.py index 7ece85701a2..bbbc52ed99f 100644 --- a/prediction_techniques/pred_menu.py +++ b/prediction_techniques/pred_menu.py @@ -13,6 +13,7 @@ from prediction_techniques import sma from prediction_techniques import knn from prediction_techniques import regression from prediction_techniques import arima +from prediction_techniques import fbprophet # ----------------------------------------------------------------------------------------------------------------------- def print_prediction(s_ticker, s_start, s_interval): @@ -37,6 +38,7 @@ def print_prediction(s_ticker, s_start, s_interval): print(" cubic cubic regression (polynomial 3)") print(" regression regression (other polynomial)") print(" arima autoregressive integrated moving average") + print(" prophet Facebook's prophet prediction") #print(" arima") #print(" rnn") #print(" lstm") @@ -52,7 +54,7 @@ def pred_menu(df_stock, s_ticker, s_start, s_interval): pred_parser.add_argument('cmd', choices=['help', 'q', 'quit', 'sma', 'knn', 'linear', 'quadratic', 'cubic', 'regression', - 'arima']) + 'arima', 'prophet']) print_prediction(s_ticker, s_start, s_interval) @@ -105,6 +107,10 @@ def pred_menu(df_stock, s_ticker, s_start, s_interval): elif ns_known_args.cmd == 'arima': arima.arima(l_args, s_ticker, s_interval, df_stock) + # ------------------------------------------------ FBPROPHET ------------------------------------------------ + elif ns_known_args.cmd == 'prophet': + fbprophet.fbprophet(l_args, s_ticker, s_interval, df_stock) + # ------------------------------------------------------------------------------------------------------------ else: print("Command not recognized!")