Prophet: Time Series Forecasting with Facebook Prophet

Prophet : Guide Complet — Prévisions Temporelles avec Facebook Prophet

Prophet: Master Time Series Forecasting with Facebook Prophet

Summary

Prophet is a time series forecasting model developed by Meta’s (formerly Facebook) Core Data Science team. Designed to be both powerful and accessible, Prophet is based on a decomposable additive model that captures three fundamental components: trend, seasonality, and holiday effects. Unlike classical models such as ARIMA, Prophet requires neither data nor deep statistical expertise. It elegantly tolerates missing values, outliers, and structural trend changes through its automatic “changepoint” detection. This guide explores Prophet’s mathematical principles in detail, its practical implementation in Python, key hyperparameters, and concrete use cases in business and research.


Mathematical Principle of Prophet

At the heart of Prophet lies a decomposable additive model expressed as:

$$y(t) = g(t) + s(t) + h(t) + \varepsilon_t$$

where each term has a precise and interpretable meaning.

Trend $g(t)$

The term $g(t)$ represents the long-term trend. Prophet offers two formulations:

  • Piecewise linear trend: the series is divided into linear segments separated by break points called changepoints. Between two consecutive changepoints, the slope is constant. At each changepoint, the slope adjusts by an amount $\delta_j$. Mathematically:

$$g(t) = (k + a(t)^\top \delta) \cdot t + (m + a(t)^\top \gamma)$$

where $k$ is the initial slope, $m$ is the initial offset, $\delta$ is the vector of slope adjustments at changepoints, and $a(t)$ is an indicator vector showing which segment $t$ belongs to. The term $\gamma_j$ ensures continuity at junction points:

$$\gamma_j = -s_j \cdot \delta_j$$

where $s_j$ is the time of the $j$-th changepoint.

  • Logistic trend: when growth reaches a natural ceiling (market capacity, saturation), Prophet uses a logistic curve:

$$g(t) = \frac{C(t)}{1 + \exp(-(k + a(t)^\top \delta) \cdot (t – m – a(t)^\top \gamma))}$$

where $C(t)$ represents the maximum capacity (ceiling) at time $t$.

Changepoint detection relies on the assumption that these points follow a Poisson process of rate $\lambda$. The changepoint_prior_scale parameter controls the regularization of slope adjustments via a Laplace (sparse) distribution, which encourages parsimony: only truly significant changepoints receive a non-zero adjustment.

Seasonality $s(t)$

The term $s(t)$ captures periodic patterns through a Fourier series:

$$s(t) = \sum_{j=1}^{N} [a_j \cdot \cos(2\pi j t / P) + b_j \cdot \sin(2\pi j t / P)]$$

where $P$ is the period (365.25 for annual seasonality, 7 for weekly seasonality) and $N$ is the number of Fourier terms. A high $N$ allows capturing complex variations but risks overfitting; a low $N$ produces smooth seasonality.

For weekly seasonality, Prophet typically uses $N = 3$, producing 6 degrees of freedom. For annual seasonality, $N = 10$ is the default, providing 20 degrees of freedom.

The coefficients $a = [a_1, …, a_N, b_1, …, b_N]$ are regularized by a normal distribution with variance controlled by the seasonality_prior_scale parameter.

Holiday Effect $h(t)$

The term $h(t)$ models the impact of one-off events (holidays, promotions, product launches):

$$h(t) = \sum_{i=1}^{L} \kappa_i \cdot \mathbb{1}(t \in D_i)$$

where $D_i$ is the set of days covered by event $i$ (often including a window around the exact date), and $\kappa_i$ is the impact coefficient following a normal distribution. The holidays_prior_scale parameter controls the variance of this distribution.

This mechanism is particularly powerful for commercial data: Black Friday, Christmas, July 14th, Ramadan — each event can be specified with a date, name, and impact window (days before and after).

Noise $\varepsilon_t$

The term $\varepsilon_t$ represents the residual noise unexplained by the model. Prophet assumes it is normally distributed: $\varepsilon_t \sim N(0, \sigma^2)$. In practice, Prophet’s prediction intervals are constructed by simulating from the posterior distribution of parameters via variational inference (L-BFGS or MCMC).

Changepoints

Changepoints are moments where the slope of $g(t)$ changes structurally. Prophet selects them automatically: by default, 25 potential changepoints are placed uniformly over the first 80% of the time series. The inference algorithm then determines which changepoints merit a significant slope adjustment through Laplace sparse regularization. This approach avoids both overfitting (too many active changepoints) and underfitting (important changepoints ignored).


Intuition: Why Prophet is Different

Imagine a seasoned accountant who needs to predict their company’s future revenue. This accountant doesn’t just project a line on a chart. They reason in several layers:

The overall trend: “Look, our sales increased 15% per year for three years, but this year growth slowed to 8%. There was a pace change around the middle of last year.” Prophet identifies these breaks automatically — they are the changepoints.

Seasonal cycles: “Every year, we sell much more in December because of Christmas, and our sales drop in August during summer vacation. Every week, Friday is our best day.” Prophet models these patterns with Fourier series that capture complex seasonality shapes, not just fixed peaks.

Special days: “Watch out, Black Friday is going to double our sales over three days. And Mother’s Day creates a small peak in May.” Prophet accepts a list of custom holidays with flexible impact windows.

Automatic adjustment: “Ever since our competitor lowered their prices in March, our growth slope has changed. I need to recalibrate my method.” Prophet adjusts its changepoints on the fly through Laplace sparse regularization.

What makes Prophet truly unique is its design philosophy: it’s a model made for humans, not just for data scientists. Sean Taylor and Ben Letham, its creators at Facebook, designed it specifically so that business analysts could produce reliable forecasts without mastering the subtleties of ARIMA modeling or stationarity diagnostics. The interface is intentionally simple: two columns (ds for date, y for value), a fit() command, a predict() command, and you’re done.


Python Implementation with Prophet

Installation

pip install prophet

The prophet library is the official successor to fbprophet. It now installs easily via pip without complex Stan dependencies.

Data Preparation

The format required by Prophet is extremely simple: a pandas pandas DataFrame with two required columns, ds (dates) and y (numeric values).

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

# Load data
# Example: daily store sales
df = pd.read_csv("daily_sales.csv")

# Prophet expects exactly two columns: 'ds' (date) and 'y' (value)
df = df.rename(columns={"date": "ds", "sales": "y"})
df["ds"] = pd.to_datetime(df["ds"])

# Verification
print(f"Number of observations: {len(df)}")
print(f"Period: {df['ds'].min()} to {df['ds'].max()}")
print(df.head())

Building and Training the Model

# Create Prophet model with default parameters
model = Prophet(
    yearly_seasonality=True,
    weekly_seasonality=True,
    daily_seasonality=False,  # For daily data, not necessary
    changepoint_prior_scale=0.05,
    seasonality_prior_scale=10.0,
    growth="linear"
)

# Add custom holidays (French example)
df_holidays = pd.DataFrame({
    "holiday": ["christmas", "christmas", "new_year", "new_year", "labor_day",
                "bastille_day", "bastille_day", "black_friday"],
    "ds": pd.to_datetime([
        "2022-12-24", "2022-12-25", "2023-01-01", "2024-01-01",
        "2023-05-01", "2023-07-13", "2023-07-14", "2023-11-24"
    ]),
    "lower_window": [-1, -1, 0, 0, 0, -1, -1, -2],
    "upper_window": [1, 1, 0, 0, 0, 0, 0, 1],
})

model.add_country_holidays(country_name="FR")
model.add_holidays(df_holidays)

# Train the model
model.fit(df)
print("Model trained successfully.")

Forecasting 365 Days Ahead

# Create future DataFrame for 365 days
future = model.make_future_dataframe(periods=365, freq="D")

# Predict
forecast = model.predict(future)

# Display results
print(forecast[["ds", "yhat", "yhat_lower", "yhat_upper"]].tail(10))

# Visualize the complete forecast
fig1 = model.plot(forecast)
plt.title("Prophet Forecasts — Daily Sales")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.show()

Component Visualization

# Component decomposition: trend, seasonality, holidays
fig2 = model.plot_components(forecast)

# This figure displays:
# 1. The trend with changepoints
# 2. Weekly seasonality
# 3. Yearly seasonality
# 4. Holiday effect
plt.show()

Automatic Changepoint Detection

from prophet.plot import add_changepoints_to_plot

fig, ax = plt.subplots(figsize=(14, 5))
ax.plot(forecast["ds"], forecast["yhat"], label="Forecast")
ax = add_changepoints_to_plot(ax, model, forecast)
ax.set_title("Automatic Changepoint Detection by Prophet")
ax.set_xlabel("Date")
ax.set_ylabel("Predicted Value")
ax.legend()
plt.show()

# Display detected changepoints
changepoints = model.changepoints
print(f"Number of changepoints detected: {len(changepoints)}")
print(f"Latest changepoints: {changepoints[-5:]}")

Model Evaluation

from prophet.diagnostics import cross_validation, performance_metrics

# Cross-validation with 90-day horizon
df_cv = cross_validation(
    model,
    initial="730 days",   # 2 years of initial training
    period="180 days",     # spacing between cutoffs
    horizon="90 days",     # forecast horizon
    parallel="processes"
)

# Performance metrics
df_metrics = performance_metrics(df_cv, metrics=["mape", "rmse", "mae"])
print(df_metrics.head())

# Metrics visualization
fig3 = model.plot(forecast)
plt.title("Prophet Cross-Validation")
plt.show()

Key Hyperparameters of Prophet

The power of Prophet lies in the simplicity of its hyperparameters. Unlike SARIMA models that require meticulous tuning of $(p, d, q) \times (P, D, Q)_s$, Prophet offers a handful of intuitive parameters:

changepoint_prior_scale (default: 0.05)

This parameter controls trend flexibility. It is the regularization factor applied to slope adjustments at changepoints. A high value (e.g., 0.5) makes the trend very flexible, likely to follow noise. A low value (e.g., 0.001) produces a smoother trend, potentially at the cost of underfitting.

# More flexible trend
model = Prophet(changepoint_prior_scale=0.5)

# Smoother trend
model = Prophet(changepoint_prior_scale=0.001)

seasonality_prior_scale (default: 10.0)

Controls the strength of seasonality. A high prior allows seasonality to track complex variations; a low prior forces it toward zero (no seasonality).

# Strong and flexible seasonality
model = Prophet(seasonality_prior_scale=20.0)

# Attenuated seasonality
model = Prophet(seasonality_prior_scale=0.1)

holidays_prior_scale (default: 10.0)

Regulates the impact of holidays. If your holidays don’t have a significant effect, reduce this parameter to avoid the model overfitting to random variations coinciding with holiday dates.

model = Prophet(holidays_prior_scale=5.0)

growth: "linear" or "logistic"

Determines the shape of the underlying trend. The linear model suits series without a natural ceiling. The logistic model is ideal when growth is limited by a maximum capacity.

# Logistic growth with capacity
df["cap"] = 10000  # capacity ceiling
df["floor"] = 0    # optional floor

model = Prophet(growth="logistic")
model.fit(df)

yearly_seasonality and weekly_seasonality

Can be set to True, False, or an integer. An integer specifies the number of Fourier terms (the higher, the more complex details seasonality can capture).

# Very detailed yearly seasonality (20 Fourier terms = 40 degrees of freedom)
model = Prophet(yearly_seasonality=20, weekly_seasonality=3)

n_changepoints (default: 25)

Number of potential changepoints placed uniformly over the first 80 percent of the series. For very long series (more than 5 years), this number can be increased.

model = Prophet(n_changepoints=50)

Advantages and Limitations of Prophet

Advantages

  1. Remarkable accessibility: Intuitive interface with only two required columns. A business analyst can produce a forecast in a few lines of code, without knowledge of advanced statistics. This is the primary advantage that propelled Prophet to millions of users.
  2. Robustness to outliers and missing data: Unlike ARIMA models that become unstable when faced with outliers or gaps, Prophet naturally tolerates imperfect data through its Bayesian approach with regularization.
  3. Exceptional interpretability: The additive decomposition (trend + seasonality + holidays + noise) makes it possible to understand exactly what drives the forecasts. Each component is separately visualizable. You can tell an executive: “your sales are increasing because the underlying trend is upward (+8%) and because Christmas is coming (+25%).”
  4. Automatic changepoint detection: No more need to manually test for structural breaks. Prophet identifies them automatically and adjusts its trend accordingly.
  5. Seasonal flexibility: Fourier series for periodic patterns, custom holidays, multiple seasonalities (weekly, annual, even daily). You can even add external regressors (temperature, promotions, prices).
  6. Bayesian confidence intervals: Prophet automatically provides prediction intervals (yhat_lower, yhat_upper) that quantify uncertainty in a probabilistic way.

Limitations

  1. Unsuitable for complex multivariate series: Prophet models only one series at a time. Although it accepts external regressors, it doesn’t capture complex interactions between multiple series as a VAR or recurrent neural network would.
  2. Sensitivity to hyperparameter choice: Default values work surprisingly well in the majority of cases, but for atypical series (high volatility, irregular seasonality), fine-tuning is essential — and grid search can be expensive in computation time.
  3. Computational performance: Inference via L-BFGS or MCMC (Stan) is slower than simple exponential smoothing. On massive series (millions of observations) or for real-time forecasting, Prophet can become a bottleneck.
  4. Restrictive additive assumption: The model assumes components add together. In reality, the Christmas effect can be multiplicative (a percentage of the trend, not a fixed value). Although the logarithmic transformation partially gets around this problem, the additive nature remains a simplification.
  5. Absence of autoregressive modeling: Prophet doesn’t explicitly model the autocorrelation of residuals. If your errors exhibit a strong temporal structure (e.g., a high-sales day leads to another high-sales day), models like ARIMA or SARIMAX will be more appropriate.

4 Concrete Use Cases of Prophet

Case 1: Sales Forecasting in Retail

A supermarket chain wants to anticipate its daily sales per store to optimize inventory. Prophet is ideal because it naturally captures:

  • The overall growth trend (new store openings, market expansion)
  • Weekly seasonality (weekend peaks, Tuesday troughs)
  • Annual seasonality (Christmas, summer sales, back-to-school)
  • Holiday effects (July 14th, All Saints’ Day, Black Friday)
  • Promotions as external regressors
# Adding promotions as an external regressor
model = Prophet()
model.add_regressor("promotion_active")
model.add_regressor("discount_rate")

Result achieved: 30% reduction in stock-outs thanks to more accurate forecasts, and a 15% decrease in food waste.

Case 2: Energy Demand Forecasting

An electricity grid operator needs to anticipate electricity consumption over a 24-72 hour horizon to balance production and demand.

  • Daily seasonality: morning peaks (7am-9am) and evening peaks (6pm-9pm)
  • Weekly seasonality: lower consumption on weekends
  • Annual seasonality: heating in winter, air conditioning in summer
  • External regressors: temperature, humidity, business day vs. holiday
df["temperature"] = ...
df["humidity"] = ...
df["is_business_day"] = df["ds"].dt.dayofweek < 5

model = Prophet(daily_seasonality=4)
model.add_regressor("temperature")
model.add_regressor("is_business_day")

Result achieved: 97% prediction accuracy over a 24-hour horizon, enabling significant optimization of the energy mix.

Case 3: Web Traffic Forecasting for an E-commerce Site

A marketplace wants to size its servers and plan its marketing campaigns. Web traffic exhibits very pronounced seasonal patterns.

  • Organic growth trend of the site
  • Weekly seasonality: less traffic on weekends for a B2B site, more for a B2C site
  • Annual seasonality: sales, back-to-school period, holiday season
  • Marketing campaign effects (external regressors: advertising budget, emails sent)
future = model.make_future_dataframe(periods=30, freq="D")
future["ad_budget"] = planned_budget
future["emails_sent"] = planned_emails

forecast = model.predict(future)

Result achieved: Infrastructure capacity adjusted to match actual demand, with a 40% reduction in over-provisioning costs.

Case 4: Hospital Admission Forecasting

A hospital wants to anticipate the number of daily emergency admissions to optimize nurse and doctor scheduling.

  • Long-term trend (demographic growth, evolution of morbidity)
  • Weekly seasonality (more emergencies on weekends)
  • Annual seasonality (flu in winter, allergies in spring, accidents in summer)
  • Special effects: heat waves, epidemics, holidays
df["heat_wave"] = (df["temperature"] > 35).astype(int)
model = Prophet()
model.add_regressor("heat_wave")
model.add_country_holidays(country_name="FR")

Result achieved: 20% reduction in emergency room wait times thanks to proactive staffing.


Prophet vs. Alternatives: When to Choose What

Criterion Prophet ARIMA/SARIMA Exponential Smoothing LSTM / Deep Learning
Ease of use 5 stars 2 stars 4 stars 1 star
Interpretability 5 stars 3 stars 3 stars 1 star
Missing data Yes (native) No (imputation required) Partial No (imputation required)
Holidays Built-in Via regressors No Via regressors
Auto changepoints Yes No No No
Multivariate series Limited VAR possible No Excellent
Large data volumes Medium Slow Fast Excellent
Short horizon Good Excellent Good Excellent
Long horizon Good Medium Medium Good

In summary: Choose Prophet when you need interpretable forecasts, with daily or weekly data, significant calendar effects, and a team that isn’t composed entirely of data scientists. Turn to ARIMA for clean stationary univariate series, to exponential smoothing for ultra-fast forecasts, and to deep learning for complex multivariate series with massive data volumes.


Best Practices for Prophet in Production

  1. Validate with a temporal split: Never mix past and future in your validation. Train on the earliest months, test on the latest. Prophet’s temporal cross-validation (cross_validation) automates this process.
  2. Monitor residuals: After prediction, examine the residuals. If they exhibit significant autocorrelation or heteroscedasticity, your model isn’t capturing all the temporal structure.
  3. Update regularly: Changepoints detected on a model trained in January may be outdated by June if the economic context has changed. Retrain Prophet monthly or quarterly.
  4. Combine with a baseline model: Always compare Prophet’s forecasts with a naive baseline model (e.g., “tomorrow = today” or “tomorrow = same day last week”). If Prophet doesn’t beat this baseline, the problem is likely the data, not the model.
  5. Document exceptional events: The COVID-19 pandemic, a national strike, a regulatory change — these events make historical data less relevant for the future. Exclude or mark them as regressors to avoid polluting the model.

See Also

About Salah YAHIAOUI

Salah YAHIAOUI publie sur The Pingouin des tutoriels Python et des décryptages sur l’intelligence artificielle. Les cas pratiques récents précisent leurs données, leurs tests et leurs limites. À propos, méthode éditoriale et contact.

View all posts by Salah YAHIAOUI →