Thursday, December 4, 2025

thumbnail

Building a Time Series Forecasting Model with Prophet

 Building a Time Series Forecasting Model with Prophet

1️⃣ Introduction to Prophet


Prophet models a time series as:


๐‘ฆ

(

๐‘ก

)

=

๐‘”

(

๐‘ก

)

+

๐‘ 

(

๐‘ก

)

+

โ„Ž

(

๐‘ก

)

+

๐œ–

๐‘ก

y(t)=g(t)+s(t)+h(t)+ฯต

t



Where:


๐‘”

(

๐‘ก

)

g(t) → trend (linear or logistic growth)


๐‘ 

(

๐‘ก

)

s(t) → seasonality (yearly, weekly, daily)


โ„Ž

(

๐‘ก

)

h(t) → effects of holidays/events


๐œ–

๐‘ก

ฯต

t


 → error term


Prophet automatically detects changepoints in trends and supports missing data and outliers.


2️⃣ Install Prophet

# For Python

pip install prophet


# Import libraries

import pandas as pd

from prophet import Prophet

import matplotlib.pyplot as plt


3️⃣ Prepare the Data


Prophet expects a dataframe with columns:


Column Description

ds datestamp (datetime type)

y value to forecast (numeric)

Example:

# Load your CSV data

df = pd.read_csv('sales_data.csv')


# Ensure columns are in Prophet format

df['ds'] = pd.to_datetime(df['date'])

df['y'] = df['sales']


df = df[['ds', 'y']]


4️⃣ Create and Fit the Model

# Initialize Prophet

model = Prophet(

    yearly_seasonality=True,

    weekly_seasonality=True,

    daily_seasonality=False

)


# Add custom holidays (optional)

holidays = pd.DataFrame({

    'holiday': 'new_year',

    'ds': pd.to_datetime(['2025-01-01']),

    'lower_window': 0,

    'upper_window': 1,

})

model = Prophet(holidays=holidays)


# Fit model

model.fit(df)


5️⃣ Make Future Predictions


Create a dataframe for future dates:


# Forecast 90 days into the future

future = model.make_future_dataframe(periods=90)


# Predict

forecast = model.predict(future)


forecast DataFrame contains:


yhat → predicted value


yhat_lower, yhat_upper → uncertainty intervals


Seasonal components: trend, weekly, yearly


6️⃣ Visualize Forecast

# Plot forecast

fig1 = model.plot(forecast)

plt.show()


# Plot components (trend, weekly/yearly seasonality, holidays)

fig2 = model.plot_components(forecast)

plt.show()



plot_components shows seasonal patterns, trend, and holiday effects.


7️⃣ Hyperparameter Tuning


Prophet allows tuning of:


changepoint_prior_scale → flexibility in trend changes (default 0.05)


seasonality_prior_scale → strength of seasonality (default 10)


holidays_prior_scale → strength of holiday effects


Example:


model = Prophet(

    yearly_seasonality=True,

    weekly_seasonality=True,

    changepoint_prior_scale=0.1,

    seasonality_prior_scale=15

)


8️⃣ Evaluate Forecast Accuracy


Split your dataset into train/test sets:


train = df[:-30]

test = df[-30:]


model.fit(train)

future = model.make_future_dataframe(periods=30)

forecast = model.predict(future)


# Compute Mean Absolute Error

from sklearn.metrics import mean_absolute_error

mae = mean_absolute_error(test['y'], forecast['yhat'][-30:])

print(f'MAE: {mae}')


9️⃣ Add Regressors (Optional)


Prophet supports external regressors to improve forecasts:


# Add a promotion column

df['promotion'] = df['promotion_flag']

model.add_regressor('promotion')


model.fit(df)


10️⃣ Best Practices


Always check for data quality (missing values, outliers)


Use log transformation for highly skewed data


Incorporate holidays and events for business forecasts


Evaluate forecast confidence intervals


Visualize components to understand trend & seasonality


✅ Summary Workflow


Prepare data (ds, y)


Initialize Prophet (seasonality, holidays)


Fit model on historical data


Make future predictions


Visualize forecast and components


Tune hyperparameters and evaluate accuracy


Incorporate regressors if needed


Prophet is particularly effective for business time series like sales, traffic, or product demand due to its ability to handle trend changes and seasonal effects with minimal configuration.

Learn Data Science Course in Hyderabad

Read More

A Guide to Imbalanced Datasets and How to Handle Them

Anomaly Detection: How to Find the Needle in the Haystack

Focus on specific techniques and their applications.

Specialized Machine Learning Concepts

Visit Our Quality Thought Training Institute in Hyderabad

Get Directions 

Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive