How to forecast time series with Prophet in Machine Learning
This tutorial shows how to forecast time series with Prophet in Machine Learning to obtain simple forecasts, interpret seasonality and handle holidays. It is useful for planning inventory, sales or capacity with a robust and easy-to-use method.
Prerequisites
- Python 3.8+ and pip
- Libraries: pandas, prophet, matplotlib (install via pip)
- A dataset with dates and a value (e.g.: vendas_diarias.csv)
Step 1: Install and import libraries
Install Prophet (the package is called prophet) plus pandas and matplotlib. Then import the essentials. If there are installation issues, check the C++ compiler or use a conda distribution.
pip install pandas prophet matplotlib
import pandas as pd
from prophet import Prophet
import matplotlib.pyplot as plt
Step 2: Prepare the data in the format Prophet requires
Prophet expects two columns: ds (dates) and y (value). Load the file, convert the date column and aggregate by day if necessary.
# Minimal example
df = pd.read_csv('vendas_diarias.csv')
df['ds'] = pd.to_datetime(df['data'])
df = df[['ds', 'vendas']].rename(columns={'vendas':'y'})
# Optional: sort and fill missing days
df = df.sort_values('ds').reset_index(drop=True)
Step 3: Explore the series and handle extreme values
Visualize the series to understand trends, seasonality and outliers. Decide whether to impute nulls or winsorize outliers before training.
df.plot(x='ds', y='y', figsize=(10,4))
plt.title('Time series of sales')
plt.show()
# Simple imputation example
df['y'] = df['y'].fillna(method='ffill')
Step 4: Create and tune the Prophet model
Create a basic Prophet model. You can configure yearly and weekly seasonality, and add holidays. Adjust changepoint_prior_scale to control sensitivity to abrupt changes (overfitting vs underfitting).
# Basic model with weekly and yearly seasonality
m = Prophet(yearly_seasonality=True, weekly_seasonality=True, daily_seasonality=False)
# If you have holidays, create a holidays DataFrame and add
# holidays = pd.DataFrame({'ds': [...], 'holiday': [...]})
# m.add_country_holidays(country_name='PT')
# Fit the model
m.fit(df)
Step 5: Generate forecasts and confidence intervals
Create a future DataFrame with the desired period (e.g. 30 days) and predict. Prophet returns forecast with intervals (yhat, yhat_lower, yhat_upper).
future = m.make_future_dataframe(periods=30, freq='D')
forecast = m.predict(future)
# See some useful columns
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())
Step 6: Visualize and interpret results
Visualize the forecast and components to see trend, seasonality and holiday effects. This helps interpret why the forecasts behave as they do.
m.plot(forecast)
plt.title('Forecast with Prophet')
plt.show()
m.plot_components(forecast)
plt.show()
Step 7: Validate the model (simple backtesting)
Perform temporal validation: hold out the last N days as test, train on the remainder and compare forecasts with actuals using metrics like MAE or RMSE.
from sklearn.metrics import mean_absolute_error, mean_squared_error
# Example: validate last 30 days
train = df.iloc[:-30]
test = df.iloc[-30:]
m2 = Prophet(yearly_seasonality=True, weekly_seasonality=True)
m2.fit(train)
future2 = m2.make_future_dataframe(periods=30, freq='D')
forecast2 = m2.predict(future2)
pred = forecast2.set_index('ds').loc[test['ds'], 'yhat']
mae = mean_absolute_error(test['y'], pred)
rmse = mean_squared_error(test['y'], pred, squared=False)
print('MAE:', mae, 'RMSE:', rmse)
Check the outcome
Confirm that the forecast plot includes the yhat line and that the components show seasonality. Validate with MAE/RMSE and check whether errors are within business tolerance. If the yhat_lower/upper intervals cover most real points, the model is calibrated.
Conclusion
You learned how to prepare data, train Prophet, generate forecasts and validate with backtesting. Next steps: experiment with changepoint_prior_scale, add external regressors (promotions, prices) and use Prophet's advanced cross-validation. Tip: start with simple models and add complexity only when errors justify it.