Prophet Tutorial: Time Series Forecasting with Python
Time series forecasting is one of the most common needs in data science and business. From predicting sales, website traffic, to stock prices — the ability to forecast time-based data is invaluable. Prophet, an open-source library from Meta (Facebook), provides a powerful yet user-friendly solution for time series forecasting. In this tutorial, we'll learn Prophet from basics to advanced features, complete with runnable code examples.
What Is Prophet?
Prophet is a forecasting library designed by Meta's Data Science team to handle business time series data. Prophet uses a decomposable additive model consisting of three main components:
- Trend: Long-term changes (growth or decline)
- Seasonality: Recurring patterns (daily, weekly, yearly)
- Holiday effects: Impact from holidays or special events
Key advantages of Prophet over traditional methods (ARIMA, Exponential Smoothing):
Installation
Using pip
pip install prophet
Using conda
conda install -c conda-forge prophet
Core Dependencies
Prophet requires several dependencies:
pip install prophet plotly matplotlib pandas numpy
Verify installation:
import prophet
print(f"Prophet version: {prophet.version}")
Installation Notes
Prophet uses Stan (a probabilistic programming language) under the hood. On some systems, installing Stan may require a C++ compiler. If you encounter installation errors:
# Ubuntu/Debian
sudo apt-get install build-essential
macOS
xcode-select --install
Then reinstall
pip install prophet
Basic Usage: Your First Forecast
Preparing Data
Prophet requires a DataFrame with two columns: ds (datetime) and y (value to predict).
import pandas as pd
from prophet import Prophet
import matplotlib.pyplot as plt
import numpy as np
Create sample daily sales data
dates = pd.daterange(start='2023-01-01', end='2025-12-31', freq='D')
np.random.seed(42)
trend = np.linspace(100, 250, len(dates))
weekly = 20 np.sin(2 np.pi np.arange(len(dates)) / 7)
yearly = 40 np.sin(2 np.pi np.arange(len(dates)) / 365.25)
noise = np.random.normal(0, 10, len(dates))
sales = trend + weekly + yearly + noise
df = pd.DataFrame({
'ds': dates,
'y': sales
})
print(df.head())
print(f"\nShape: {df.shape}")
print(f"Date range: {df['ds'].min()} to {df['ds'].max()}")
Output:
ds y
0 2023-01-01 108.234567
1 2023-01-02 126.789012
2 2023-01-03 131.456789
3 2023-01-04 119.876543
4 2023-01-05 105.123456
Shape: (1096, 2)
Date range: 2023-01-01 to 2025-12-31
Building and Forecasting
# Initialize and fit the model
model = Prophet()
model.fit(df)
Create a dataframe for future predictions (90 days ahead)
future = model.makefuturedataframe(periods=90)
print(f"Future dataframe shape: {future.shape}")
Generate forecast
forecast = model.predict(future)
View forecast results
print(forecast[['ds', 'yhat', 'yhatlower', 'yhatupper']].tail(10))
Visualizing Results
# Plot forecast
fig1 = model.plot(forecast)
plt.title('Sales Forecast with Prophet')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.tightlayout()
plt.savefig('prophetforecast.png', dpi=150)
plt.show()
Plot components (trend, weekly, yearly)
fig2 = model.plotcomponents(forecast)
plt.tightlayout()
plt.savefig('prophetcomponents.png', dpi=150)
plt.show()
Understanding Forecast Output
Key columns in the forecast results:
| Column | Description |
|--------|-------------|
| yhat | Predicted value |
| yhatlower | Lower bound of confidence interval |
| yhatupper | Upper bound of confidence interval |
| trend | Trend component |
| weekly | Weekly seasonality component |
| yearly | Yearly seasonality component |
# Analyze forecast components
print("=== Forecast Summary ===")
futureonly = forecast[forecast['ds'] > df['ds'].max()]
print(f"Average prediction (next 90 days): {futureonly['yhat'].mean():.2f}")
print(f"Min prediction: {futureonly['yhat'].min():.2f}")
print(f"Max prediction: {futureonly['yhat'].max():.2f}")
print(f"Average uncertainty interval width: {(futureonly['yhatupper'] - futureonly['yhatlower']).mean():.2f}")
Using Real Data: Retail Sales Dataset
# Reading data from CSV or API
Example: reading monthly sales data
data = pd.readcsv('monthlysales.csv')
Ensure correct format
data['ds'] = pd.todatetime(data['date'])
data['y'] = data['revenue']
data = data[['ds', 'y']]
Or create realistic retail simulation data
dates = pd.daterange(start='2021-01-01', end='2025-12-31', freq='D')
np.random.seed(123)
base = 1000
trend = np.linspace(0, 500, len(dates))
yearly = 200 np.sin(2 np.pi (np.arange(len(dates)) - 80) / 365.25)
weekly = 100 np.sin(2 np.pi np.arange(len(dates)) / 7)
Holiday season effect (e.g., Q4 retail surge)
holidayeffect = np.zeros(len(dates))
for year in range(2021, 2026):
mask = (dates.month == 11) | (dates.month == 12)
holidayeffect[mask & (dates.year == year)] = 150
noise = np.random.normal(0, 50, len(dates))
sales = base + trend + yearly + weekly + holidayeffect + noise
sales = np.maximum(sales, 0)
dfretail = pd.DataFrame({'ds': dates, 'y': sales})
print(f"Retail data: {dfretail.shape[0]} days")
Configuring Seasonality
Automatic Seasonality Settings
model = Prophet(
yearlyseasonality=True, # Enable yearly seasonality
weeklyseasonality=True, # Enable weekly seasonality
dailyseasonality=False, # Disable daily seasonality (for daily data)
)
model.fit(df)
Adding Custom Seasonality
# Add monthly seasonality
model = Prophet(weeklyseasonality=True, yearlyseasonality=True)
model.addseasonality(
name='monthly',
period=30.5,
fourierorder=5
)
model.fit(df)
forecast = model.predict(future)
Seasonality with Fourier Order
Fourier order determines how "flexible" the model is at capturing seasonal patterns. Higher values capture more detail but are more susceptible to overfitting.
# Comparing fourier orders
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
for i, order in enumerate([3, 10, 20]):
m = Prophet(yearlyseasonality=order)
m.fit(df)
future = m.makefuturedataframe(periods=90)
forecast = m.predict(future)
m.plot(forecast, ax=axes[i])
axes[i].settitle(f'Fourier Order = {order}')
plt.tightlayout()
plt.savefig('fouriercomparison.png', dpi=150)
plt.show()
Multiplicative Seasonality
By default, Prophet uses additive seasonality. For data where seasonal amplitude changes with the trend (e.g., percentages rather than absolute values), use multiplicative:
model = Prophet(seasonalitymode='multiplicative')
model.fit(df)
future = model.make
futuredataframe(periods=90)
forecast = model.predict(future)
Holiday Effects
Adding Custom Holidays
# Define custom holidays
newyear = pd.DataFrame({
'holiday': 'newyear',
'ds': pd.todatetime(['2023-01-01', '2024-01-01', '2025-01-01', '2026-01-01']),
'lowerwindow': -1,
'upperwindow': 1,
})
blackfriday = pd.DataFrame({
'holiday': 'blackfriday',
'ds': pd.todatetime(['2023-11-24', '2024-11-29', '2025-11-28']),
'lowerwindow': -1,
'upperwindow': 3,
})
christmas = pd.DataFrame({
'holiday': 'christmas',
'ds': pd.todatetime(['2023-12-25', '2024-12-25', '2025-12-25']),
'lowerwindow': -7,
'upperwindow': 1,
})
independenceday = pd.DataFrame({
'holiday': 'independenceday',
'ds': pd.todatetime(['2023-07-04', '2024-07-04', '2025-07-04', '2026-07-04']),
'lowerwindow': -1,
'upperwindow': 1,
})
Combine all holidays
holidays = pd.concat([newyear, blackfriday, christmas, independenceday])
Create model with holidays
model = Prophet(holidays=holidays)
model.fit(df)
future = model.makefuturedataframe(periods=180)
forecast = model.predict(future)
View holiday effects
fig = model.plotcomponents(forecast)
plt.show()
Using Built-in Country Holidays
Prophet provides built-in holidays for many countries:
model = Prophet()
model.addcountryholidays(countryname='US') # United States
model.fit(df)
View added holidays
print(model.trainholidaynames)
Advanced Usage
Adding Extra Regressors
Regressors are additional variables that influence the forecast, such as weather, promotions, or special events.
# Example: adding promotion data as a regressor
dfwithpromo = df.copy()
dfwithpromo['ispromo'] = 0
Mark promotion days
promodates = pd.daterange('2023-06-15', '2023-06-30')
promodates = promodates.append(pd.daterange('2023-11-25', '2023-12-05'))
promodates = promodates.append(pd.daterange('2024-06-15', '2024-06-30'))
promodates = promodates.append(pd.daterange('2024-11-25', '2024-12-05'))
dfwithpromo.loc[dfwithpromo['ds'].isin(promodates), 'ispromo'] = 1
Add temperature as a regressor
np.random.seed(42)
dfwithpromo['temperature'] = 68 + 15 np.sin(
2 np.pi np.arange(len(dfwithpromo)) / 365.25
) + np.random.normal(0, 3, len(dfwithpromo))
Build model with regressors
model = Prophet()
model.addregressor('ispromo')
model.addregressor('temperature')
model.fit(dfwithpromo)
For forecasting, we need to provide regressor values for the future
future = model.makefuturedataframe(periods=90)
future['ispromo'] = 0 # Assume no promotions in forecast period
future['temperature'] = 68 + 15 np.sin(
2 np.pi np.arange(len(future)) / 365.25
)
forecast = model.predict(future)
Trend Changepoints
Prophet automatically detects trend changepoints. You can configure this behavior:
# Configure changepoint number and flexibility
model = Prophet(
changepointpriorscale=0.05, # Trend flexibility (default: 0.05)
nchangepoints=25, # Number of potential changepoints
changepointrange=0.8, # Proportion of data for changepoint placement
)
model.fit(df)
future = model.makefuturedataframe(periods=90)
forecast = model.predict(future)
Visualize changepoints
fig = model.plot(forecast)
from prophet.plot import addchangepointstoplot
addchangepointstoplot(fig.gca(), model, forecast)
plt.title('Forecast with Changepoints')
plt.savefig('changepoints.png', dpi=150)
plt.show()
View changepoint locations
print("Changepoint dates:")
for cp in model.changepoints:
print(f" {cp.date()}")
Adjusting Changepoint Sensitivity
# More flexible trend (more changes allowed)
modelflex = Prophet(changepointpriorscale=0.5)
modelflex.fit(df)
Smoother trend (fewer changes)
modelsmooth = Prophet(changepointpriorscale=0.001)
modelsmooth.fit(df)
Compare
fig, axes = plt.subplots(1, 2, figsize=(16, 5))
forecastflex = modelflex.predict(modelflex.makefuturedataframe(periods=90))
modelflex.plot(forecastflex, ax=axes[0])
axes[0].settitle('Flexible Trend (scale=0.5)')
forecastsmooth = modelsmooth.predict(modelsmooth.makefuturedataframe(periods=90))
modelsmooth.plot(forecastsmooth, ax=axes[1])
axes[1].settitle('Smooth Trend (scale=0.001)')
plt.tightlayout()
plt.show()
Logistic Growth (Saturating Forecast)
For data with an upper bound (capacity), use logistic growth:
# Example: user growth approaching saturation
dfgrowth = df.copy()
dfgrowth['cap'] = 300 # Upper bound
dfgrowth['floor'] = 0 # Lower bound
model = Prophet(growth='logistic')
model.fit(dfgrowth)
future = model.makefuturedataframe(periods=365)
future['cap'] = 300
future['floor'] = 0
forecast = model.predict(future)
fig = model.plot(forecast)
plt.title('Logistic Growth Forecast')
plt.show()
Flat Trend
For data without a trend, use flat growth:
model = Prophet(growth='flat')
model.fit(df)
Cross-Validation and Model Evaluation
Cross-Validation with Prophet
Prophet provides a built-in cross-validation function using a rolling window approach:
from prophet.diagnostics import crossvalidation, performancemetrics
Cross-validation
initial: initial training data
period: spacing between cutoff dates
horizon: how far ahead to forecast for evaluation
df
cv = crossvalidation(
model,
initial='730 days', # 2 years of initial training data
period='90 days', # Evaluate every 90 days
horizon='90 days' # Forecast 90 days ahead
)
print(df
cv.head())
print(f"\nNumber of evaluations: {dfcv['cutoff'].nunique()}")
Computing Metrics
# Calculate performance metrics
dfmetrics = performancemetrics(dfcv)
print(dfmetrics[['horizon', 'mape', 'rmse', 'mae']].head(10))
Average metrics
print("\n=== Average Metrics ===")
print(f"MAPE: {dfmetrics['mape'].mean():.4f} ({dfmetrics['mape'].mean()100:.2f}%)")
print(f"RMSE: {dfmetrics['rmse'].mean():.2f}")
print(f"MAE: {dfmetrics['mae'].mean():.2f}")
Visualizing Cross-Validation
from prophet.plot import plotcrossvalidationmetric
Plot MAPE over forecast horizon
fig = plotcrossvalidationmetric(dfcv, metric='mape')
plt.title('MAPE vs Forecast Horizon')
plt.savefig('cvmape.png', dpi=150)
plt.show()
Plot RMSE
fig = plotcrossvalidationmetric(dfcv, metric='rmse')
plt.title('RMSE vs Forecast Horizon')
plt.show()
Hyperparameter Tuning
import itertools
Define parameter grid
paramgrid = {
'changepointpriorscale': [0.001, 0.01, 0.1, 0.5],
'seasonalitypriorscale': [0.01, 0.1, 1.0, 10.0],
'seasonalitymode': ['additive', 'multiplicative'],
}
Generate all combinations
allparams = [dict(zip(paramgrid.keys(), v))
for v in itertools.product(paramgrid.values())]
rmses = []
for params in allparams:
m = Prophet(*params)
m.fit(df)
dfcv = crossvalidation(m, initial='730 days', period='90 days', horizon='90 days')
dfp = performancemetrics(dfcv)
rmses.append(dfp['rmse'].mean())
Find best parameters
bestparams = allparams[np.argmin(rmses)]
print(f"Best RMSE: {min(rmses):.2f}")
print(f"Best params: {bestparams}")
Real-World Example: Website Traffic Forecasting
# Simulate website traffic data
dates = pd.daterange(start='2022-01-01', end='2025-12-31', freq='H')
np.random.seed(42)
Base traffic
base = 5000
Upward trend
trend = np.linspace(0, 3000, len(dates))
Yearly seasonality (holiday season is busier)
yearly = 1000 np.sin(2 np.pi (np.arange(len(dates)) / (365.25 24)))
Weekly seasonality (weekdays are busier)
dayofweek = dates.dayofweek
weekly = np.where(dayofweek < 5, 500, -500)
Daily seasonality (peak at 10am-2pm)
hour = dates.hour
daily = 800 np.sin(2 np.pi (hour - 6) / 24)
noise = np.random.normal(0, 300, len(dates))
traffic = base + trend + yearly + weekly + daily + noise
traffic = np.maximum(traffic, 0)
Aggregate to daily for modeling
dftraffic = pd.DataFrame({'ds': dates, 'y': traffic})
dfdaily = dftraffic.resample('D', on='ds').sum().resetindex()
print(f"Data points: {len(dfdaily)}")
Build model with optimal configuration
model = Prophet(
yearlyseasonality=True,
weeklyseasonality=True,
dailyseasonality=False,
changepointpriorscale=0.05,
seasonalitypriorscale=10,
)
model.addcountryholidays(countryname='US')
model.fit(dfdaily)
Forecast 6 months ahead
future = model.makefuturedataframe(periods=180)
forecast = model.predict(future)
Visualization
fig, axes = plt.subplots(2, 1, figsize=(14, 10))
model.plot(forecast, ax=axes[0])
axes[0].settitle('Website Traffic Forecast')
axes[0].setylabel('Daily Visitors')
Zoom into forecast period
forecastonly = forecast[forecast['ds'] > dfdaily['ds'].max()]
axes[1].fillbetween(
forecastonly['ds'],
forecastonly['yhatlower'],
forecastonly['yhatupper'],
alpha=0.3, color='blue', label='Uncertainty Interval'
)
axes[1].plot(forecastonly['ds'], forecastonly['yhat'],
color='blue', label='Forecast')
axes[1].settitle('Forecast Detail (Next 6 Months)')
axes[1].setylabel('Daily Visitors')
axes[1].legend()
plt.tightlayout()
plt.savefig('trafficforecast.png', dpi=150)
plt.show()
Saving and Loading Models
import json
from prophet.serialize import modeltojson, modelfromjson
Save model
with open('prophetmodel.json', 'w') as f:
f.write(modeltojson(model))
print("Model saved to prophetmodel.json")
Load model
with open('prophetmodel.json', 'r') as f:
loadedmodel = modelfromjson(f.read())
Use loaded model
future = loadedmodel.makefuturedataframe(periods=30)
forecast = loadedmodel.predict(future)
print(f"Loaded model forecast shape: {forecast.shape}")
Best Practices
1. Data Preparation
# Always inspect data before modeling
def preparedata(df, datecol, valuecol):
"""Prepare data for Prophet."""
result = df[[datecol, valuecol]].copy()
result.columns = ['ds', 'y']
result['ds'] = pd.todatetime(result['ds'])
result = result.sortvalues('ds').resetindex(drop=True)
# Check for missing dates
fullrange = pd.daterange(result['ds'].min(), result['ds'].max(), freq='D')
missing = set(fullrange) - set(result['ds'])
if missing:
print(f"Warning: {len(missing)} missing dates detected")
# Check for outliers (IQR method)
Q1 = result['y'].quantile(0.25)
Q3 = result['y'].quantile(0.75)
IQR = Q3 - Q1
outliers = result[(result['y'] < Q1 - 3IQR) | (result['y'] > Q3 + 3IQR)]
if len(outliers) > 0:
print(f"Warning: {len(outliers)} potential outliers detected")
return result
2. Evaluate Before Deployment
# Always cross-validate before using the model in production
def evaluatemodel(model, df, initialdays=730, perioddays=90, horizondays=90):
"""Evaluate model with cross-validation."""
dfcv = crossvalidation(
model,
initial=f'{initialdays} days',
period=f'{perioddays} days',
horizon=f'{horizondays} days'
)
metrics = performancemetrics(dfcv)
print("=== Model Evaluation ===")
print(f"MAPE: {metrics['mape'].mean()100:.2f}%")
print(f"RMSE: {metrics['rmse'].mean():.2f}")
print(f"MAE: {metrics['mae'].mean():.2f}")
print(f"Coverage: {metrics['coverage'].mean()100:.1f}%")
return metrics
3. Monitoring Forecast Quality
# Compare forecast with actuals regularly
def monitorforecast(forecastdf, actualdf):
"""Monitor forecast quality vs actual."""
merged = forecastdf.merge(actualdf, on='ds', suffixes=('pred', 'actual'))
merged['error'] = merged['y'] - merged['yhat']
merged['abserror'] = merged['error'].abs()
merged['pcterror'] = (merged['abserror'] / merged['y']) 100
# Check if actual falls within uncertainty interval
merged['ininterval'] = (
(merged['y'] >= merged['yhatlower']) &
(merged['y'] <= merged['yhatupper'])
)
print(f"MAE: {merged['abserror'].mean():.2f}")
print(f"MAPE: {merged['pcterror'].mean():.2f}%")
print(f"Coverage: {merged['ininterval'].mean()100:.1f}%")
return merged
4. General Tips
- At least 2 seasonal cycles — To detect yearly seasonality, ideally you need at least 2 years of data
- Don't use daily seasonality for daily data — it's only relevant for sub-daily (hourly) data
- Watch changepointpriorscale — too high causes overfitting, too low causes underfitting
- Use multiplicative seasonality if seasonal amplitude correlates with the trend
- Always cross-validate — don't rely solely on training data fit
- Retrain periodically — new data may contain new patterns
- Consider regressors — external variables can significantly improve accuracy
Integration with ML Pipelines
# Example: integrating Prophet with MLflow for experiment tracking
import mlflow
def trainandlogprophet(df, params, experimentname="prophetforecasting"):
mlflow.setexperiment(experimentname)
with mlflow.startrun():
# Log parameters
mlflow.logparams(params)
# Train model
model = Prophet(*params)
model.fit(df)
# Cross-validate
dfcv = crossvalidation(
model, initial='730 days', period='90 days', horizon='90 days'
)
metrics = performancemetrics(dfcv)
# Log metrics
mlflow.logmetric("mape", metrics['mape'].mean())
mlflow.logmetric("rmse", metrics['rmse'].mean())
mlflow.logmetric("mae", metrics['mae'].mean())
# Save model
modeljson = modeltojson(model)
with open("prophetmodel.json", "w") as f:
f.write(modeljson)
mlflow.logartifact("prophetmodel.json")
print(f"Run logged with MAPE: {metrics['mape'].mean()100:.2f}%")
return model, metrics
Execute
params = {
'changepointpriorscale': 0.05,
'seasonalitypriorscale': 10,
'seasonalitymode': 'additive',
}
model, metrics = trainandlogprophet(df, params)
Conclusion
Prophet is an excellent tool for forecasting business time series data. With minimal configuration, you can get high-quality forecasts. Key takeaways:
ds and y columnsProphet is ideal for cases where you need fast, interpretable, and robust forecasts. For more complex scenarios (multivariate forecasting, deep learning-based approaches), consider combining Prophet with other libraries like NeuralProphet, Chronos, or TimeGPT.
Full documentation is available at facebook.github.io/prophet. Happy forecasting, and we hope this tutorial helps with your time series projects!