Forecasting by FB Prophet in Colab

#install FB Prophet and yfinance
!pip install prophet
!pip install yfinance
#import pd, plt and Prophet
import yfinance as yf
import
pandas as pd
import matplotlib.pyplot as plt
import datetime as datetime
from
prophet import Prophet
#read time series data from Yahoo Finance by yfinance
HSI = yf.Ticker("^HSI")
start = datetime.datetime(2015,1,1)
end = datetime.datetime(2021,9,5)
hist = HSI.history(start=start, end=end, auto_adjust=True)
hist
#if import data via url: #url="https://query1.finance.yahoo.com/v7/finance/download/^HSI?period1=1420066800&period2=
1622437200&interval=1d&events=history&crumb=tO1hNZoUQeQ"
#df=pd.read_csv(url)
#print(df.head())
#show the data table in Date, Stock Price (Close)
df = pd.DataFrame()
df['ds'] = hist.index
df['y'] = hist['Close'].values
df.tail(10)
#show the information and descriptions of the data collected
#print(df.reset_index().info())
#print(df.reset_index().describe())
#plot the chart
plt.figure(figsize=(14,6))
plt.title('Close Price History')
plt.plot(df['Close'])
plt.xlabel('Year', fontsize=16)
plt.ylabel('Close Price' , fontsize=16)
plt.show()
#define data x,y
#data = df.reset_index()[['Date', 'Close']]
#data.columns = ['ds' , 'y']
#define the forecasting model parameters, trend = logistic growth, yearly seasonality = multiplicative, no holiday parameter
model_params = {"daily_seasonality": False, "weekly_seasonality": False, "yearly_seasonality": True, "seasonality_mode": "multiplicative", "growth": "logistic"}
#define the forecasting model and set the cap
model = Prophet(model_params)
#define future as the future 365 days' data, and define forecast as predicting the future by the forecasting model
model.fit(df)
future = model.make_future_dataframe(365, freq='D')
forecast = model.predict(future)
#plot the model forecast chart with component charts in trend and seasonality 
model.plot_components(forecast)
model.plot(forecast)
Figure 1 Time Series and Forecast by FB Prophet
Figure 2 Forecast Components by FB Prophet
#show all the forecasting values in a table
pd.set_option(‘display.max_rows’, None)
pd.set_option(‘display.max_columns’, None)
forecast[[‘ds’, ‘yhat’, ‘yhat_lower’, ‘yhat_upper’]]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store