CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-prophet

Automatic forecasting procedure for time series data with strong seasonal effects and multiple seasons of historical data

Pending
Overview
Eval results
Files

core-forecasting.mddocs/

Core Forecasting

The Prophet class provides the main forecasting functionality with comprehensive time series modeling capabilities. It supports multiple growth patterns, automatic seasonality detection, custom seasonalities, external regressors, and holiday effects.

Capabilities

Prophet Class

The main forecasting class that implements Facebook's Prophet algorithm for time series forecasting.

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
    ):
        """
        Prophet forecaster.

        Parameters:
        - growth: str, growth trend type ('linear', 'logistic', 'flat')
        - changepoints: list, dates for potential changepoints
        - n_changepoints: int, number of potential changepoints (default: 25)
        - changepoint_range: float, proportion of history for changepoints (default: 0.8)
        - yearly_seasonality: bool/str/int, yearly seasonality setting ('auto', True, False, or Fourier terms)
        - weekly_seasonality: bool/str/int, weekly seasonality setting
        - daily_seasonality: bool/str/int, daily seasonality setting
        - holidays: DataFrame, holiday dates and effects
        - seasonality_mode: str, seasonality mode ('additive' or 'multiplicative')
        - seasonality_prior_scale: float, prior scale for seasonality (default: 10.0)
        - holidays_prior_scale: float, prior scale for holidays (default: 10.0)
        - changepoint_prior_scale: float, prior scale for changepoints (default: 0.05)
        - mcmc_samples: int, number of MCMC samples (default: 0 for MAP estimation)
        - interval_width: float, width of uncertainty intervals (default: 0.8)
        - uncertainty_samples: int, number of samples for uncertainty estimation (default: 1000)
        - stan_backend: str, Stan backend to use
        - scaling: str, scaling method ('absmax' or 'minmax')
        - holidays_mode: str, holiday mode (defaults to seasonality_mode)
        """

Model Fitting

Fit the Prophet model to historical time series data.

def fit(self, df, **kwargs):
    """
    Fit the Prophet model.

    Parameters:
    - df: DataFrame with columns 'ds' (date) and 'y' (values)
    - **kwargs: additional arguments passed to Stan

    Returns:
    - self: fitted Prophet object
    """

Prediction

Generate forecasts for future time periods.

def predict(self, df=None, vectorized=True):
    """
    Predict using the Prophet model.

    Parameters:
    - df: DataFrame with column 'ds' (dates), 'cap' for logistic growth,
          and any additional regressors. If None, uses dates from training.
    - vectorized: bool, whether to use vectorized prediction (default: True)

    Returns:
    - DataFrame with forecast components: yhat, yhat_lower, yhat_upper, trend, etc.
    """

Future Dataframe Creation

Create a dataframe with future dates for forecasting.

def make_future_dataframe(self, periods, freq='D', include_history=True):
    """
    Create a dataframe with future dates for forecasting.

    Parameters:
    - periods: int, number of future periods to forecast
    - freq: str, frequency of dates ('D' for daily, 'W' for weekly, etc.)
    - include_history: bool, whether to include historical dates (default: True)

    Returns:
    - DataFrame with 'ds' column containing historical and future dates
    """

Built-in Plotting Methods

Prophet instance methods for quick plotting and visualization.

def plot(self, fcst, ax=None, uncertainty=True, plot_cap=True,
         xlabel='ds', ylabel='y', figsize=(10, 6), include_legend=False):
    """
    Plot the Prophet forecast (instance method).

    Parameters:
    - fcst: DataFrame, forecast output from self.predict()
    - ax: matplotlib axes, axes to plot on (optional)
    - uncertainty: bool, whether to plot uncertainty intervals (default: True)
    - plot_cap: bool, whether to plot carrying capacity (default: True)
    - xlabel: str, label for X-axis (default: 'ds')
    - ylabel: str, label for Y-axis (default: 'y')
    - figsize: tuple, figure size in inches (default: (10, 6))
    - include_legend: bool, whether to add legend (default: False)

    Returns:
    - matplotlib Figure object
    """

def plot_components(self, fcst, uncertainty=True, plot_cap=True,
                    weekly_start=0, yearly_start=0, figsize=None):
    """
    Plot the Prophet forecast components (instance method).

    Parameters:
    - fcst: DataFrame, forecast output from self.predict()
    - uncertainty: bool, whether to plot uncertainty intervals (default: True)
    - plot_cap: bool, whether to plot carrying capacity (default: True)
    - weekly_start: int, start day of weekly plot (0=Sunday, default: 0)
    - yearly_start: int, start day of yearly plot (0=Jan 1, default: 0)
    - figsize: tuple, figure size in inches (optional)

    Returns:
    - matplotlib Figure object with component subplots
    """

Seasonality Management

Add custom seasonality patterns to the model.

def add_seasonality(
    self, 
    name, 
    period, 
    fourier_order, 
    prior_scale=None, 
    mode=None, 
    condition_name=None
):
    """
    Add a custom seasonality component.

    Parameters:
    - name: str, name of the seasonality component
    - period: float, period of the seasonality in the same units as the data
    - fourier_order: int, number of Fourier terms to generate
    - prior_scale: float, prior scale for this seasonality (default: uses global seasonality_prior_scale)
    - mode: str, seasonality mode ('additive' or 'multiplicative', default: uses global seasonality_mode)  
    - condition_name: str, column name for conditional seasonality

    Returns:
    - self: Prophet object with added seasonality
    """

Regressor Management

Add external regressor variables to the model.

def add_regressor(
    self, 
    name, 
    prior_scale=None, 
    standardize='auto', 
    mode=None
):
    """
    Add an external regressor variable.

    Parameters:
    - name: str, name of the regressor column
    - prior_scale: float, prior scale for the regressor coefficient
    - standardize: str/bool, whether to standardize the regressor ('auto', True, False)
    - mode: str, regressor mode ('additive' or 'multiplicative')

    Returns:
    - self: Prophet object with added regressor
    """

Holiday Integration

Add built-in country holidays to the model.

def add_country_holidays(self, country_name):
    """
    Add built-in holidays for a specific country.

    Parameters:
    - country_name: str, country name (e.g., 'US', 'UK', 'Germany')

    Returns:
    - self: Prophet object with added country holidays
    """

Prediction Sampling

Generate samples from the posterior predictive distribution.

def predictive_samples(self, df, vectorized=True):
    """
    Generate samples from the posterior predictive distribution.

    Parameters:
    - df: DataFrame with column 'ds' and any regressors
    - vectorized: bool, whether to use vectorized sampling (default: True)

    Returns:
    - DataFrame with samples from posterior predictive distribution
    """

Static Methods

Seasonality Features

Generate Fourier series components for seasonality modeling.

@staticmethod
def fourier_series(dates, period, series_order):
    """
    Generate Fourier series components.

    Parameters:
    - dates: Series of dates
    - period: float, period of the seasonality
    - series_order: int, number of Fourier terms

    Returns:
    - DataFrame with Fourier series components
    """

@staticmethod  
def make_seasonality_features(dates, period, series_order, prefix):
    """
    Create seasonality features DataFrame.

    Parameters:
    - dates: Series of dates
    - period: float, period of the seasonality  
    - series_order: int, number of Fourier terms
    - prefix: str, prefix for column names

    Returns:
    - DataFrame with seasonality features
    """

Trend Functions

Evaluate trend functions for different growth patterns.

@staticmethod
def piecewise_linear(t, deltas, k, m, changepoint_ts):
    """
    Evaluate piecewise linear trend function.

    Parameters:
    - t: array, time values
    - deltas: array, rate changes at changepoints
    - k: float, base growth rate
    - m: float, offset
    - changepoint_ts: array, changepoint times

    Returns:
    - array, trend values
    """

@staticmethod
def piecewise_logistic(t, cap, deltas, k, m, changepoint_ts):
    """
    Evaluate piecewise logistic trend function.

    Parameters:
    - t: array, time values
    - cap: array, carrying capacity values
    - deltas: array, rate changes at changepoints
    - k: float, base growth rate
    - m: float, offset
    - changepoint_ts: array, changepoint times

    Returns:
    - array, trend values
    """

@staticmethod
def flat_trend(t, m):
    """
    Evaluate flat trend function.

    Parameters:
    - t: array, time values
    - m: float, offset value

    Returns:
    - array, constant trend values
    """

Growth Initialization

Initialize parameters for different growth patterns.

@staticmethod
def linear_growth_init(df):
    """
    Initialize linear growth parameters.

    Parameters:
    - df: DataFrame with 'ds' and 'y' columns

    Returns:
    - tuple, (growth rate, offset)
    """

@staticmethod
def logistic_growth_init(df):
    """
    Initialize logistic growth parameters.

    Parameters:
    - df: DataFrame with 'ds', 'y', and 'cap' columns

    Returns:
    - tuple, (growth rate, offset)
    """

@staticmethod
def flat_growth_init(df):
    """
    Initialize flat growth parameters.

    Parameters:
    - df: DataFrame with 'ds' and 'y' columns

    Returns:
    - tuple, (growth rate, offset)
    """

Usage Examples

Basic Time Series Forecasting

import pandas as pd
import numpy as np
from prophet import Prophet

# Create sample data
df = pd.DataFrame({
    'ds': pd.date_range('2020-01-01', periods=365, freq='D'),
    'y': np.random.randn(365).cumsum() + 100
})

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

# Create future dates and predict
future = model.make_future_dataframe(periods=30)
forecast = model.predict(future)

print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())

Logistic Growth with Capacity

import numpy as np

# Data with capacity constraint
df = pd.DataFrame({
    'ds': pd.date_range('2020-01-01', periods=365, freq='D'),
    'y': np.random.randn(365).cumsum() + 100,
    'cap': [200] * 365  # Carrying capacity
})

# Model with logistic growth
model = Prophet(growth='logistic')
model.fit(df)

# Future dataframe must include capacity
future = model.make_future_dataframe(periods=30)
future['cap'] = 200

forecast = model.predict(future)

Custom Seasonality and Regressors

import numpy as np

# Add custom seasonality and external regressor
model = Prophet()
model.add_seasonality(name='monthly', period=30.5, fourier_order=5)
model.add_regressor('temperature')

# Training data with regressor
df = pd.DataFrame({
    'ds': pd.date_range('2020-01-01', periods=365, freq='D'),
    'y': np.random.randn(365).cumsum() + 100,
    'temperature': np.random.normal(20, 5, 365)
})

model.fit(df)

# Future data must include regressor
future = model.make_future_dataframe(periods=30)
future['temperature'] = np.random.normal(20, 5, len(future))

forecast = model.predict(future)

Install with Tessl CLI

npx tessl i tessl/pypi-prophet

docs

core-forecasting.md

diagnostics.md

holidays.md

index.md

plotting.md

serialization.md

utilities.md

tile.json