Time Series Forecasting in Python: Prophet vs statsforecast vs ARIMA

Forecast daily data with Prophet, AutoARIMA, AutoETS, and statsmodels ARIMA, handle two seasonal cycles, and compare the models with rolling backtests.

To forecast a time series in Python, use Prophet().fit(df) from the prophet package, or StatsForecast(models=[AutoARIMA(season_length=7)], freq="D") from statsforecast, which picks the ARIMA order for you. Both take a DataFrame with a date column ds and a value column y. Compare them, and a simple baseline, on dates they haven't seen.

Install them with pip install prophet statsforecast. The code here was run with Prophet 1.5, statsforecast 2.0, and statsmodels 0.14.

Quick Example

This example makes up three and a half years of daily visits to a climbing gym, with busier weekends, busier winters, and slow growth. The last 90 days are held out for testing.

import logging

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from prophet import Prophet
from statsforecast import StatsForecast
from statsforecast.models import AutoARIMA, AutoETS, SeasonalNaive

logging.getLogger("cmdstanpy").setLevel(logging.WARNING)

rng = np.random.default_rng(38)
dates = pd.date_range("2022-01-01", "2025-06-30")
weekly = np.array([0.85, 0.95, 1.0, 0.98, 0.9, 1.3, 1.2])[dates.dayofweek]
yearly = 1 + 0.22 * np.cos(2 * np.pi * (dates.dayofyear - 20) / 365.25)
trend = 180 + 0.09 * np.arange(len(dates))
noise = np.zeros(len(dates))
for i in range(1, len(dates)):
    noise[i] = 0.6 * noise[i - 1] + rng.normal(0, 0.05)
visits = pd.DataFrame({
    "unique_id": "gym",
    "ds": dates,
    "y": np.round(trend * weekly * yearly * (1 + noise)),
})
horizon = 90
train, test = visits[:-horizon], visits[-horizon:]

# statsforecast: three models in one call
sf = StatsForecast(
    models=[SeasonalNaive(season_length=7), AutoARIMA(season_length=7),
            AutoETS(season_length=7)],
    freq="D")
forecast = sf.forecast(df=train, h=horizon, level=[80])

# Prophet
np.random.seed(38)  # makes Prophet's intervals repeatable
prophet = Prophet(seasonality_mode="multiplicative")
prophet.fit(train[["ds", "y"]])
future = prophet.make_future_dataframe(periods=horizon, include_history=False)
pred = prophet.predict(future)
forecast["Prophet"] = pred.yhat.values
forecast["Prophet-lo-80"] = pred.yhat_lower.values
forecast["Prophet-hi-80"] = pred.yhat_upper.values

def mae(predicted):
    return np.mean(np.abs(test.y.values - np.asarray(predicted)))

names = ["SeasonalNaive", "AutoARIMA", "AutoETS", "Prophet"]
for name in names:
    print(f"{name:<14} MAE {mae(forecast[name]):.1f}")

recent = visits[-180:]

def plot_forecasts(data, names, colors):
    fig, axes = plt.subplots(len(names), 1, figsize=(8, 2.2 * len(names)),
                             sharex=True, sharey=True, layout="constrained")
    for ax, name, color in zip(axes, names, colors):
        ax.plot(recent.ds, recent.y, color="#6b7280", lw=1, label="Actual")
        ax.plot(data.ds, data[name], color=color, lw=1.6, label="Forecast")
        ax.fill_between(data.ds, data[f"{name}-lo-80"],
                        data[f"{name}-hi-80"], color=color, alpha=0.2,
                        label="80% interval")
        ax.axvline(test.ds.iloc[0], color="#111827", ls=":")
        ax.set_title(f"{name}  (MAE {mae(data[name]):.1f})", loc="left")
        ax.legend(loc="lower left", ncols=3, fontsize=8)
    fig.supylabel("Daily visits")
    axes[0].set_ylim(80, 480)
    plt.show()

plot_forecasts(forecast, ["AutoARIMA", "AutoETS", "Prophet"],
               ["#2563eb", "#7c3aed", "#ea580c"])

Three forecasts of 90 days of gym visits: AutoARIMA and AutoETS stay level while Prophet follows the seasonal decline

Prophet's error is 12.4 visits a day, compared with 29.0 for AutoARIMA, 32.6 for AutoETS, and 37.6 for repeating the last week. The last three only model the weekly pattern, so they carry spring levels into summer and forecast about 25 visits too many on average. Prophet detects the yearly cycle on its own, and its 80% interval contains 80% of the held-out days.

This data suits Prophet: it was built from a linear trend, a smooth yearly cycle, and a weekly pattern, which are the shapes Prophet assumes.

How to Handle Weekly and Yearly Seasonality in ARIMA

season_length=7 only describes the weekly cycle, and a seasonal ARIMA with a period of 365 is impractically slow. Two ways to add the yearly cycle in statsforecast:

  • Fourier terms: give ARIMA a few sine and cosine columns with a one-year period as extra inputs. Their future values are known, so pass them as X_df.
  • MSTL: MSTL(season_length=[7, 365]) separates both cycles from the trend, then forecasts what's left.
from statsforecast.models import MSTL

def add_fourier(df, order=3):
    angle = 2 * np.pi * df.ds.dt.dayofyear / 365.25
    for k in range(1, order + 1):
        df = df.assign(**{f"sin{k}": np.sin(k * angle),
                          f"cos{k}": np.cos(k * angle)})
    return df

extended = add_fourier(visits)
sf_fourier = StatsForecast(
    models=[AutoARIMA(season_length=7, alias="ARIMA + Fourier")], freq="D")
seasonal = sf_fourier.forecast(
    df=extended[:-horizon], h=horizon, level=[80],
    X_df=extended[-horizon:].drop(columns="y"))

mstl = StatsForecast(models=[MSTL(season_length=[7, 365])], freq="D")
seasonal = seasonal.merge(mstl.forecast(df=train, h=horizon, level=[80]),
                          on=["unique_id", "ds"])

plot_forecasts(seasonal, ["ARIMA + Fourier", "MSTL"], ["#2563eb", "#0f766e"])

ARIMA with Fourier terms and MSTL forecasts both following the seasonal decline in gym visits

Both improve a lot on the weekly-only models. ARIMA with Fourier terms has an error of 16.8 and MSTL 18.9, against 12.4 for Prophet. Check the intervals too: the Fourier model's 80% interval contains 74% of the actual values, and MSTL's contains 93%, so one is a little narrow and the other wide. A higher Fourier order allows a more detailed yearly shape; choose it by cross-validation.

Backtest Forecasts with Time Series Cross-Validation

One test window can flatter a model. cross_validation() refits at several cutoff dates and forecasts forward from each. Here 12 windows of 28 days cover the last 336 days. Prophet gets the same cutoffs in a loop. This block takes a few minutes to run.

windows = {"h": 28, "step_size": 28, "n_windows": 12}
cv = sf.cross_validation(df=visits, **windows)
cv = cv.merge(
    sf_fourier.cross_validation(df=extended, **windows).drop(columns="y"),
    on=["unique_id", "ds", "cutoff"])
cv = cv.merge(
    mstl.cross_validation(df=visits, **windows).drop(columns="y"),
    on=["unique_id", "ds", "cutoff"])

folds = []
for cutoff in cv.cutoff.unique():
    model = Prophet(seasonality_mode="multiplicative")
    model.fit(visits.loc[visits.ds <= cutoff, ["ds", "y"]])
    p = model.predict(model.make_future_dataframe(28, include_history=False))
    folds.append(p[["ds", "yhat"]].assign(cutoff=cutoff))
cv = cv.merge(pd.concat(folds).rename(columns={"yhat": "Prophet"}),
              on=["ds", "cutoff"])

models = ["SeasonalNaive", "AutoETS", "AutoARIMA", "MSTL",
          "ARIMA + Fourier", "Prophet"]
errors = cv[models].sub(cv.y, axis=0).abs()
overall = errors.mean().sort_values(ascending=False)
by_window = errors.groupby(cv.cutoff).mean()
print(overall.round(1))

colors = {"SeasonalNaive": "#9ca3af", "AutoETS": "#7c3aed",
          "AutoARIMA": "#93c5fd", "MSTL": "#0f766e",
          "ARIMA + Fourier": "#2563eb", "Prophet": "#ea580c"}
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5), layout="constrained",
                               width_ratios=[2, 3])
bars = ax1.barh(overall.index, overall, color=[colors[m] for m in overall.index])
ax1.bar_label(bars, fmt="%.1f", padding=3)
ax1.set(title="Average over 12 windows", xlabel="Mean absolute error",
        xlim=(0, overall.max() * 1.15))
for name in ["SeasonalNaive", "AutoARIMA", "ARIMA + Fourier", "Prophet"]:
    ax2.plot(by_window.index, by_window[name], "o-", color=colors[name],
             label=name)
ax2.set(title="Error in each window", xlabel="Forecast made on")
ax2.set_ylim(0, by_window.to_numpy().max() * 1.1)
ax2.tick_params(axis="x", rotation=30)
ax2.legend(fontsize=8)
plt.show()

Bar chart of average forecast error by model, with Prophet and ARIMA with Fourier terms lowest, next to a line chart showing error varying widely between windows

Across a year of 28-day forecasts, Prophet (15.0) and ARIMA with Fourier terms (15.5) are nearly tied, far closer than in the single test above. Prophet has the lowest error in 5 windows and the Fourier model in 4, and even the seasonal naive baseline wins one. The error for the same model can double from one window to the next, so a single test period says little about a gap of a few visits.

For classifiers and regressors on ordered data, see TimeSeriesSplit in train/test splits and cross-validation.

Plot Prophet's Trend and Seasonality

Prophet builds a forecast from separate parts, and plot_components() draws each one. That's useful for explaining a forecast or spotting something wrong.

fig = prophet.plot_components(prophet.predict(train[["ds"]]), figsize=(9, 8))
plt.show()

Prophet component plots showing a rising trend, a weekend peak and a yearly cycle that is high in January and low in July

The trend rises, Saturdays and Sundays are the busiest days, and the yearly cycle is high in winter and low in summer. In multiplicative mode, the seasonal values are fractions of the trend: 0.3 means 30% above it. Use the default seasonality_mode="additive" when seasonal swings stay the same size as the series grows. For public holidays, call prophet.add_country_holidays(country_name="US") before fit().

ARIMA with statsmodels

Use ARIMA from statsmodels when you want to choose the order yourself and read coefficients and diagnostics. order is (p, d, q), the autoregressive terms, differences, and moving average terms. exog takes the same Fourier columns.

from statsmodels.tsa.arima.model import ARIMA

indexed = extended.set_index("ds").asfreq("D")
inputs = [c for c in indexed if c.startswith(("sin", "cos"))]
fit = ARIMA(indexed.y[:-horizon], exog=indexed[inputs][:-horizon],
            order=(1, 0, 1), seasonal_order=(0, 1, 1, 7)).fit()
result = fit.get_forecast(horizon, exog=indexed[inputs][-horizon:])
print(fit.summary().tables[1])
print("MAE:", round(mae(result.predicted_mean), 1))
interval = result.conf_int(alpha=0.2)  # 80% interval

The summary shows that sin1 and cos1 carry the yearly cycle, while the second and third pairs aren't distinguishable from zero. This model's error on the 90 test days is 14.4, and 80% of them fall inside its interval. It differs from the AutoARIMA result because the order differs. Don't pick an order by trying many on the test set; use the summary's AIC or cross-validation on the training data. Check the leftover errors with fit.plot_diagnostics().

Which Forecasting Library Should You Use?

Use When
Seasonal naive (repeat last week) Always, as the baseline to beat
Prophet Daily data with several seasonal cycles and holidays, and you want readable components
statsforecast Many series, speed, and several classical models compared with one API
statsmodels ARIMA One series where you want to set the order and inspect the fit
Gradient boosting on lag features Outside drivers such as price or weather matter a lot

Practical Tips

  • Forecast from complete, evenly spaced dates. Decide how to fill gaps before fitting.
  • Judge models at the horizon you will use. A model that wins at 7 days can lose at 90.
  • Check how often actual values fall inside your prediction intervals. An 80% interval should contain about 80% of them.
  • Inputs such as weather must be known, or forecast, for future dates too.

Similar Topics