Codeunit 2000 Forecasting in Business Central: From Sales History to MPS and MRP

Reading Time: 10 minutes

Every Business Central tenant already has a forecasting engine. Most people never use it. It sits in codeunit 2000, “Time Series Management”, and it is the same Azure AI service that feeds the cash flow forecast and Microsoft’s Sales and Inventory Forecast extension. It runs ARIMA, ETS, STL and TBATS, and in Business Central online you do not need an Azure subscription to call it.

At the same time, most manufacturing companies I work with have an empty Demand Forecast page. MPS and MRP run only on sales orders, so everything with a lead time longer than the order book shows up late. The planner fixes this with a spreadsheet, a reorder point nobody remembers setting, or both.

This post connects the two. It shows how to take posted sales (or consumption), send them to codeunit 2000, and write the result as demand forecast entries that MPS and MRP really use. You get a free extension that does it, diagrams of every step, and the code explained line by line.

Get the Code

github.com/GmsoftLtd/bc-demand-forecast-mps-mrp

Free. MIT licensed. Object range 50500 to 50599, so no conflict with bc-safety-stock, bc-eoq-calculator, bc-reorder-point or bc-replenishment-policy. Runtime 18.0, built and checked against Business Central 29 (2026 release wave 2).

At a Glance

QuestionShort answer
Where is the forecasting engine?Codeunit 2000 “Time Series Management” (namespace System.AI), tables 2000 “Time Series Buffer” and 2001 “Time Series Forecast”
Do I need Azure?Not in BC online: the Microsoft-hosted service is used. On-premises you need your own Azure ML endpoint
What goes in?One series per item: a value per week or month, with zero for empty periods
What comes out?A forecast per item and period, plus a range (Delta, Delta %)
How does planning use it?You write it as Demand Forecast Entries. MPS nets it against sales, MRP against component need
Sales or component forecast?Sales history gives a sales item forecast (MPS). Consumption history gives a component forecast (MRP)

The Big Picture

From item ledger to planned orders

There are two halves, and it helps to keep them apart.

The first half is pure forecasting. Codeunit 2000 reads history, sends it to the service and gives you back numbers in a temporary table. It knows nothing about planning. It does not write anything.

The second half is standard Business Central planning. MPS and MRP read Demand Forecast Entries (table 99000852, “Production Forecast Entry” in AL). They do not know or care where the numbers came from.

The bridge between the two is your code: a few lines that turn the Time Series Forecast table into forecast entries. That bridge is what nobody ships, and it is what the extension does.

Codeunit 2000 in Five Calls

These are the public procedures you need, checked against the Base Application 29 symbols:

ProcedureWhat it does
Initialize(Uri, Key, TimeOutSeconds, UseStdCredentials)Connects. In BC online pass an empty URI and key and true for the Microsoft-hosted service. The key is SecretText
PrepareData(Record, GroupFieldNo, DateFieldNo, ValueFieldNo, PeriodType, StartDate, Periods)Reads any table and sums one field per group and period into the Time Series Buffer
SetPreparedData(TempBuffer, PeriodType, StartDate, Periods)The alternative: you fill the buffer yourself
Forecast(Periods, ConfidenceLevel, Model)Calls the service
GetForecast(TempTimeSeriesForecast)Returns Group ID, Period No., Period Start Date, Value, Delta and Delta %

The call order never changes:

Call sequence

And here is the heart of the extension. It is short on purpose:

[TryFunction]
local procedure TryForecast(ItemFilter: Text; var TempTimeSeriesForecast: Record "Time Series Forecast" temporary)
var
    ItemLedgerEntry: Record "Item Ledger Entry";
    TimeSeriesManagement: Codeunit "Time Series Management";
    NoKey: SecretText;
begin
    // BC online: empty URI + key + standard credentials = Microsoft-hosted service
    TimeSeriesManagement.Initialize('', NoKey, 0, true);

    // History: posted sales (or consumption) before the first forecast period
    ItemLedgerEntry.SetFilter("Item No.", ItemFilter);
    ItemLedgerEntry.SetRange("Entry Type", GetEntryType());
    ItemLedgerEntry.SetFilter("Posting Date", '<%1', ForecastStart);

    TimeSeriesManagement.PrepareData(
        ItemLedgerEntry,
        ItemLedgerEntry.FieldNo("Item No."),      // one series per item
        ItemLedgerEntry.FieldNo("Posting Date"),  // date of each entry
        ItemLedgerEntry.FieldNo(Quantity),        // value to sum per period
        GetDatePeriodType(),                      // Date."Period Type"::Month or ::Week
        ForecastStart,                            // history runs back from this date
        HistoryPeriods);                          // for example 24 months

    TimeSeriesManagement.Forecast(HorizonPeriods, ConfidencePct, Model.AsInteger());
    TimeSeriesManagement.GetForecast(TempTimeSeriesForecast);
end;

A few things in there are not obvious, and each one cost me time.

It is a TryFunction on purpose. The service can fail: no connection, a time-out, or the tenant has used its monthly Azure AI allowance. A TryFunction catches that, the batch is counted as failed and the run continues with the next batch. This only works because nothing is written to the database inside it. All the writing happens afterwards.

PrepareData fills the gaps. The service does not accept missing periods. A month with no sales must be sent as 0, not skipped. PrepareData does that for you. If you build the buffer yourself with SetPreparedData, it is your job.

The model is an Option, not an enum. The ordinals are 0 ARIMA, 1 ETS, 2 STL, 3 ETS+ARIMA, 4 ETS+STL, 5 ALL, 6 TBATS. The extension has its own enum with the same ordinals and passes AsInteger().

Send items in batches. Microsoft’s own documentation mentions time-outs with ARIMA on big datasets. The extension sends 50 items per call. You can change that with SetBatchSize.

The Sign Trap

Sales and consumption are negative in the Item Ledger Entry. PrepareData sums Quantity as it is, so the forecast comes back negative too. If you write that straight into the demand forecast, planning sees negative demand and does nothing. Silently.

// Sales and consumption are negative in the item ledger, so the forecast is negative too.
ForecastQty := Round(-TempTimeSeriesForecast.Value, 0.00001);

if (MaxDeltaPct > 0) and (Abs(TempTimeSeriesForecast."Delta %") > MaxDeltaPct) then
    LinesSkippedUncertain += 1
else
    if ForecastQty > 0 then
        InsertEntry(LastItemNo, TempTimeSeriesForecast."Period Start Date", ForecastQty);

The second part is the Delta. Every forecast line comes with a range: Delta is the plus-or-minus around the value at the confidence level you asked for, and Delta % is that range as a percentage. Microsoft suggests treating forecasts with a range wider than 20 to 30 percent of the value with suspicion. The extension has a “Skip Lines Above Delta %” option for exactly this. I leave it at 0 for the first run, look at the numbers, then set it.

Which Model?

ModelWhen I use it
ARIMAThe default. Good start for most items with 2 years of monthly history
ETSSmooth demand with a trend
STLStrong yearly seasonality, but only with more than two years of data
ETS+ARIMA, ETS+STLThe average of the two. Useful when one model alone jumps around
ALLRuns every model and keeps the one with the lowest error (MAPE). Costs more processing time
TBATSAvoid on short histories: it can return extreme values

With six months of history, ARIMA cannot even calculate a range. Twenty-four monthly periods is where I start, and for seasonal items 36 is better: two seasons is the bare minimum. The request page will not let you go below six.

Measure it before you trust it

A forecast you have not tested is a guess with decimals. Before the numbers reach planning, hide the last six months, forecast them from the history before, and compare with what really happened. Two figures are enough to start: WAPE, the sum of the absolute errors divided by the sum of actual demand, and bias, the sum of forecast minus actual divided by actual demand, which tells you if you always forecast too high or too low. Then do the same with a naive forecast: last month repeated, or the same month last year for seasonal items. If ARIMA does not beat the naive forecast on an item, do not use it for that item. ARIMA is not automatically better than a moving average, and for intermittent demand a Croston-type method usually does better than both.

How MPS and MRP Use the Forecast

This is the part most posts skip, and it is the reason a forecast either works or makes planning worse.

MPS and MRP

MPS works on end items: items with a sales order line or a forecast. MRP works on everything else, the items with dependent demand from a parent. Business Central identifies the MPS items when the calculation starts. Usually you run both together.

There are two kinds of forecast, and the extension writes the right one depending on the Demand Source you choose:

  • Sales Item forecast, from Sale history. Independent demand. Sales orders reduce it.
  • Component forecast, from Consumption history. Dependent demand. Component lines of production orders reduce it, so it does not add up on top of the BOM: a forecast of 200 for a component that the BOM already needs 200 of gives 200, not 400. Only the part above the BOM need counts as extra demand. Use it when the parent cannot be forecast, typically for the stocked components of make-to-order items. Spare parts sold to customers are Sale entries, so give them a sales item forecast instead.

Forecast consumption, in numbers

The forecast itself is never changed by sales. What planning does is reduce the forecast quantity by the sales in the same forecast period, and only the remainder enters the demand profile. “Sales” means open sales orders and what was already shipped in that period. A forecast period runs from the forecast date to the date of the next forecast entry.

MonthForecastShippedOpen sales ordersRemaining forecastDemand planning sees
January1003050100 – 80 = 2050 + 20 = 70
February11001300130
March1200408040 + 80 = 120

January is the classic case: the forecast is partly used up, and the rest stays as demand. February shows why a forecast is not a cap: when orders are higher, orders win. March is where the forecast earns its money: there are only 40 orders yet, but planning prepares for 120.

Two more rules from Microsoft’s design notes. Forecast for periods before the planning starting date is ignored, consumed or not. And a component forecast higher than the sales item forecast of its parent is treated as extra independent demand.

Setup that planning reads

WhereFieldWhat to do
Inventory SetupCurrent Demand ForecastThe forecast planning uses by default. The extension can set it for you
Inventory SetupUse Forecast on LocationsOff, because the sample writes at item level without location
Inventory SetupUse Forecast on VariantsOff, same reason
Inventory SetupCombined MPS/MRP CalculationOn, to run both in one go
Calculate Regenerative PlanMPS, MRPTick both
Calculate Regenerative PlanUse ForecastThe forecast name, for example TS-FCST
Calculate Regenerative PlanExclude Forecast BeforeUsually the planning starting date

A note for upgraders: in Business Central 29 these four setup fields live on Inventory Setup. The old ones on Manufacturing Setup are marked obsolete (“field moved to same field in table Inventory Setup”). Microsoft Learn still points to Manufacturing Setup in some places, so do not be surprised.

Which items should get a forecast

Not all of them. My rule:

  • Lot-for-Lot items are usually the best fit for a forecast. Planning creates supply for the forecast and the sales on top of it, period by period. Usually, not always: a stable, cheap purchased part with a long lead time is often better on a reorder point and safety stock (see bc-reorder-point). Choose per item, based on variability, lead time and order cost, not one policy for the whole company.
  • Fixed Reorder Qty. and Maximum Qty. items already carry demand in their reorder point, which is demand during lead time. Add a forecast as well and you count the same demand twice. Pick one.
  • Order (make-to-order) items should not have a forecast. Microsoft says it plainly: forecasts should not create supply that is bound order-to-order. For MTO end items, forecast the stocked components instead, with a component forecast.

Going Further: Per Location

PrepareData groups by one field only. If you need a forecast per item and location, build the buffer yourself and use SetPreparedData. Group ID is Code[50], so “ITEM|LOCATION” fits. This example is in the repository too (codeunit 50501):

for PeriodNo := 1 to HistoryMonths do begin
    // Period 1 is the oldest month, the last one is the month before ForecastStart
    PeriodStart := CalcDate(StrSubstNo(MonthsBackTok, HistoryMonths - PeriodNo + 1), ForecastStart);

    ItemLedgerEntry.SetRange("Item No.", ItemNo);
    ItemLedgerEntry.SetRange("Location Code", Location.Code);
    ItemLedgerEntry.SetRange("Entry Type", ItemLedgerEntry."Entry Type"::Sale);
    ItemLedgerEntry.SetRange("Posting Date", PeriodStart, CalcDate('<CM>', PeriodStart));
    ItemLedgerEntry.CalcSums(Quantity);

    TempTimeSeriesBuffer.Init();
    TempTimeSeriesBuffer."Group ID" := CopyStr(ItemNo + '|' + Location.Code, 1, MaxStrLen(TempTimeSeriesBuffer."Group ID"));
    TempTimeSeriesBuffer."Period No." := PeriodNo;
    TempTimeSeriesBuffer."Period Start Date" := PeriodStart;
    TempTimeSeriesBuffer.Value := -ItemLedgerEntry.Quantity; // positive this time
    TempTimeSeriesBuffer.Insert();
end;

TimeSeriesManagement.SetPreparedData(TempTimeSeriesBuffer, DateRec."Period Type"::Month, ForecastStart, HistoryMonths);

Two things change when you do this. You write the forecast entries with a Location Code, and you turn on Use Forecast on Locations, otherwise planning adds everything up into the blank location. For a real tenant, replace the CalcSums loop with a Query object, because one CalcSums per item, location and month adds up fast.

Developer and AL Notes

  • Credentials. Initialize('', NoKey, 0, true) uses the Microsoft-hosted service and only works in BC online. On-premises, pass your own Azure ML URI and key. Keep the key in isolated storage, never in a table field.
  • SecretText. In current versions the key parameter is SecretText. Old blog examples pass a Text constant, and that does not compile any more.
  • Usage. The hosted service counts against the tenant’s Azure AI usage. Batches, a sensible history length and a single model (not ALL) keep it low.
  • Replace, do not append. Each run deletes the future entries of the same items in the same forecast, then inserts the new ones. History entries and the other forecast type are kept. Without this, every run adds on top of the last one.
  • Permissions. The permission set “Time Series Demand Forecast” gives read on Item Ledger Entry and insert and delete on Production Forecast Entry. Planners who only run planning do not need it.

Install and Try It

Sandbox first:

  1. Clone the repository, download the symbols and publish from VS Code, or upload a release .app in Extension Management
  2. Assign the permission set Time Series Demand Forecast
  3. Search for Create Time Series Demand Forecast
  4. Filter a handful of items you know well. Keep the defaults: TS-FCST, Sales, Month, 24 history periods, 6 forecast periods, ARIMA, 80%
  5. Open Demand Forecasts, then TS-FCST, and compare the numbers with what your sales people expect
  6. In the Planning Worksheet, run Calculate Regenerative Plan with MPS and MRP ticked and Use Forecast = TS-FCST

The extension only writes to Demand Forecast Entries, and to Inventory Setup if you tick Set as Current Demand Forecast. Delete the forecast name and everything is gone.

What It Does Not Do

It is a sample, and it is honest about that. It forecasts at item level only, with no review step before the numbers reach planning, and no measure of how good last month’s forecast was. For that you need forecast versions with approval, back-testing per item and a forecast accuracy log. That is the job of my app Demand Forecast Replenishment, which uses the same codeunit 2000 underneath.

Summary

Codeunit 2000 gives every Business Central tenant a real forecasting engine, and MPS and MRP are already waiting for a demand forecast. The missing piece is a small bridge: send the right history, flip the sign, check the range, write entries to the right forecast type, and pick the items where a forecast makes sense. With that in place, planning stops reacting only to the order book.

Resources

If your Demand Forecast page is empty and your planners live in a spreadsheet, install this in a sandbox and run it on ten items you know by heart. If the numbers look sensible, you have just found a forecasting engine you were already paying for.


Questions, an edge case, or a planning behaviour you cannot explain? Get in touch.


Discover more from Inside Business Central

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top