Automatic forecasting procedure for time series data with strong seasonal effects and multiple seasons of historical data
npx @tessl/cli install tessl/pypi-prophet@1.1.0Prophet is a comprehensive time series forecasting library that implements an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. Developed by Facebook's Core Data Science team, it excels at forecasting time series with strong seasonal effects and multiple seasons of historical data, providing robust handling of missing data, trend shifts, and outliers.
pip install prophetfrom prophet import ProphetFor plotting functionality:
from prophet.plot import plot, plot_componentsFor diagnostics and cross-validation:
from prophet.diagnostics import cross_validation, performance_metricsimport pandas as pd
import numpy as np
from prophet import Prophet
# Prepare your data with 'ds' (datestamp) and 'y' (value) columns
df = pd.DataFrame({
'ds': pd.date_range('2020-01-01', periods=365, freq='D'),
'y': np.random.randn(365).cumsum() + 100
})
# Create and fit the model
model = Prophet()
model.fit(df)
# Make future dataframe for predictions
future = model.make_future_dataframe(periods=30) # 30 days into future
# Generate forecast
forecast = model.predict(future)
# Plot results
fig = model.plot(forecast)
fig_components = model.plot_components(forecast)Prophet uses a decomposable time series model with three main components:
The model equation: y(t) = g(t) + s(t) + h(t) + ε(t)
Prophet uses a Bayesian approach with Stan for parameter estimation, providing uncertainty intervals and allowing for incorporation of prior knowledge through hyperparameters.
The main Prophet class providing time series forecasting with trend, seasonality, and holiday modeling. Supports linear, logistic, and flat growth trends with automatic changepoint detection.
class Prophet:
def __init__(
self,
growth='linear',
changepoints=None,
n_changepoints=25,
changepoint_range=0.8,
yearly_seasonality='auto',
weekly_seasonality='auto',
daily_seasonality='auto',
holidays=None,
seasonality_mode='additive',
seasonality_prior_scale=10.0,
holidays_prior_scale=10.0,
changepoint_prior_scale=0.05,
mcmc_samples=0,
interval_width=0.8,
uncertainty_samples=1000,
stan_backend=None,
scaling='absmax',
holidays_mode=None
): ...
def fit(self, df, **kwargs): ...
def predict(self, df=None, vectorized=True): ...
def make_future_dataframe(self, periods, freq='D', include_history=True): ...Comprehensive plotting functionality supporting both matplotlib and Plotly backends for forecast visualization, component decomposition, and seasonality analysis.
def plot(m, fcst, ax=None, uncertainty=True, plot_cap=True, **kwargs): ...
def plot_components(m, fcst, uncertainty=True, plot_cap=True, **kwargs): ...
def plot_plotly(m, fcst, **kwargs): ...
def plot_components_plotly(m, fcst, **kwargs): ...Time series cross-validation and performance evaluation tools for model validation, including multiple performance metrics and rolling window analysis.
def cross_validation(
model,
horizon,
period=None,
initial=None,
parallel=None,
cutoffs=None,
disable_tqdm=False,
extra_output_columns=None
): ...
def performance_metrics(df, metrics=None, rolling_window=0.1, monthly=False): ...Model persistence functionality for saving and loading trained Prophet models using JSON serialization.
def model_to_json(model): ...
def model_from_json(model_json): ...
def model_to_dict(model): ...
def model_from_dict(model_dict): ...Helper functions for analyzing regressor coefficients, extracting model parameters, and supporting advanced model introspection.
def regressor_coefficients(m): ...
def regressor_index(m, name): ...
def warm_start_params(m): ...Built-in holiday calendars for multiple countries and functionality for creating custom holiday definitions with flexible windows and effects.
def get_holiday_names(country): ...
def make_holidays_df(year_list, country, province=None, state=None): ...# Core data structures
class ModelInputData:
"""Input data structure for Stan model"""
class ModelParams:
"""Model parameters structure"""
# Enums
class TrendIndicator:
LINEAR = 0
LOGISTIC = 1
FLAT = 2
# Expected DataFrame formats
# Training data: DataFrame with 'ds' (datetime) and 'y' (numeric) columns
# Future data: DataFrame with 'ds' column, 'cap' for logistic growth, regressor columns
# Holidays: DataFrame with 'ds' and 'holiday' columns, optional 'lower_window', 'upper_window', 'prior_scale'