Python Advanced - Time Series Analysis with Prophet
Performing time series analysis and forecasting using Prophet in Python
Prophet is an open-source forecasting tool developed by Facebook, designed for simplicity and flexibility in producing high-quality forecasts for time series data. This tutorial explores how to use Prophet for performing time series analysis and forecasting in Python.
Key Points:
- Prophet is an open-source forecasting tool developed by Facebook.
- It is designed for simplicity and flexibility in time series forecasting.
- Prophet can handle missing data and outliers, and it can model seasonal effects and holidays.
Installing Prophet
To use Prophet, you need to install it using pip:
pip install prophet
Loading and Preparing Data
Here is an example of loading and preparing time series data using Pandas:
import pandas as pd
# Load the dataset
data = pd.read_csv('path/to/your/dataset.csv')
# Display the first few rows of the dataset
print(data.head())
# Rename columns to 'ds' and 'y' for Prophet
data.rename(columns={'date_column': 'ds', 'value_column': 'y'}, inplace=True)
Creating and Fitting a Prophet Model
Here is an example of creating and fitting a Prophet model:
from prophet import Prophet
# Create a Prophet model
model = Prophet()
# Fit the model to the data
model.fit(data)
Making Forecasts
Here is an example of making forecasts with a fitted Prophet model:
# Create a DataFrame for future dates
future = model.make_future_dataframe(periods=365)
# Make predictions
forecast = model.predict(future)
# Display the forecast
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())
Visualizing the Forecast
Here is an example of visualizing the forecast with Prophet:
import matplotlib.pyplot as plt
# Plot the forecast
fig1 = model.plot(forecast)
plt.show()
# Plot the forecast components
fig2 = model.plot_components(forecast)
plt.show()
Handling Seasonality and Holidays
Here is an example of modeling seasonality and adding holidays to a Prophet model:
# Create a Prophet model with yearly seasonality
model = Prophet(yearly_seasonality=True)
# Add country holidays
model.add_country_holidays(country_name='US')
# Fit the model to the data
model.fit(data)
# Create a DataFrame for future dates
future = model.make_future_dataframe(periods=365)
# Make predictions
forecast = model.predict(future)
# Plot the forecast
fig1 = model.plot(forecast)
plt.show()
# Plot the forecast components
fig2 = model.plot_components(forecast)
plt.show()
Custom Seasonalities
Here is an example of adding custom seasonalities to a Prophet model:
# Create a Prophet model
model = Prophet()
# Add a custom seasonality
model.add_seasonality(name='monthly', period=30.5, fourier_order=5)
# Fit the model to the data
model.fit(data)
# Create a DataFrame for future dates
future = model.make_future_dataframe(periods=365)
# Make predictions
forecast = model.predict(future)
# Plot the forecast
fig1 = model.plot(forecast)
plt.show()
# Plot the forecast components
fig2 = model.plot_components(forecast)
plt.show()
Evaluating Model Performance
Here is an example of evaluating the performance of a Prophet model:
from sklearn.metrics import mean_absolute_error
# Make predictions on the training data
train_pred = model.predict(data)
# Calculate the mean absolute error
mae = mean_absolute_error(data['y'], train_pred['yhat'])
print(f"Mean Absolute Error: {mae}")
Saving and Loading a Prophet Model
Here is an example of saving and loading a Prophet model:
import joblib
# Save the model
joblib.dump(model, 'prophet_model.pkl')
# Load the model
loaded_model = joblib.load('prophet_model.pkl')
# Verify the loaded model
future = loaded_model.make_future_dataframe(periods=365)
forecast = loaded_model.predict(future)
print(forecast[['ds', 'yhat']].tail())
Summary
In this tutorial, you learned about performing time series analysis and forecasting using Prophet in Python. Prophet is a powerful tool for time series forecasting developed by Facebook, designed to handle missing data, outliers, seasonality, and holidays. Understanding how to load and prepare data, create and fit a model, make forecasts, visualize results, handle seasonality and holidays, add custom seasonalities, evaluate model performance, and save/load models can help you leverage Prophet for high-quality time series analysis and forecasting.