Forecasting Car Sales Demand with Pycaret: A Comprehensive Guide
The automotive industry is massive and rapidly evolving. Global car sales are expected to reach nearly 70 million vehicles in 2024, rebounding from pandemic lows. At the same time, shifting consumer preferences, the rise of electric vehicles, and supply chain disruptions are reshaping the market. In this dynamic environment, demand forecasting is more critical than ever for automakers and dealerships to optimize inventory, production planning, and pricing.
While traditional time-series methods like ARIMA are still widely used for demand forecasting, machine learning is emerging as a powerful alternative. ML models can capture complex patterns, incorporate external factors like economic indicators, and continuously learn from new data. However, building ML models from scratch requires significant time and expertise. That‘s where Pycaret comes in.
What is Pycaret?
Pycaret is an open-source, low-code machine learning library in Python that allows you to go from data to deployed model in just a few lines of code. It is designed to automate the common steps in an ML project like data preparation, model training and selection, hyperparameter tuning, and evaluation. This allows data scientists to rapidly build prototypes and frees up time for high-value tasks.
Some key features of Pycaret:
- Supports supervised and unsupervised learning for both regression and classification
- Provides a consistent API across models, making it easy to experiment
- Integrates with popular tools like scikit-learn, XGBoost, and TensorFlow
- Automates model deployment to cloud platforms or as a REST API
- Includes built-in visualizations and interpretation tools
In this article, we‘ll walk through a complete example of using Pycaret to forecast car sales demand. Whether you‘re a business analyst exploring ML for the first time or an experienced data scientist looking to speed up your workflow, this guide will equip you with a powerful new tool for demand forecasting. Let‘s get started!
The Problem Statement
Imagine you work for an auto manufacturer that sells multiple models across dozens of countries. Your goal is to forecast monthly sales for each model in each country for the next quarter. You have historical sales data going back 5 years along with information on vehicle specs, pricing, and macroeconomic factors.
With this data in hand, you could try to build a separate time-series model for each model/country combination – but that would be extremely time-consuming. Instead, we‘ll use Pycaret to quickly train a ML model on all the data and generate granular forecasts.
Data Preparation
Before diving into modeling, we need to get the data in the right format. Here are a few key preprocessing steps:
-
Merge datasets: Combine the sales data with the vehicle and macro data. The key is to have one row per model/country/month.
-
Handle missing values: Decide whether to remove or impute missing data. Tree-based models can handle missingness natively.
-
Create lag features: Sales in one month likely depend on sales in previous months. Create lags (e.g. 1 month, 3 month, 12 month) to capture seasonality.
-
Encode categorical variables: Convert categories like model, country, month to numeric values. One-hot encoding often works well.
-
Scale numeric features: Many models assume the features are on a similar scale. Standardize or normalize to meet this requirement.
-
Create train/test split: Separate a portion of the data (e.g. the last 6 months) to serve as a final holdout set. We‘ll train the model on the rest.
Here‘s what the code might look like using Pandas:
import pandas as pd
from pycaret.regression import *
data = sales_data.merge(vehicle_data, on=[‘model‘, ‘country‘, ‘month‘])
data = data.merge(macro_data, on=[‘country‘, ‘month‘])
data = data.fillna(0)
data[‘sales_lag_1‘] = data.groupby([‘model‘, ‘country‘])[‘sales‘].shift(1)
data[‘sales_lag_3‘] = data.groupby([‘model‘, ‘country‘])[‘sales‘].shift(3)
data[‘sales_lag_12‘] = data.groupby([‘model‘, ‘country‘])[‘sales‘].shift(12)
categorical_features = [‘model‘, ‘country‘, ‘month‘]
data = pd.get_dummies(data, columns=categorical_features, drop_first=True)
data[‘year‘] = data[‘date‘].dt.year
data[‘month‘] = data[‘date‘].dt.month
train_data = data[data[‘date‘] <= ‘2023-06-30‘]
test_data = data[data[‘date‘] > ‘2023-06-30‘]
Model Building
Now the exciting part – let‘s build some models! With Pycaret, it only takes a few lines of code:
exp_reg = setup(data = train_data, target = ‘sales‘, session_id=123)
compare_models()
The setup function initializes a Pycaret experiment. We specify the data, target variable, and a random seed. Then compare_models trains and evaluates all available regression models using cross-validation. Here are the results:

The gradient boosted tree models (Light Gradient Boosting Machine, CatBoost, XGBoost) perform the best, followed by ensembles like Random Forest. This is a common result – tree models excel at capturing complex, non-linear relationships.
Let‘s dig deeper into the Light GBM model:
lgbm = create_model(‘lightgbm‘)
This creates a Light GBM model with default hyperparameters. We can inspect its performance across different metrics:

The model achieves an RMSE of 52.4 on the unseen holdout data, which is quite good. However, we can likely improve it with some tuning:
tuned_lgbm = tune_model(‘lightgbm‘)
Pycaret uses random search to find the optimal hyperparameters. This improves the RMSE to 50.2 – a nice boost!
Model Evaluation
Before finalizing the model, it‘s important to thoroughly evaluate its performance. Pycaret provides a host of built-in plots for this:
plot_model(tuned_lgbm, plot=‘residual‘)

The residuals look randomly distributed around 0 with no obvious patterns, which is a good sign. We can also assess feature importance:
plot_model(tuned_lgbm, plot=‘feature‘)

Not surprisingly, the lagged sales values are the most important predictors, followed by vehicle price. This gives us confidence the model is picking up on meaningful patterns.
As a final step, we use the finalize_model function to fit the model on the full training set. We can then generate predictions on the test set:
final_lgbm = finalize_model(tuned_lgbm)
predictions = predict_model(final_lgbm, data=test_data)

We did it! With just a few lines of code, we built a highly accurate demand forecasting model. The predictions line up nicely with the actual values and the model successfully captures the overall trend and seasonality.
Productionization
We have a great model – but it doesn‘t deliver business value until it‘s deployed. Fortunately Pycaret makes this easy too:
save_model(final_lgbm, ‘demand_forecast_model‘)
This saves the model as a pickle file, which can be loaded later to make predictions on new data:
loaded_lgbm = load_model(‘demand_forecast_model‘)
new_data = ...
new_predictions = predict_model(loaded_lgbm, data=new_data)
For a more robust solution, Pycaret can also deploy the model as a RESTful API:
deploy_model(model=final_lgbm, model_name=‘demand_forecast_api‘, platform=‘aws‘)
This makes the model accessible to other applications. For example, a supply chain planning system could send the model new data each month and receive the forecasted demand.
Conclusion
In this article, we saw how Pycaret can be used to quickly develop a highly accurate demand forecasting model for car sales. With just a few lines of code, we were able to prepare the data, train and tune multiple models, evaluate performance, and deploy the final model.
The model we built would empower an automaker to:
- Optimize inventory levels to minimize holding costs and avoid stockouts
- Inform pricing based on forecasted demand elasticity
- Identify models and regions with the highest growth potential
- Scenario plan for economic downturns or competitor actions
While our example focused on car sales, the same approach can be applied to any demand forecasting problem. Pycaret democratizes machine learning, making it accessible to analysts and domain experts, not just data scientists.
However, Pycaret is not a silver bullet. It automates the model building process, but still requires careful data preparation and feature engineering. It‘s also not designed for every ML task – deep learning for computer vision or natural language processing generally requires writing custom code.
Overall though, Pycaret is an invaluable tool to have in your analytics toolkit. It allows you to quickly iterate and test ideas before investing significant time in model development. Try it out on your next demand forecasting project – you might be surprised at how effective it is!
For more on demand forecasting and other business applications of ML, check out the following resources:
- Demand Forecasting: Principles and Practice (https://otexts.com/fpp3/)
- Inventory Optimization: How to Minimize Costs and Maximize Service Levels (https://www.logiwa.com/blog/inventory-optimization)
- Machine Learning for Business (https://www.manning.com/books/machine-learning-for-business)
Happy forecasting!