mirror of
https://github.com/OpenBB-finance/OpenBB.git
synced 2026-10-27 12:40:35 +00:00
Add fbprophet to prediction_techniques
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
61
prediction_techniques/fbprophet.py
Normal file
61
prediction_techniques/fbprophet.py
Normal file
@@ -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("")
|
||||
@@ -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!")
|
||||
|
||||
Reference in New Issue
Block a user