Skip to content

How to build a demand forecasting model: lessons from retail

I have worked with many retailers and large amounts of data. I've seen and tried different strategies to create good demand forecasting models and I'll try to explain here what worked best and what are complexities that I had to work around or make decisions about.

You will see that at every step, a range of new questions appear and not being overwhelmed is a must to be able to keep going.

The goal

Usually a demand forecast model aims to predict the demand (sales) at some point in time in the future. Could be just one specific day, could be multiple days into the future. This is important, because some approaches can handle only some of those scenarios.

So, let's say we want to predict sales for the next 15 days. We have transactional data (every customer purchase by product/SKU). What's important for the business?

Situation 1: define the level you forecast at

We want to narrow down this and have a clear scope and be very specific. A better phrasing could be:

We want to predict daily sales for the next 15 days at the store and brand level.

Here we have our first problem to tackle. We need to go from transactional data to store-brand level data. I'm keeping it simple here, a real project might have sub brands, or multiple categories per brand (say Nike, but we have Nike Sports Men, Nike Sports Women, Nike Basketball Kids, etc).

We can aggregate quantities quite easily (summing) but what about prices? Weighted mean sounds like a good option...

A good mental model to have here is that every entity to predict (brand sales by store for example) is an independent time series. So, you have as many time series to predict as store-brands... This is a number worth having in mind.

Sketch of transactional sales data by date, store and SKU being aggregated into daily sales by store and brand, with the aggregated price left as an open question

Situation 2: why brand level and not SKU level

Why brand level and not product level? Well, it depends on the business domain but at the product/SKU level a range of situations might happen:

  1. having too many SKUs -> exponential growth of datasets
  2. SKUs not selling on a daily basis (intermittent time series)
  3. SKUs appearing and disappearing over time (products leave and get into the market)

At a high level, I could say that this also depends on your team and infrastructure. So, if you have Walmart scale, you probably can handle very large datasets with distributed and high performance infrastructure, and have people working on subsets of the problem but let's assume you are not at that scale.

1) Data size. To properly train a model you need the full history of the product, including all those days where sales were 0 because that's valuable information and you will have 0 sales days in the future. However, transactional data doesn't have that, you only have sales, so when filling all the blank days with 0 you will increase the size of the data. How much depends on your specific data. At the SKU-store level this increase could be huge.

Aggregating at the brand level can minimize this effect. Of course this depends on your specific question. What if you really need it at the product level? (another rabbit hole...)

Tip for low resources

You could train and predict at a higher level (brand) and decompose that prediction based on share by SKU, for example.

2) Intermittent demand. SKUs that don't sell daily and hence have zeros are harder to predict. There are specific methods (Croston's), two-stage methods, etc. They also constrain the metrics available in some sense because MAPE (or any percentage based metric) can break. If reality is 0 and you predicted 1, percentage errors go crazy... and it's harder to optimize and evaluate. You can totally use other metrics but again, it's a small universe and you can spend days on intermittent data. I suggest trying to move into something less intermittent, especially if you have many brands or products to forecast.

If you have only a few time series, then you can do specialized training and work with intermittent data if you are into that, but if you have hundreds or thousands of time series, then dealing with a mix of intermittent and regular time series could be a problem.

3) Products come and go. Brands stay over time despite their SKUs changing. It's more likely that a brand is quite stable despite the mix inside, and if it changes patterns then the model should eventually learn that. At the product level, if a SKU is dropped then you need to know that in advance to stop forecasting it, and what do you do when a new one enters the market? Another rabbit hole to explore...

Situation 3: how to forecast 15 days ahead

How do we predict 15 consecutive days? It's not trivial because it depends on the family of models we use.

Regression and tree-based models

Starting simple, we have our aggregated dataset by day, store, brand and price for example. We decide we want a baseline using linear regression to see how well we predict with a simple model.

Without going into much detail yet about the features, we need the date in some way (day of the week, week of the year, other transformation) to take into account the time dependence of this problem and seasonality.

We want to predict a new observation, sales of tomorrow. If we have the day of the week, week of the year and other features we can do that. And we could do that for every other date in the future. So we can prepare a dataset with the 15 days we want to predict, put the price and any other feature such as brand and store as categorical and predict.

Now, that's rather simple in terms of features. A lot of demand forecast models rely on features about past performance such as lagged sales, average sales in the last X days, etc. We can create those features in the training dataset without problems. But if we have a feature that is average sales of the last 7 days, then we can create it for the next day prediction after our last training datapoint, but we can't for the day after that, because we don't know yet how much the brand will sell the day just after the last training datapoint. After that day, we can't create the features.

Option 1: one model per horizon (direct forecasting)

Create one model per day after the last training data we want to predict. In this case, we would need to create 15 models. One for tomorrow, one for the next day, and so on. The features would be all the same. We can include the average of the last 7 days until the last day we have data, and with those features we estimate sales for every day after we want. It is expected that performance degrades as we move further away, like predicting 15 days into the future using data until today is probably harder than predicting tomorrow. We need to be very careful creating these models while putting together the training data, as every observation should have the right point in time value for each lagged or window feature.

Option 2: one model, recursive forecasting

Create one model that predicts the next day sales and do a recursive forecast. We predict tomorrow and then we use that prediction as our estimate for the sales of that day. We can compute the average 7 days sales using that expected value and that way predict the day after, and so on. Again prediction is expected to degrade as we go further away. Any error in prediction will have a cumulative error as all predictions will be based on that. But we can keep only one model and we can predict as many days as we want. If for some reason we need 16 days, we don't need to train another model, we just need to extend the recursion one more day.

A talk that helped me think about this: Jean François Puget.

Time series models

Another approach is using time series models that kind of automatically handle the recursive issue and are able to predict well into the future out of the box, of course with higher uncertainty and lower performance as we move forward. This can work fine if you have one or a manageable amount of time series. As far as I know it's not trivial to predict thousands of independent time series. A time series needs its own parametrization and requires some care to define it and estimate it. One of the best resources to dig deeper is Rob Hyndman - Forecasting: Principles and Practice.

How: one global model with LightGBM

Back at the goal:

We want to predict daily sales for the next 15 days at the store and brand level.

If we have multiple (hundreds, thousands) of different store-brand combinations, my experience is that time series models could be a big headache if you need to manage them in some way independently. Even more, most of the approaches are individual and do not leverage having time series with similar patterns.

One way to tackle this is to use a single machine learning model including all the data and having a way to get results for each "time series", like having features for each store and brand. In linear regression or tree-based methods it could be a categorical variable for each store and brand for instance. There are other approaches, such as including numerical representations of brands and stores instead.

One of the most successful approaches is LightGBM, a gradient boosting library (same family as XGBoost). More in particular, there is a forecasting competition where in one edition they tackled this problem with a Walmart dataset. This is one of the best sources and there is a lot of literature around it worth the time: M5 Competition.

I recommend reading:

There are many more papers associated with the topic and how they developed models for the competition. Also there are notebooks from the top solutions sharing the code they used and write-ups.

Some takeaways that helped me implement a model:

  • LightGBM was used in many of the top performing solutions
  • The recursive approach was also used
  • Feature engineering is really important. Lagged variables, averages
  • Seasonality shared across products is really helpful and is one of the main drivers
  • Working with price is hard, do it carefully. Point in time price for the past is not trivial (promotions, etc) and having future price is also tricky sometimes.
  • Embeddings for stores and brands (or categories) are useful and help with generalization

Evaluation

If you take a look at the M5 competition you will see they use a custom weighted metric, which makes sense to have a single metric useful to evaluate thousands of competitors based only on the model.

For my use case I kept it simpler, which I think should be the rule unless there is proof of a more complex alternative.

For good intuition about performance and to have a simple metric that is also shareable with non technical people I used and recommend MAPE (Mean Absolute Percentage Error), basically, what's your average error in terms of percentage of sales. However, there are nuances to take into account, traps to avoid. It works well for large and aggregated categories where sales are more or less stable in terms of scale. For our main time series that handle most of the sales this was great, but it fails with low selling series or highly seasonal ones, as approaching 0 the errors get higher. If sales were 1 and you predict 3 you have a 200% error for that observation, which is kind of crazy, while 103 predicted vs 100 sold is only 3%.

So, takeaway: be careful with intermittent time series, really low selling ones, or time series that go to 0 in a specific time of the year (bikinis during winter...).

Daily sales and model predictions for a highly seasonal series over two years, with sales dropping close to zero for several months each year

You can trade a bit of explainability for RMSE (Root Mean Squared Error), which is in absolute differences and not percentage. You can use it across the board but you probably need some reference to anchor the error and understand it. For the model itself it's a good error to optimize for / loss function.

How to use these metrics

We have the metrics but how do we evaluate the model? We need a train-validation-test split ideally. Many things to mention here.

1) Use a time series split. When training the model (and doing parameter optimization) be sure to do a time series split. This is crucial and means that your train, validation and test splits are not random. They should be consecutive and time arranged. Train is the older data and validation comes after. You train the model on train data and evaluate on validation. This is the only way to have some real production data structure and you don't leak changes of behavior into your training data. If you do cross validation, you keep it this way.

Time series cross validation: each fold trains on an expanding window of older data and tests on the period right after it

What I call validation could be test in this image.

2) Focus on the series that matter. You should probably pay more attention to the most important series for your use case and don't get crazy about errors in series that initially won't be highly inspected.

Anonymized heatmap of forecast error by category: rows are high level categories such as Men, Women and Kids, columns are sub categories such as Running, Trekking and Basketball

Anonymized chart. You can visualize lots of time series this way and compare across categories. Each row corresponds to all the time series of a particular high level category such as Men. Each column is a sub category. Columns with multiple rows exist for both Men and Women, for instance.

3) Keep a final test set. After evaluating and getting hyperparameters using train and validation, you need to later evaluate on the test set, which is a set that was completely unused before, neither for training nor for evaluation during any stage. This is your final evaluation, it should be the most up to date data, and it will best reflect how your model performs on unseen data.

4) Evaluate what the business uses. Be creative and true to yourself regarding evaluation. Our goal was to predict 15 days in advance. We care about individual predictions but also about the aggregated level of the 15 days. We also created evaluations using the sum of the 15 days of predictions against real data. Maybe that's the most relevant value to look at!

Deployment

Once you have a model trained and evaluated that you are happy with and you want to start using it for your goal, you need to deploy it somehow, somewhere. Many strategies here and it depends a lot on your organization, your stack, your people, etc.

One way is to create an API that has the model loaded in memory and you can run inference based on parameters such as date, category, etc. This will get the data from the database, prepare the features to be in the same format the model expects them and run inference on that subset of data. Lots of flexibility depending on what you actually need. Some teams prefer feature stores instead of preprocessing on the fly. Others have strict needs and they don't need much flexibility around the parameters initially.

If you know exactly what to run every day you can have a small workflow and run it on a cron job or with some scheduler. That's also deployment despite not having an API exposed.

Or, as a different flavor, a CLI that is called on an instance that is spun up and shut down daily during a specific time range, which is enough to run the process.

Many approaches are available, and they need to be customized for your specific needs and use case.


If you are working on a demand forecasting problem and want help with it, see how I work with companies.