An End-to-End Guide to Time Series Forecasting with FBProphet

Time series forecasting is an important predictive modeling technique used across many domains, from retail demand planning to economic forecasting to predictive maintenance. At its core, time series forecasting is about making predictions about the future based on historical time-stamped data.

While classical statistical methods like ARIMA have been used for decades, recent years have seen the rise of more flexible and scalable machine learning-based approaches. One of the most popular open source libraries for time series forecasting is Facebook‘s Prophet library. In this post, we‘ll dive into using Prophet for end-to-end time series forecasting.

What is FBProphet?

Released as an open source project by Facebook‘s Core Data Science team in 2017, Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well.

Some of the key advantages of Prophet include:

  • Simplicity: Designed to be intuitive and require minimal hand-tuning
  • Flexibility: Easily incorporates custom seasonality, holidays, and external regressors
  • Performance: Fast and scalable even on large datasets
  • Open source: Available for anyone to use, modify and extend

A key feature of Prophet is its decomposable time series model, with three main model components:

  1. Trend: Models non-periodic changes in the value of the time series
  2. Seasonality: Represents periodic changes (e.g. weekly, yearly seasonality)
  3. Holidays: Contributes information about holidays and events that could impact predictions

By combining these into a single model, Prophet aims to both accurately fit historical data and make robust predictions for the future. This flexibility and ease of use has made it a go-to tool for data science teams in industry.

Preparing Data for FBProphet

Before we can start modeling with Prophet, we need to get our data in the right format. The input to Prophet is always a dataframe with two columns: ds and y. The ds (datestamp) column should contain a date or datetime, and the y column must be numeric and represents the value we wish to forecast.

For this tutorial, we‘ll use a public dataset of monthly car sales in Quebec from 1960 to 2022, which you can download from the link below:
Monthly Car Sales Quebec Dataset

Our data preparation steps will be:

  1. Load the CSV into a Pandas dataframe
  2. Rename the columns to ds and y
  3. Convert ds to datetime format
  4. Plot the time series to visualize trends and seasonality

Here‘s the code to load and prep the data:

import pandas as pd
from fbprophet import Prophet

df = pd.read_csv(‘https://raw.githubusercontent.com/facebook/prophet/main/examples/example_wp_log_peyton_manning.csv‘)
df = df.rename(columns={‘Month‘:‘ds‘, ‘Sales‘:‘y‘})
df[‘ds‘]= pd.to_datetime(df[‘ds‘])

df.head()

This gives us a dataframe with a ds datetime column and a y numeric column representing monthly car sales. Plotting the data, we can clearly see both an overall increasing trend and yearly seasonal patterns:

fig = px.line(df, x=‘ds‘, y=‘y‘, title=‘Monthly Car Sales in Quebec‘)
fig.show()

With our data prepped, we‘re ready to start modeling with Prophet!

Building a Time Series Model

The process of creating a forecast in Prophet is simple:

  1. Instantiate a new Prophet model
  2. Fit the model to historical data
  3. Make predictions for future dates
  4. Visualize the forecast results

To create a baseline model with Prophet, all we need to do is instantiate a Prophet object and call its fit method on our historical dataframe:

m = Prophet()
m.fit(df)

Prophet‘s model fitting routine will estimate the trend, seasonality and holiday components based on the input data. We can then make predictions for a new set of dates by calling the predict method.

To specify the dates to forecast for, we create a new dataframe with a ds column containing the future dates and pass it to predict:

future = m.make_future_dataframe(periods=24, freq=‘M‘) 
forecast = m.predict(future)

Here we‘re extending the dates 24 months into the future from the last historical date in monthly increments. The returned forecast dataframe contains the predicted yhat values for each future date, along with uncertainty intervals.

Finally, we can use Prophet‘s built-in plot function to visualize the forecast:

fig = m.plot(forecast)

This plots the actual and predicted values over time, the model components, and the forecast uncertainty intervals – a quick way to gut check model performance.

Improving Model Performance

While Prophet‘s default model is a great starting point, we can further tune and improve forecasts in a few key ways:

  1. Adjusting seasonality: Prophet will auto-detect seasonality, but we can specify custom seasonalities or turn off detection
  2. Adding holidays: Including a list of relevant holidays can improve model fit
  3. Tuning trend flexibility: Prophet offers parameters to control how sensitive the model is to recent trend changes
  4. Including regressors: Adding additional time series as model inputs can help explain variation

To demonstrate, let‘s try improving our car sales model by providing Canadian holidays and specifying a custom seasonality:

from fbprophet.models import Prophet
holidays = pd.DataFrame({
    ‘holiday‘: ‘canada_day‘,
    ‘ds‘: pd.to_datetime([‘2014-07-01‘, ‘2015-07-01‘, ‘2016-07-01‘, ‘2017-07-02‘, 
                          ‘2018-07-02‘, ‘2019-07-01‘, ‘2020-07-01‘]),
    ‘lower_window‘: -1,
    ‘upper_window‘: 1,
})
m = Prophet(holidays=holidays, yearly_seasonality=20)
forecast = m.fit(df).predict(future)

Here we defined Canada Day as a relevant holiday and adjusted the yearly seasonality prior scale to 20 (vs default of 10). Evaluating the model on a holdout period shows the MAE is slightly lower compared to the baseline default model.

We can repeat this process, tuning the model and incorporating additional variables until we arrive at a model that both fits historical data well and produces reliable future forecasts. Prophet‘s many configuration options allow for building increasingly customized and sophisticated models.

Comparing to Other Methods

While Prophet is a powerful tool for time series forecasting, it‘s certainly not the only game in town. Classical methods like ARIMA are still widely used, while other machine learning libraries like sklearn offer alternative approaches. Deep learning sequence models such as LSTMs are also increasingly being applied to forecasting problems.

So how does Prophet stack up? Compared to classical statistical methods, Prophet is generally more flexible, scalable and requires less manual effort to tune and train an effective model. It can also handle multiple seasonalities and incorporate external variables, which methods like ARIMA cannot do natively.

However, Prophet‘s model assumptions (decomposable time series, uniform noise) may not hold for all datasets, and it typically requires more historical data vs. classical approaches. Methods like ARIMA may perform better for simpler, small-scale problems.

Compared to other ML approaches, a key advantage of Prophet is its ability to handle messy data and provide robust, tunable forecasts with intuitive parameters. Libraries like sklearn require more data preprocessing and manual feature engineering.

However, Prophet may underperform ML models for larger, more complex forecasting problems. Deep learning models in particular can capture more complex non-linear patterns and scale to large high-dimensional datasets.

Ultimately, the best tool for the job will depend on the specific forecasting problem, the available data, and the relative importance of simplicity, scalability and performance. An increasingly common approach is to evaluate multiple modeling approaches and use cross-validation to select the model that performs best for the task at hand.

Real-World Applications

Time series forecasting with Prophet has been successfully applied across many business domains and use cases. Some common applications include:

  • Demand forecasting for retail and consumer goods
  • Sales and revenue forecasting
  • Capacity planning and resource allocation
  • Inventory and supply chain optimization
  • Workforce planning and staffing
  • User/subscriber growth forecasting
  • Economic and financial market forecasting

Specific real-world examples include:

  • Forecasting daily number of trips for a ride sharing service
  • Predicting hourly electricity consumption for a utility company
  • Estimating weekly sales of retail SKUs for inventory planning
  • Forecasting monthly active users for a subscription service
  • Predicting daily web traffic for capacity planning

In each of these cases, accurate time series forecasts help organizations better plan and optimize their operations. By leveraging historical patterns and trends, Prophet can provide data-driven predictions to inform key business decisions.

Conclusion and Further Reading

We‘ve covered a lot of ground in this post, from the basics of time series forecasting to a detailed look at how to use Facebook‘s Prophet library for modeling and prediction. We walked through the steps of preparing data, creating a baseline model, evaluating performance, and tuning the model to improve forecast accuracy.

Prophet is a powerful and flexible tool for time series forecasting, well-suited for a wide range of business problems. However, it‘s important to understand its assumptions and limitations, and to compare it to other modeling approaches to select the best fit for your use case.

If you‘d like to dive deeper into Prophet and time series forecasting, here are some additional resources to check out:

I hope this post has been a helpful introduction to time series forecasting with Prophet. Happy forecasting!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts