Forecasting by FB Prophet in Colab

PropTech@ecyY
4 min readMay 31, 2021

There are many forecasting tools available in the market, even Excel worksheet also provides a simple forecasting function, which I have shown how to use it (Yiu, 2019). Other more sophisticated software can provide ARIMA and HP Filter methods for forecasting, but they can be costly.

I learned that FB Prophet provides an open source code and free forecasting tool in R or Python. It allows more detailed parameter settings for making forecasts including three additive components: trend, seasonality and holidays. For more details, one may refer Lyla (2019).

Here is a trial of building a forecaster of HSI. To make it very simple, I simply do the following two tasks:

  1. read and plot time series data from Yahoo Finance into Colab; and
  2. make a forecast on the time series by FB Prophet.

If you do not know how to use Colab, please refer to my previous article at Yiu (2020). For more information of FB Prophet, here is the link —https://facebook.github.io/prophet/. This simple example has only 10 routines, see whether they are correct or not. All lines start with a # sign are remarks only:

1. install FB Prophet and yfinance

#install FB Prophet and yfinance
!pip install prophet
!pip install yfinance

2. import pd, plt and Prophet

#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

3. read the time series data (here I use ^HSI from Yahoo Finance)

#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())

You may also read data directly from an URL, for example, the data provided in the Our World in Data website are downloadable via an URL. For example, you can program in Colab by: url=”https://covid.ourworldindata.org/data/owid-covid-data.csv"

df=pd.read_csv(url)

4. show the data collected

#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())

5. plot the time series chart

#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()

6. define data x, y

#define data x,y
#data = df.reset_index()[['Date', 'Close']]
#data.columns = ['ds' , 'y']

7. define the parameters for the forecasting model — trend and seasonality

#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"}

8. define the forecasting model

#define the forecasting model and set the cap
model = Prophet(model_params)

9. define the forecast

#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)

10. plot the chart with the forecast

#plot the model forecast chart with component charts in trend and seasonality 
model.plot_components(forecast)
model.plot(forecast)

Here shows the results. Figure 1 shows the HSI and its forecast by FB Prophet. Figure 2 shows the forecast components, with the upper chart shows the trend and the lower chart shows the seasonality.

Figure 1 Time Series and Forecast by FB Prophet
Figure 2 Forecast Components by FB Prophet

If you would like to show the forecasting values in numeric figures, you can program in Colab by:

#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’]]

The first two rows extend the default maximum numbers of rows and columns from 5 to no-limit, thus all the data will be shown. The third row specifies the table in four columns, showing the date, forecasting value, lower bound and upper bound, respectively, as illustrated below.

— —

I have uploaded my1st Time Series Forecaster by FBProphet at the following Github: https://github.com/Chung-collab/great/blob/master/my1st_ts_forecaster_fbprophet.ipynb

I also produce a Youtube at https://youtu.be/ItzY73xpcyY (Yiu, 2021) to explain in details.

[Caveat: this is just a trial and the forecast is not sophisticated enough to discuss for real life predictions. Please do not consider the results as any advice on the future predictions.]

References

Jain, A. P. (2021) ARIMA & SARIMA: Real-World Time Series Forecasting (Advanced Guide), neptune blog, 31 May. https://neptune.ai/blog/arima-sarima-real-world-time-series-forecasting-guide

Lyla, Y. (2019) A Quick Start of Time Series Forecasting with a Practical Example using FB Prophet, Medium, Jan 3. https://towardsdatascience.com/a-quick-start-of-time-series-forecasting-with-a-practical-example-using-fb-prophet-31c4447a2274

Yiu, C.Y. (2019) Excel Forecasts a 40% Plummet of HK Housing Price! Medium, Apr 15. https://ecyy.medium.com/2-forecasting-methods-by-excel-1991b5b7d111

Yiu, C.Y. (2020) Learning Machine Learning — How to Code without Learning Coding, Medium, Feb 6. https://ecyy.medium.com/learning-machine-learning-how-to-code-without-learning-coding-9fc4291902b

Yiu, C.Y. (2021) My First Forecaster by FB Prophet in Colab, Youtube, May 31. https://youtu.be/ItzY73xpcyY

--

--