Introduction

This example demonstrates how to use Facebook's Prophet library for time series forecasting. Prophet is a procedure for generating high-quality forecasts of business time series that have strong multiple seasonal effects and several seasons of historical data. It is robust to missing data and shifts in the trend, and typically handles outliers well.

What is Prophet?

Prophet is an additive regression model where non-linear trends are fit with daily, weekly, and yearly seasonality, plus holiday effects. It's designed to be easy to use for experts and makes the underlying model interpretable.

Key Features:

  • Seasonality: Automatically handles daily, weekly, and yearly seasonality.
  • Holidays: Allows inclusion of custom holiday effects.
  • Trend Flexibility: Can model changepoints to allow the growth rate to vary over time.
  • Robustness: Handles missing data and outliers effectively.
  • Interpretability: Provides interpretable parameters for seasonality and trend.

Prerequisites

To run this example, you will need:

  • Python 3.7+
  • pandas
  • numpy
  • matplotlib
  • prophet (from conda install -c conda-forge prophet or pip install prophet)

Code Example

Below is a simplified example of how to use Prophet for sales forecasting. In a real-world scenario, you would load your specific sales data.

Python

import pandas as pd
from prophet import Prophet
import matplotlib.pyplot as plt

# Sample Data (Replace with your actual data)
# 'ds' is the timestamp column, 'y' is the value to forecast
data = {'ds': pd.to_datetime(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05',
                              '2023-01-06', '2023-01-07', '2023-01-08', '2023-01-09', '2023-01-10']),
        'y': [10, 12, 15, 13, 16, 18, 20, 22, 25, 23]}
df = pd.DataFrame(data)

# Initialize and fit the model
model = Prophet()
model.fit(df)

# Create a future dataframe for forecasting
future = model.make_future_dataframe(periods=5) # Forecast next 5 days

# Make predictions
forecast = model.predict(future)

# Plot the forecast
fig1 = model.plot(forecast)
plt.title('Sales Forecast with Prophet')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()

# Plot the components of the forecast
fig2 = model.plot_components(forecast)
plt.show()
                    

Understanding the Forecast

The forecast generated by Prophet includes several key components:

  • yhat: The forecasted value.
  • yhat_lower, yhat_upper: The uncertainty interval for the forecast.
  • Seasonality: Visualizations of daily, weekly, and yearly patterns.
  • Trend: The underlying trend of the time series.

Visualizations

The Prophet library provides convenient plotting functions to visualize the forecast and its components. The first plot shows the historical data, the forecasted values, and the uncertainty intervals. The second plot breaks down the forecast into its constituent parts: trend, weekly seasonality, and yearly seasonality (if applicable).