All articles →

100 Exercises / Machine Learning / Practical Machine Learning 100 Exercises

Feature Engineering for Manufacturing Demand: 10 Python Exercises

Build calendar, lag, rolling, and target-encoded features for daily demand forecasts in Python while excluding information unavailable at prediction time.

Use synthetic customer–product order histories to create features available at prediction time. Calendar indicators, past demand, and customer and product summaries help describe the inputs to daily production and purchasing decisions.

This article covers No.051–No.060, the feature-engineering chapter of the 100 Machine Learning Exercises. Each exercise connects a feature to a planning question and checks when its inputs become available.

[!NOTE] This material is adapted, with permission, from notebooks used in corporate training by Surikobo or its representative, Hiroshi Wayama. All data listed is fictional and has no relation whatsoever to real companies, factories, or figures.

Introduction: Practical Challenges in Manufacturing Covered in This Article

Parts manufacturers forecast daily orders to plan materials, equipment time, overtime, and outsourcing. Raw dates and identifiers do not explicitly represent month-end peaks, holidays, customer order cycles, or product demand levels. Build these patterns into features that can be calculated when the forecast is made.

Common situations on site

  • Extracting dates, customers, products, and quantities from ERP but directly entering them into the model
  • Using the average over the entire period as a feature ensures accuracy only during verification
  • Filling missing lags with zero and confusing days off with missing history
  • The definition of features and their availability timing are individualized.

Why is this issue so difficult to judge?

A feature must be available when the forecast is made and reproducible when the model runs again. Even a small amount of future information can make validation results look better than deployment results.

Exercises in this article

No.ThemeConnection to Planning Operations
051Date featureWeekday Cycle, Month, and Quarter Cycle
052Holidays & Business DaysOperating Days and Holiday Effects
053Lag featuresRecent demand and the same weekday last week
054moving averageStandard Demand and Fluctuations
055Customer AggregationCustomer-specific order levels
056Product-specific aggregationItem-specific demand levels
057ratioCapacity Load and Composition Ratio
058interactionCombination of Conditions Effects
059Target EncodingSummarizing demand for many categories
060Data Leak PreventionMatching information available at prediction time

Preparing the Python environment

Run each article from top to bottom in a fresh Jupyter kernel, including collapsed setup cells. [IN: n] and [OUT: n] identify matching input and output. The displayed results were rerun; library versions can affect numbers or formatting even with the same random seed.

Use numpy and pandas for data, matplotlib for plots, and scikit-learn for modeling. Fix the random seed for reproducible runs in the same environment.

[IN: 1]
from IPython.display import display

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder

SEED = 42
rng = np.random.default_rng(SEED)
plt.rcParams["figure.figsize"] = (9, 4.5)
plt.rcParams["axes.unicode_minus"] = False

print("numpy:", np.__version__)
print("pandas:", pd.__version__)
print("matplotlib:", matplotlib.__version__)
[OUT: 1]
numpy: 2.5.1
pandas: 3.0.3
matplotlib: 3.11.0

Creating the synthetic data

From January 2024 to June 2025, we will create daily records for 8 customers × 5 products. The objective variable is the order quantity order_qty. It includes the day of the week, end of month, customer size, product popularity, promotions, and the impact of holidays. capacity_qty is the daily capacity assumed to be allocated to each customer–product pair, not the total shared capacity of the factory. No external data is used.

Show setup code (run this cell)
[IN: 2]
dates = pd.date_range("2024-01-01", "2025-06-30", freq="D")
customers = [f"C{i:02d}" for i in range(1, 9)]
products = [f"P{i:02d}" for i in range(1, 6)]
idx = pd.MultiIndex.from_product(
    [dates, customers, products], names=["date", "customer_id", "product_id"]
)
df = idx.to_frame(index=False)

customer_scale = {
    c: v for c, v in zip(customers, [0.75, 0.9, 1.05, 1.25, 1.5, 0.85, 1.15, 1.35])
}
product_base = {p: v for p, v in zip(products, [18, 25, 34, 43, 55])}
product_capacity = {p: v for p, v in zip(products, [52, 58, 68, 78, 90])}
df["promotion"] = (rng.random(len(df)) < 0.045).astype(int)
df["unit_price"] = df["product_id"].map(
    dict(zip(products, [1280, 1650, 2100, 2480, 3150]))
)

# A fictional calendar modeled after Japanese holidays (does not depend on external calendars)
holiday_dates = pd.to_datetime(
    [
        "2024-01-01",
        "2024-01-08",
        "2024-02-12",
        "2024-02-23",
        "2024-04-29",
        "2024-05-03",
        "2024-05-06",
        "2024-07-15",
        "2024-08-12",
        "2024-09-16",
        "2024-10-14",
        "2024-11-04",
        "2025-01-01",
        "2025-01-13",
        "2025-02-11",
        "2025-02-24",
        "2025-04-29",
        "2025-05-05",
        "2025-05-06",
    ]
)
weekday = df["date"].dt.dayofweek
is_holiday = df["date"].isin(holiday_dates)
business = ((weekday < 5) & ~is_holiday).astype(int)
month_end = (df["date"].dt.day >= 25).astype(int)
season = 1 + 0.10 * np.sin(2 * np.pi * (df["date"].dt.month - 1) / 12)
mu = (
    df["product_id"].map(product_base)
    * df["customer_id"].map(customer_scale)
    * season
    * (1 + 0.18 * month_end)
    * (1 + 0.28 * df["promotion"])
    * np.where(business == 1, 1.0, 0.16)
)
df["order_qty"] = rng.poisson(mu).astype(int)
df["capacity_qty"] = df["product_id"].map(product_capacity)
df["revenue"] = df["order_qty"] * df["unit_price"]

print("shape:", df.shape)
display(df.head())
[OUT: 2]
shape: (21880, 8)
date customer_id product_id promotion unit_price order_qty capacity_qty revenue
0 2024-01-01 C01 P01 0 1280 4 52 5120
1 2024-01-01 C01 P02 0 1650 4 58 6600
2 2024-01-01 C01 P03 0 2100 3 68 6300
3 2024-01-01 C01 P04 0 2480 7 78 17360
4 2024-01-01 C01 P05 0 3150 7 90 22050

No.051: Creating Days of the Week, Month, and Quarter from Dates

Practical purpose

Calendar features represent recurring production and shipping patterns. Weekdays can reflect dispatch schedules, months seasonal demand, and quarters budgeting or inventory cycles.

Method

Extract day of week, month, and quarter from each date. The quarter is q(t)=⌊(m(t)−1)/3⌋+1q(t)=\lfloor(m(t)-1)/3\rfloor+1. For models that would interpret these numbers as continuous magnitudes, use suitable categorical or cyclic encodings.

Check with Python

[IN: 3]
df["day_of_week"] = df["date"].dt.dayofweek
df["day_name"] = df["date"].dt.day_name()
df["month"] = df["date"].dt.month
df["quarter"] = df["date"].dt.quarter
calendar_summary = (
    df.groupby("day_name", observed=True)["order_qty"]
    .mean()
    .reindex(
        ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    )
)
display(calendar_summary.rename("mean_order_qty").round(2).to_frame())
calendar_summary.plot(kind="bar", color="#4472C4")
plt.title("Average order quantity by day of week")
plt.xlabel("Day of week")
plt.ylabel("Average order quantity")
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 3]
mean_order_qty
day_name
Monday 35.70
Tuesday 39.81
Wednesday 40.99
Thursday 41.38
Friday 40.45
Saturday 6.64
Sunday 6.51

No.051: Creating Days of the Week, Month, and Quarter from Dates

Interpreting the results

Orders differ clearly between weekdays and weekends in this synthetic data. Check actual closing times and delivery schedules before assigning the same interpretation to a real factory.

No.052: Create Holiday and Business Day Flags

Practical purpose

The calendar days do not match the actual number of days available. Specifying holidays allows you to separate decreased demand and equipment outages from fluctuations on regular days.

Method

Let HtH_t indicate a holiday and WtW_t a weekend. The business-day flag is Bt=1[(Ht=0)∧(Wt=0)]B_t=\mathbb{1}[(H_t=0)\land(W_t=0)]. The holiday list is synthetic; production use needs the relevant company and customer calendars.

Check with Python

[IN: 4]
df["is_holiday"] = df["date"].isin(holiday_dates).astype(int)
df["is_business_day"] = ((df["day_of_week"] < 5) & (df["is_holiday"] == 0)).astype(int)
business_summary = df.groupby("is_business_day")["order_qty"].agg(
    ["mean", "median", "count"]
)
business_summary.index = ["non-business", "business"]
display(business_summary.round(2))
business_summary["mean"].plot(kind="bar", color=["#A5A5A5", "#70AD47"])
plt.title("Orders on business and non-business days")
plt.xlabel("Calendar class")
plt.ylabel("Average order quantity")
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 4]
mean median count
non-business 6.57 6.0 7000
business 41.35 38.0 14880

No.052: Create Holiday and Business Day Flags

Interpreting the results

The average order volume on non-business days has dropped significantly compared to business days. The business day flag is a prerequisite for material and personnel planning. Whether to use the order date or desired delivery date is defined according to the target variable.

No.053: Creating Lag Features

Practical purpose

Yesterday’s orders and orders on the same weekday last week can inform short-term planning. Lag features make these historical comparisons reproducible.

Method

Within each customer–product series, create Lt,k=yt−kL_{t,k}=y_{t-k} for lags of one and seven days. Here every day is present, so shifting one row means one day. Reindex real data to a complete daily calendar first. The example forecasts one day at a time after the previous day is observed; a weekly batch forecast cannot use actual outcomes from within that future week.

Check with Python

[IN: 5]
df = df.sort_values(["customer_id", "product_id", "date"]).copy()
series_keys = ["customer_id", "product_id"]
df["lag_1"] = df.groupby(series_keys)["order_qty"].shift(1)
df["lag_7"] = df.groupby(series_keys)["order_qty"].shift(7)
sample = df.query("customer_id == 'C05' and product_id == 'P05'").tail(12)
display(sample[["date", "order_qty", "lag_1", "lag_7"]])
plt.plot(sample["date"], sample["order_qty"], marker="o", label="actual")
plt.plot(sample["date"], sample["lag_7"], marker="s", label="lag 7")
plt.title("Actual orders and 7-day lag")
plt.xlabel("Date")
plt.ylabel("Order quantity")
plt.grid(alpha=0.3)
plt.legend()
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()
[OUT: 5]
date order_qty lag_1 lag_7
21424 2025-06-19 86 94.0 80.0
21464 2025-06-20 81 86.0 61.0
21504 2025-06-21 11 81.0 15.0
21544 2025-06-22 12 11.0 15.0
21584 2025-06-23 95 12.0 71.0
21624 2025-06-24 89 95.0 89.0
21664 2025-06-25 103 89.0 94.0
21704 2025-06-26 100 103.0 86.0
21744 2025-06-27 94 100.0 81.0
21784 2025-06-28 19 94.0 11.0
21824 2025-06-29 16 19.0 12.0
21864 2025-06-30 105 16.0 95.0

No.053: Creating Rug Features

Interpreting the results

The seven-day lag reflects the previous occurrence of the same weekday. Missing lags at the start of each series mean insufficient history, not zero demand. Exclude those rows or use an explicit missing-history rule.

No.054: Creating Moving Average Features

Practical purpose

Orders on a single day fluctuate by chance. Moving averages stabilize baseline demand and support decisions regarding safety stock and capacity planning.

Method

A past-only moving average is MAt,w=1w∑i=1wyt−iMA_{t,w}=\frac{1}{w}\sum_{i=1}^{w}y_{t-i}. Use shift(1).rolling(w) to exclude the current day. The code permits partial windows through min_periods; for those initial windows, divide by the available count rather than the nominal width.

Check with Python

[IN: 6]
g = df.groupby(series_keys)["order_qty"]
df["rolling_mean_7"] = g.transform(
    lambda s: s.shift(1).rolling(7, min_periods=3).mean()
)
df["rolling_mean_28"] = g.transform(
    lambda s: s.shift(1).rolling(28, min_periods=7).mean()
)
sample = df.query("customer_id == 'C05' and product_id == 'P05'").tail(60)
plt.plot(sample["date"], sample["order_qty"], alpha=0.45, label="actual")
plt.plot(sample["date"], sample["rolling_mean_7"], label="7-day mean")
plt.plot(sample["date"], sample["rolling_mean_28"], label="28-day mean")
plt.title("Short- and medium-term demand baselines")
plt.xlabel("Date")
plt.ylabel("Order quantity")
plt.grid(alpha=0.3)
plt.legend()
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()
[OUT: 6]

No.054: Creating Moving Average Features

Interpreting the results

The 7-day average reacts more quickly to recent changes than the 28-day average. Choose and validate the window against the decision horizon, such as short-term staffing or monthly purchasing.

No.055: Creating Customer-Specific Aggregated Features

Practical purpose

Order sizes and variability vary by customer. Historical averages and variance can be used to forecast the load of key customers and design forecast intervals.

Method

Aggregate demand by customer and date, then compute an expanding mean from earlier dates only. Do not attach a full-period customer mean to historical prediction rows.

Check with Python

[IN: 7]
customer_daily = df.groupby(["date", "customer_id"], as_index=False)["order_qty"].sum()
customer_daily = customer_daily.sort_values(["customer_id", "date"])
customer_daily["customer_past_mean"] = customer_daily.groupby("customer_id")[
    "order_qty"
].transform(lambda s: s.shift(1).expanding().mean())
customer_profile = customer_daily.groupby("customer_id").agg(
    latest_past_mean=("customer_past_mean", "last"), observed_std=("order_qty", "std")
)
display(customer_profile.round(2).sort_values("latest_past_mean", ascending=False))
customer_profile["latest_past_mean"].sort_values().plot(kind="barh", color="#ED7D31")
plt.title("Historical demand level by customer")
plt.xlabel("Past mean daily quantity")
plt.ylabel("Customer")
plt.grid(axis="x", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 7]
latest_past_mean observed_std
customer_id
C05 206.99 115.22
C08 184.89 102.48
C04 171.93 95.56
C07 158.00 87.48
C03 144.15 79.93
C02 122.89 68.19
C06 116.22 64.75
C01 102.44 57.00

No.055: Creating Customer-Specific Aggregated Features

Interpreting the results

Customer C05 has a relatively high historical demand level. The displayed observed_std describes the full period and is not a prediction-time feature. If variability or days since the last order is used for prediction, calculate it only from information available at that date.

No.056: Creating Product-Specific Aggregated Features

Practical purpose

Demand levels and variability differ by product. Historical product summaries can inform material planning; a numeric product identifier alone does not express those differences.

Method

Aggregate demand by product and date, then calculate a cumulative mean using earlier dates only. For new products, consider a product-family average when sufficient product history is unavailable.

Check with Python

[IN: 8]
product_daily = df.groupby(["date", "product_id"], as_index=False)["order_qty"].sum()
product_daily = product_daily.sort_values(["product_id", "date"])
product_daily["product_past_mean"] = product_daily.groupby("product_id")[
    "order_qty"
].transform(lambda s: s.shift(1).expanding().mean())
product_profile = product_daily.groupby("product_id").agg(
    latest_past_mean=("product_past_mean", "last"), max_daily=("order_qty", "max")
)
display(product_profile.round(2))
product_profile["latest_past_mean"].plot(kind="bar", color="#5B9BD5")
plt.title("Historical demand level by product")
plt.xlabel("Product")
plt.ylabel("Past mean daily quantity")
plt.grid(axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 8]
latest_past_mean max_daily
product_id
P01 124.02 228
P02 172.20 318
P03 235.02 428
P04 296.70 555
P05 379.57 672

No.056: Creating Product-Specific Aggregated Features

Interpreting the results

Product P05 has higher historical demand than P01. The table’s max_daily summarizes the full period and must not be attached to earlier rows as a feature. Reconsider how much weight to give old data after discontinuations or price changes.

No.057: Creating Ratio Features

Practical purpose

You cannot judge whether the quantity is heavy relative to its capability based on absolute quantity. Load rates and customer composition ratios can be compared using common metrics to show congestion and importance.

Method

Use rt=MAt,7/ctr_t=MA_{t,7}/c_t: past seven-day mean demand divided by the capacity allocated to the same customer–product pair. Treat a zero or unknown denominator as missing. This is a historical load ratio, not a forecast of today’s demand or a factory-wide utilization measure.

Check with Python

[IN: 9]
df["demand_capacity_ratio"] = df["rolling_mean_7"].div(
    df["capacity_qty"].replace(0, np.nan)
)
ratio_summary = df.groupby("product_id")["demand_capacity_ratio"].agg(
    ["mean", "median", "max"]
)
display(ratio_summary.round(3))
plot_data = df.dropna(subset=["demand_capacity_ratio"]).sample(2500, random_state=SEED)
plt.hist(
    plot_data["demand_capacity_ratio"], bins=30, color="#FFC000", edgecolor="white"
)
plt.axvline(1.0, color="red", linestyle="--", label="capacity threshold")
plt.title("Distribution of expected load ratio")
plt.xlabel("7-day mean / standard capacity")
plt.ylabel("Frequency")
plt.grid(axis="y", alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 9]
mean median max
product_id
P01 0.298 0.291 0.585
P02 0.371 0.362 0.687
P03 0.433 0.422 0.845
P04 0.476 0.462 0.842
P05 0.528 0.514 0.941

No.057: Creating Ratio Features

Interpreting the results

A ratio above 1 means that past average demand exceeds the allocated capacity. Use the comparison to identify items for capacity review, while checking that numerator and denominator refer to the same unit and allocation period.

No.058: Creating Interaction Features

Practical purpose

A promotion may have a different effect at month-end or for a particular product. Interaction features let a model represent these combinations explicitly.

Method

For two variables x1x_1 and x2x_2, add their product x1x2x_1x_2. Here, promotion × month_end represents promotions at month-end, and business_day × lag_7 combines the business-day flag with demand on the same weekday last week.

Check with Python

[IN: 10]
df["is_month_end"] = (df["date"].dt.day >= 25).astype(int)
df["promotion_month_end"] = df["promotion"] * df["is_month_end"]
df["business_lag_7"] = df["is_business_day"] * df["lag_7"]
interaction_summary = (
    df.groupby(["promotion", "is_month_end"])["order_qty"].mean().unstack()
)
interaction_summary.columns = ["not_month_end", "month_end"]
display(interaction_summary.round(2))
interaction_summary.plot(kind="bar", color=["#A5A5A5", "#C00000"])
plt.title("Interaction of promotion and month-end")
plt.xlabel("Promotion flag")
plt.ylabel("Average order quantity")
plt.grid(axis="y", alpha=0.3)
plt.legend()
plt.tight_layout()
plt.show()
[OUT: 10]
not_month_end month_end
promotion
0 28.57 34.89
1 36.13 41.03

No.058: Creating Interaction Features

Interpreting the results

The largest group mean occurs when both promotion and month-end flags are set. This agrees with the synthetic data design but does not establish a causal promotion effect. Test a small set of operationally motivated interactions to limit overfitting.

No.059: Using Target Encoding

Practical purpose

If there are many categories such as customers, products, or facilities, One-Hot Encoding increases the number of columns. You can summarize categories into a single column at the level of past objective variables.

Method

The smoothed encoding is TEc=(ncyˉc+mμ)/(nc+m)TE_c=(n_c\bar y_c+m\mu)/(n_c+m). Compute category totals and the global prior using dates strictly before the prediction date. Exclude outcomes from other customer–product rows on the same day too. The smoothing parameter mm pulls sparse categories toward the historical global mean.

Check with Python

[IN: 11]
df = df.sort_values("date").copy()
cat_key = df["customer_id"] + "_" + df["product_id"]
past_sum = df.groupby(cat_key)["order_qty"].cumsum() - df["order_qty"]
past_count = df.groupby(cat_key).cumcount()
# Shift daily totals so no outcome from the prediction date enters the prior.
daily_totals = df.groupby("date")["order_qty"].agg(["sum", "count"]).sort_index()
prior_sum = daily_totals["sum"].cumsum().shift(1)
prior_count = daily_totals["count"].cumsum().shift(1)
prior_by_date = prior_sum / prior_count
global_prior = df["date"].map(prior_by_date)
smoothing = 30
df["target_encoding"] = (past_sum + smoothing * global_prior) / (past_count + smoothing)
te_summary = (
    df.groupby(["customer_id", "product_id"])["target_encoding"].last().unstack()
)
display(te_summary.round(2))
plt.imshow(te_summary, aspect="auto", cmap="Blues")
plt.colorbar(label="Past target mean")
plt.xticks(range(len(te_summary.columns)), te_summary.columns)
plt.yticks(range(len(te_summary.index)), te_summary.index)
plt.title("Leakage-safe target encoding")
plt.xlabel("Product")
plt.ylabel("Customer")
plt.grid(False)
plt.tight_layout()
plt.show()
[OUT: 11]
product_id P01 P02 P03 P04 P05
customer_id
C01 11.62 15.37 20.65 25.38 31.95
C02 13.37 17.92 24.23 30.20 38.64
C03 15.59 21.16 28.28 34.99 44.49
C04 18.31 25.00 33.46 41.62 52.44
C05 21.55 29.66 39.95 49.88 63.02
C06 12.86 17.41 22.76 28.40 36.60
C07 17.20 22.92 30.61 38.53 48.38
C08 19.65 26.36 35.42 44.82 56.87

No.059: Using Target Encoding

Interpreting the results

The encoding summarizes historical customer–product demand in one column. A new category can fall back to the historical global mean once earlier data exist; the first date remains missing because there is no history. For time series, ordinary random out-of-fold encoding is insufficient if it draws on future dates.

No.060: Preventing Data Leaks

Practical purpose

Even if verification accuracy is high, if unknown information is used at the time of production, it cannot be used for planning. Leak prevention is a quality requirement that predates algorithm selection.

Method

Fit the model on dates before the cutoff and evaluate later dates. leaky_target is the same-day target accidentally retained as an input; safe_roll is a shifted past-only mean. The valid example is daily rolling one-step prediction, with new actual observations becoming available each day, not a single forecast for the entire test period.

Check with Python

[IN: 12]
daily = df.groupby("date", as_index=False)["order_qty"].sum().sort_values("date")
daily["leaky_target"] = daily[
    "order_qty"
]  # Unknown at the time of prediction. Typical leaks for explanation
daily["safe_roll"] = daily["order_qty"].shift(1).rolling(7, min_periods=7).mean()
daily = daily.dropna().copy()
cutoff = pd.Timestamp("2025-04-01")
train = daily[daily["date"] < cutoff]
test = daily[daily["date"] >= cutoff]

results = []
predictions = {}
for feature in ["leaky_target", "safe_roll"]:
    model = RandomForestRegressor(
        n_estimators=150, min_samples_leaf=4, random_state=SEED, n_jobs=1
    )
    model.fit(train[[feature]], train["order_qty"])
    pred = model.predict(test[[feature]])
    predictions[feature] = pred
    results.append(
        {"feature": feature, "MAE": mean_absolute_error(test["order_qty"], pred)}
    )
display(pd.DataFrame(results).set_index("feature").round(2))
view = test.iloc[:45]
plt.plot(view["date"], view["order_qty"], label="actual", color="black")
plt.plot(view["date"], predictions["leaky_target"][:45], label="leaky feature")
plt.plot(view["date"], predictions["safe_roll"][:45], label="safe feature")
plt.title("Apparent accuracy caused by target leakage")
plt.xlabel("Date")
plt.ylabel("Total order quantity")
plt.grid(alpha=0.3)
plt.legend()
plt.xticks(rotation=30)
plt.tight_layout()
plt.show()
[OUT: 12]
MAE
feature
leaky_target 3.34
safe_roll 613.13

No.060: Preventing Data Leaks

Interpreting the results

Including the target itself produces an unrealistically low MAE, but that feature cannot exist at prediction time. Record event time, finalization time, and availability time for every input. Validate chronologically and use the same feature-generation code during training and prediction.

What the results mean in practice

Calendar features describe operating cycles; lags and moving averages summarize past demand. Customer and product aggregates capture demand levels, while ratios and interactions represent capacity comparisons and combinations of conditions.

First establish which information is available, then align the forecast horizon and aggregation level with the planning decision. Evaluate additional features using both forecast errors and operational measures such as shortages, overtime, inventory, and plan changes.

Requirements for deployment

  1. Prediction Specifications: Define the target, granularity, forecast date, forecast period, and plan finalization time
  2. Data time management: Manage the occurrence, confirmation, and acquisition times for each item, as well as correction rules.
  3. feature ledger: Definition, Units, Window Width, missing-value rules, and responsible owners
  4. reproducible processing: Use the same code for learning and inference to save historical snapshots
  5. Timeline Verification: Evaluate MAE and operational KPIs across multiple periods, including busy and holiday seasons.
  6. Monitoring and Updates: Monitor distribution changes due to new products, customer composition, capabilities, and calendar changes

Conclusion

No.051–060 convert raw dates and order histories into meaningful features for manufacturing planning. The key is to use information available at prediction time. Future calendar dates and confirmed promotion schedules are allowed; future actual demand is not. If you want to start small, start with business days, 7-day lag, 7-day moving averages, and historical averages by customer and product, and verify their effectiveness through time series verification.

Consulting for businesses

In demand forecasting and inventory and production planning, data definition, features, validation, and on-site operations connections determine outcomes more than the model itself. At Surikobo, we support you with everything from problem organization, data diagnosis, PoC, business implementation, to corporate training, tailored to your data and decision-making process.

📩 Contact Us: www.surikobo.co.jp/contact Please feel free to consult us first.