To prepare a sales time series for an AI forecast, first build a calendar for each product–store pair, then join daily sales and indicators for load completeness and item availability. Fill missing operations with zero only when full loading is confirmed. Keep stockout days separate: zero sales on an empty shelf do not show the size of unmet demand.
This guide is intended for retail analysts and replenishment process owners. The output is a daily table with actual sales, observation conditions, and a separate column for later modeling. Model training, lost-demand reconstruction, and order calculation are not performed here.
The material was prepared by Vladimir Lomtev’s AI studio, which focuses on data preparation and ML solutions. The documentation was reviewed on November 16, 2026. The code shown was run in a single session on Python 3.14.3 and pandas 3.1.1, using fictional data only. Its result confirms that the transformation works as shown, not the forecast accuracy or readiness for integration with your accounting system.
Contents
- 1. Define what one row should mean
- 2. Prepare sales and independent day statuses
- 3. Build the calendar grid while preserving unknown values
- 4. Separate actual sales from the target series
- 5. Check the result before sending it to the model
- 6. Choose missing-value handling for the model
1. Define what one row should mean
Lock down the key: one SKU, one store, one calendar day. SKU is the identifier of a specific product item. In this example, the unit of measure is units sold; sales are counted after agreed exclusion of cancellations, and returns have already been separated. Returns must not be quietly mixed into sales: a negative daily total would describe a different metric.
Choose the start and end of the period based on the task, not on the first and last sales you find. Otherwise, days without transactions at the edges of the extract will disappear. For a new item, use the date it was added to the assortment at that store; do not turn the period before that into a history of zero demand.
Convert the event date to the store’s approved time zone before grouping. Local dates without times are already used below, so the code does not perform time zone conversion. For multiple locations in different time zones, this step should be done separately.
A consistent definition may look like this:
Key: SKU + store + local date.
Metric: units sold, cancellations excluded, returns separate.
Period: from the product’s introduction into the assortment to the last closed day.
Day boundary: store time zone.
Incomplete load: unknown observation, not zero.
The result of this step is an unambiguous definition of the row and the unit of measure. If the goal is to forecast actual sales under a known schedule, a closed store may have a target of zero. If you are estimating demand at an operating store with product available, that day cannot be used as a normal observation. The example below uses the second option.
2. Prepare sales and independent day statuses
A receipts extract alone is not enough: a missing row may mean no customers, a data exchange failure, or a closed store. You will need a second source that confirms the observation conditions for the day. The indicators in the example are set manually as training inputs; the program does not infer them from receipts.
| Field | Meaning | Source in the workflow |
|---|---|---|
date |
Local date | Accounting system after the day boundary is agreed |
qty |
Units sold in the transaction | Sales rows after cancellations and returns are excluded |
load_complete |
All day’s transactions were loaded | Control over exchange completion and period close |
open |
The store was operating under the approved rule | The store’s operating calendar |
availability |
The product was available all day, part of the day, or unavailable | Availability history, not just end-of-day inventory |
A zero inventory balance in the evening does not prove the item was unavailable in the morning. A positive evening balance also does not rule out daytime stockouts. If you only have evening snapshots, the honest status is "availability within the day unknown." Do not assign full automatically from such a snapshot.
For the minimal example, we use the week of November 1–7, 2026. On the first day there are two transactions — 2 and 1 units; on the third day, 5 units were sold; on the fifth, 2 units. On the second day the store is open, the item is available, the exchange is complete, and there are no transactions. On the fourth day the item is unavailable, on the fifth it is available only part of the day, on the sixth the store is closed, and on the seventh the exchange is not complete.
The result of this step is two aligned tables. For real sales, you also need a transaction ID or document line ID: re-importing the same transaction must not increase the total. The code below assumes duplicates have been removed before it runs. Do not remove duplicates just because the date and quantity match: two real sales can be identical.
3. Build the calendar grid while preserving unknown values
In pandas, the date_range function creates a sequence of dates at a specified frequency. The reindex method aligns data to a new index; new positions get missing values by default. This makes it possible to show missing days first, then decide how to fill them.
The daily total is obtained with groupby. The min_count=1 parameter in group summation requires at least one non-empty value to calculate the total. But it does not verify the completeness of all operations. That is why the example stops if there is a missing value in the source qty and separately tracks whether the load is complete.
Below is a fully reproducible example. You need Python and an installed pandas package; the editorial run used version 3.1.1. The code does not read production files, connect to 1C, or send data to an external model.
import pandas as pd
# Fictional sales for one SKU in one store.
sales = pd.DataFrame({
'date': ['2026-11-01', '2026-11-01', '2026-11-03', '2026-11-05'],
'qty': [2, 1, 5, 2],
})
sales['date'] = pd.to_datetime(sales['date'])
sales['qty'] = sales['qty'].astype('Int64')
assert sales['date'].notna().all() and sales['qty'].notna().all()
assert sales['qty'].ge(0).all() # In this example, returns have already been separated.
calendar = pd.date_range('2026-11-01', '2026-11-07', freq='D', name='date')
status = pd.DataFrame({
'load_complete': [True, True, True, True, True, True, False],
'open': [True, True, True, True, True, False, True],
'availability': ['full', 'full', 'full', 'none', 'partial', 'none', 'full'],
}, index=calendar)
assert sales['date'].isin(calendar).all()
assert status.index.is_unique and status.notna().all().all()
# Total by day; new dates remain NA until load verification.
daily = sales.groupby('date')['qty'].sum(min_count=1).reindex(calendar)
result = status.copy()
result['recorded_units'] = daily
result['sales_units'] = daily
no_rows = ~result.index.isin(sales['date'])
result.loc[no_rows & result['load_complete'], 'sales_units'] = 0
result.loc[~result['load_complete'], 'sales_units'] = pd.NA
# Conditional target series: only observations with full availability.
eligible = (result['load_complete'] & result['open']
& result['availability'].eq('full'))
result['target_units'] = result['sales_units'].where(eligible)
print(result.to_string())
assert len(result) == 7 and result.index.equals(calendar)
assert result.loc['2026-11-01', 'sales_units'] == 3
assert result.loc['2026-11-02', 'target_units'] == 0
assert result.loc['2026-11-04', 'sales_units'] == 0
assert result.loc['2026-11-04':'2026-11-07', 'target_units'].isna().all()
assert pd.isna(result.loc['2026-11-07', 'sales_units'])
assert result['recorded_units'].sum(min_count=1) == sales['qty'].sum()
print('CHECKS: PASS')
Checks assert here are intended for a training run. In a production workflow, input validation checks should fail explicitly and preserve the reason; do not rely on assert if Python may be run with optimizations that disable these checks.
For multiple SKUs and stores, first build a separate calendar for each active pair. Do not use an unrestricted Cartesian product of all products and all locations: it will add combinations that never existed. The dates of assortment entry and exit are needed separately for each pair.
The output of this step is one row for each day in the required period. In a real status table, check key uniqueness before joining. In pandas.merge the parameter validate="one_to_one" lets you check the required join cardinality; the example shown does without merge because both tables are already aligned on a single index.
4. Separate actual sales from the target series
The example produces three numeric columns. recorded_units stores the sum of found transactions without filling in missing days. sales_units adds confirmed zero sales, while leaving the value unknown when loading is incomplete. target_units further excludes a closed store and days with partial product availability from the regular observations.
This is a suggested rule for preparing the target variable for the task of “sales when the store is open and the item is fully available.” It does not reconstruct true demand. Even a day with no stockout can depend on price, promotions, product visibility, and channel operations. Your specific problem may require different features and a different selection rule.
| Date | Conditions in the training example | sales_units |
target_units |
|---|---|---|---|
| November 1 | Open, full availability, full load | 3 | 3 |
| November 2 | Same, but no transactions | 0 | 0 |
| November 3 | Open, full availability, full load | 5 | 5 |
| November 4 | Item unavailable, full load | 0 | NA |
| November 5 | Item was available for part of the day | 2 | NA |
| November 6 | Store closed, no transactions | 0 | NA |
| November 7 | Loading not complete | NA | NA |
NA means “value is unknown or excluded by the selected rule,” not zero. The reason can be recovered from neighboring statuses. The capitalized type Int64 lets you store whole numbers and pd.NA; the rules for working with them are described in the pandas missing-data documentation.
The fourth and second days have the same actual sales, but a different meaning for modeling. The fifth day shows another case: positive sales do not make an observation fully usable if the item ran out before the end of the day. Do not remove these days from the source table — keep the facts and flags so you can choose the modeling approach later.
In the Hyndman and Athanasopoulos textbook Forecasting: Principles and Practice, Section 13.9 emphasizes that missing-value handling depends on the reason they are missing. The authors separately discuss a store closed for a holiday and the possible change in sales afterward. This is not a ready-made demand reconstruction algorithm: calendar context must be taken into account for the specific problem.
5. Check the result before sending it to the model
In the editorial run, the full code ended with the line CHECKS: PASS. Seven calendar rows were checked, the sum of the first day’s two transactions, preservation of the true zero on the second day, an unknown target for days 4–7, unknown sales on the seventh day, and the match between the sum of found transactions before and after aggregation. The total found sales were 10 units.
These are transformation checks on one fictional example. They do not prove that any input file will be processed correctly. In particular, the code does not reconstruct loading, does not detect stockouts from inventory, and does not train a forecasting model. For your own extract, separately verify the following conditions:
- The key
SKU + store + dateis unique, and the period and frequency match the task. - Before aggregation, there are no duplicate transactions or unknown quantities; negative values are handled according to the returns rule.
- The sums of the retained transactions reconcile with the source extract in the same unit of measure.
- Every zero sale has confirmation that the load was complete; for a zero target, the availability rule must also be met.
- Every excluded value has a reason. An unknown status is not converted into a positive fact.
The output of the step is a reproducible table and a clear list of exclusions. If the totals do not match, go back to keys, duplicates, and transaction filters. If the totals match but all missing values became zeros, check the fill rules: arithmetic equality does not confirm the correct meaning of the series.
6. Choose how to handle missing values for the model
First, find out whether the chosen tool accepts missing values in the target column. The presence of NA in a prepared table does not mean it can be passed unchanged to any model. The FPP3 book presents different method behaviors; you cannot transfer one method’s capabilities to another.
If the tool requires a fully populated target, there are several options: use a sufficiently long continuous segment with suitable conditions, choose another method, or estimate missing values separately. The last option creates calculated values that must be distinguished from observations. Automatic fillna(0) does not solve this problem.
Do not fill sales with ffill just because it is available in the library. Carrying yesterday’s five units into today means assuming five sales, not preserving the product’s status. Extending the last known status also requires a validity period and update rules.
When the table is prepared, use the data splitting checklist for demand forecasting. Configure imputation and trainable transformations without access to the future test period. Removing missing values should not compress the calendar as if adjacent remaining rows were always adjacent days.
The result of this stage is a consistent input for a specific tool: which values were observed, which were calculated, which were excluded, and how the calendar is preserved during training. The overall project setup, baseline forecast selection, and error evaluation are covered in the article “Demand Forecasting with AI”.
How a studio helps prepare sales history
Vladimir Lomtev’s AI Studio handles data preparation, ML forecasting, and integration with business systems. For this task, you can discuss combining sales history and availability into a single view, implementing rules for zeros and missing values, and comparing forecasting approaches over aligned periods.
The first step is to choose one product group and locations, describe the current replenishment method, available sources, and limitations. The data readiness criterion can be stated concretely: every date is present, transaction totals are reconciled, and the reason for excluding the target is available for review. Accuracy values and business impact are not promised in advance. Discuss the project.
Bottom line: the calendar does not replace availability data
Collect regular dates, join transactions and independent status records, then separate actual sales from the selected target. An open day with no transactions during full staffing can produce zero. An exchange failure leaves an unknown value, while out-of-stock requires a separate decision about demand modeling. A verified example shows this separation across seven days; for a production system, the input statuses and rules of the specific process still need to be confirmed.


