Quick Guide to Time Series Forecasting by Python Prophet

Gen. David L.
5 min readApr 24, 2024

--

What is Python Prophet?

Prophet is a time series forecasting library developed by Facebook. It aims to simplify the modeling and prediction of time series data, making it easy for users, even those without domain-specific knowledge, to perform time series analysis and forecasting with just a few lines of code.

Prophet features the following characteristics and functionalities:

1. Flexibility: Prophet can handle various types of time series data, including data with multiple patterns such as seasonality, trends, and holidays.

2. Automatic seasonal modeling: Prophet automatically detects and models seasonal patterns in time series data, such as daily, weekly, monthly, or yearly seasonal changes.

3. Interpretability: Models generated by Prophet are interpretable, allowing users to understand trends, seasonality, and other factors influencing time series data.

4. Flexible trend modeling: Prophet automatically selects appropriate trend models based on the data’s characteristics, which can include linear trends, nonlinear trends, and change points.

5. Consideration of holiday effects: Prophet can consider the impact of holidays on time series data and provides a flexible way to define and model different types of holidays.

6. Outlier handling: Prophet is robust to outliers and can effectively handle and exclude outliers that may interfere with forecasting results.

7. Intuitive visualization: Prophet offers rich visualization capabilities to help users better understand patterns and trends in time series data and assess the quality of the models.

The formula for the Prophet model can be summarized as follows:

Where:

- y(t) is the predicted value
- g(t) represents the trend component
- s(t) represents the seasonal component
- h(t) represents the holiday component
- epsilon ε is the error component

Prophet aims to make time series modeling simple and user-friendly, minimizing technical barriers for users. It has been successful in many practical applications, including sales forecasting, trend analysis, weather forecasting, and more.

Prophet is implemented in both R and Python, and it is widely embraced across various industries due to its ability to generate accurate and interpretable forecasts with minimal effort. It is extensively used in fields such as finance and e-commerce, where time series forecasting is crucial for decision-making processes.

How to Install Python Prophet?

To install the Prophet library, you can follow these steps:

1. Make sure your Python environment is installed and configured correctly. You can download the latest version of Python from the official website (https://www.python.org/downloads/).

2. Open a terminal or command prompt.

3. Use the pip command to install the Prophet library and its dependencies. Run the following command:

pip install fbprophet

This will download and install the latest version of the Prophet library from the Python Package Index (PyPI) using the pip package manager.

4. Once the installation is complete, you can import the Prophet library in your Python program and start using it. For example, you can import Prophet as follows:

from fbprophet import Prophet

Now, you can use the functions and classes provided by the Prophet library to model and forecast time series data.

Please note that the Prophet library has some dependencies such as pystan and matplotlib. These dependencies are usually installed automatically, but in some cases, manual installation may be required.

Basic Usage of Prophet

Below is an example of basic time series forecasting using the Prophet library:

import pandas as pd
from fbprophet import Prophet

# Create a time series data frame
data = pd.read_csv('time_series_data.csv')
df = pd.DataFrame()
df['ds'] = pd.to_datetime(data['date'])
df['y'] = data['amount']

# Create a Prophet model
model = Prophet()

# Train the model
model.fit(df)

# Create a data frame for future dates
future_dates = model.make_future_dataframe(periods=30) # Prediction for the next 30 days

# Make predictions
forecast = model.predict(future_dates)

# Print the forecast results
print(forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail())

In this example, let’s assume we have a file named “time_series_data.csv” containing time series data with two columns: “date” and “amount”.

First, we read the data into a DataFrame and convert the date column to datetime format. Then, we create a Prophet model and train it using the training data.

Next, we use the `make_future_dataframe()` function to create a DataFrame containing future dates for prediction in the model. In this example, we set the periods parameter to predict data for the next 30 days.

Finally, we make predictions for the future dates using the trained model and print out the forecast results. The forecast results include predicted values (“yhat”), lower limits (“yhat_lower”), and upper limits (“yhat_upper”), representing the confidence interval range of the predicted values.

Please note that this is just a basic example of the Prophet library. You can adjust and expand the code according to your specific needs, such as adding holiday effects or adjusting model parameters.

Advanced Usage of Prophet

Here are some advanced usage examples of the Prophet library:

  1. Customizing holiday effects: You can consider the impact of specific holidays on predictions by creating a DataFrame containing holiday dates and names, and passing it as the holidays parameter to the Prophet model.
holidays = pd.DataFrame({
'holiday': 'my_holiday',
'ds': pd.to_datetime(['2023-01-01', '2023-12-31']),
'lower_window': -1,
'upper_window': 1
})
model = Prophet(holidays=holidays)

2. Visualizing Results: Prophet provides built-in visualization tools to help you better understand forecast results. You can use the `plot()` method to plot the time series fitted by the model and the forecast results.

model.plot(forecast)

3. Evaluating Model Performance: You can use cross-validation to assess the performance of the model on historical data. By setting the initial and period parameters, you can specify the training and prediction period lengths for each subset. Use the `cross_validation()` function for cross-validation and the `performance_metrics()` function to compute performance metrics.

from fbprophet.diagnostics import cross_validation, performance_metrics
df_cv = cross_validation(model, initial='365 days', period='60 days', horizon='30 days')
df_p = performance_metrics(df_cv)
print(df_p)

4. Adjusting Model Parameters: Prophet has many adjustable parameters, such as seasonality mode (`seasonality_mode`), change point prior scale (`changepoint_prior_scale`), etc. You can adjust these parameters based on the characteristics of your data to obtain better forecast results.

model = Prophet(seasonality_mode='multiplicative', changepoint_prior_scale=0.6)

These are some advanced usage examples of the Prophet library. Prophet also offers additional features and extension options, such as handling missing values, adding extra regression variables, and joint modeling.

In general, for time series in fields like business analytics, Prophet can provide good fitting and forecasting. However, it may not be suitable for time series with weak periodicity or trend. Nonetheless, Prophet offers a method for time series forecasting that can be used by users who may not have a strong understanding of time series analysis to obtain acceptable results. Whether to use Prophet depends on the specific characteristics of the time series.

Thanks for your reading.

--

--

Gen. David L.

AI practitioner & python coder to record what I learned in python project development