All articles →

100 Exercises / Machine Learning / Practical Machine Learning 100 Exercises

Time Series Forecasting in Python: From Demand Analysis to Stock Planning

Analyze demand and validate forecasts over time in Python, then make seven-day recursive forecasts to compare shortages, surplus, and safety stock.

Use daily order and shipment records for the fictional pump component PX-100 to study production and stock planning. The exercises cover aggregation, trend and seasonality, forecasting, chronological validation, error analysis, and a comparison of required stock.

[!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

Demand forecasts inform material orders, staffing, production sequencing, and finished-goods stock. Overprediction can tie up working capital; underprediction can cause shortages and late deliveries. This article connects forecast errors to the quantity needed over the following seven days.

Common situations on site

  • They only look at monthly totals and cannot grasp the impact of weekday differences or holidays.
  • Although high accuracy was achieved through random splitting, it was not reproduced in actual operation.
  • The average error is small, but it can be significantly off during important periods such as promotions and holidays
  • Although forecasts were made, there were no rules to convert them into safety stock or ordering points.

Why is this issue so difficult to judge?

Demand can combine trends, recurring patterns, and one-off events. Features must respect what was known when a forecast was made. Forecast errors also have different consequences: shortages and surplus do not have equal costs.

Exercises in this article

No.ThemeConnecting to decision-making
061Daily Sales VisualizationGrasping fluctuation and abnormal periods
062Weekly and monthly aggregationChoosing time units for capacity and purchasing plans
063moving averageSeparating the trend from short-term noise
064Seasonal Trends by Day of the Week and MonthAnticipating recurring peaks and troughs
065Lag featuresDemand forecasting using recent performance
066Regression ModelForecasting that integrates multiple factors
067Time-based validationPerformance Evaluation Close to Production
068Visualization of Prediction ErrorsUnderstanding Biases and Variation
069Analysis of the Missed PeriodIdentification of Improvement Targets and Exceptions
070Connecting to Inventory and Order PlanningBalancing service standards and inventory costs

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.

Handle data with pandas and numpy, visualize it with matplotlib, and build and evaluate models with scikit-learn. Random number seeds are fixed to 42. To avoid garbled characters caused by the execution environment, graphs are presented in English, and reading is explained in detail in the main text.

[IN: 1]
from IPython.display import display

import warnings

warnings.filterwarnings("ignore", category=FutureWarning)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.model_selection import TimeSeriesSplit

SEED = 42
rng = np.random.default_rng(SEED)
pd.set_option("display.max_columns", 20)
plt.rcParams["figure.figsize"] = (11, 4)
print("Libraries loaded. Random seed:", SEED)
[OUT: 1]
Libraries loaded. Random seed: 42

Creating the synthetic data

Generate 730 daily observations from January 1, 2024 to December 30, 2025. demand_units represents observed order or shipment quantity, while sales_yen is its monetary value. A supply constraint deliberately reduces observed quantity in April 2025, so the target is not unconstrained latent demand. Other effects include growth, weekdays, month, promotions, summer shutdowns, and a year-end rush.

The synthetic daily quantity yty_t follows the additive model below.

yt=Tt+Wt+St+18Pt+Et+εt,εt∼N(0,52)y_t = T_t + W_t + S_t + 18P_t + E_t + \varepsilon_t, \qquad \varepsilon_t \sim \mathcal{N}(0, 5^2)

TtT_t is the trend, WtW_t is the day-of-the-week effect, StS_t is the monthly effect, PtP_t is the promotional flag, and EtE_t is the temporary factor. In practice, it is important to note that treating shipment performance without including backlogs or lost orders as “demand” underestimates the potential demand during supply constraint periods.

Show setup code (run this cell)
[IN: 2]
dates = pd.date_range("2024-01-01", periods=730, freq="D")
n = len(dates)
weekday_effect = np.array([8, 10, 9, 7, 4, -16, -20])
month_effect = {
    1: -5,
    2: -2,
    3: 8,
    4: 3,
    5: -1,
    6: 5,
    7: 7,
    8: -10,
    9: 6,
    10: 4,
    11: 9,
    12: 13,
}

df = pd.DataFrame({"date": dates})
df["weekday"] = df["date"].dt.dayofweek
df["month"] = df["date"].dt.month
df["promotion"] = (
    (df["date"].dt.day >= 10)
    & (df["date"].dt.day <= 12)
    & (df["month"].isin([3, 6, 9, 11]))
).astype(int)
trend = np.linspace(0, 16, n)
season = df["month"].map(month_effect).to_numpy()
special = np.zeros(n)
special[(df["date"].dt.month == 8) & (df["date"].dt.day.between(11, 16))] -= 30
special[(df["date"].dt.month == 12) & (df["date"].dt.day.between(16, 22))] += 22
supply_constraint = df["date"].between("2025-04-07", "2025-04-18")
special[supply_constraint] -= 24

latent = (
    72
    + trend
    + weekday_effect[df["weekday"].to_numpy()]
    + season
    + 18 * df["promotion"].to_numpy()
    + special
    + rng.normal(0, 5, n)
)
df["demand_units"] = np.maximum(0, np.rint(latent)).astype(int)
df["unit_price_yen"] = 12500
df["sales_yen"] = df["demand_units"] * df["unit_price_yen"]
df["special_period"] = np.select(
    [
        supply_constraint,
        (df["date"].dt.month == 8) & (df["date"].dt.day.between(11, 16)),
        (df["date"].dt.month == 12) & (df["date"].dt.day.between(16, 22)),
    ],
    ["supply_constraint", "summer_shutdown", "year_end_rush"],
    default="normal",
)

print(
    f"Period: {df['date'].min().date()} to {df['date'].max().date()} / {len(df):,} days"
)
display(df.head())
display(df[["demand_units", "sales_yen"]].describe().round(1))
[OUT: 2]
Period: 2024-01-01 to 2025-12-30 / 730 days
date weekday month promotion demand_units unit_price_yen sales_yen special_period
0 2024-01-01 0 1 0 77 12500 962500 normal
1 2024-01-02 1 1 0 72 12500 900000 normal
2 2024-01-03 2 1 0 80 12500 1000000 normal
3 2024-01-04 3 1 0 79 12500 987500 normal
4 2024-01-05 4 1 0 61 12500 762500 normal
demand_units sales_yen
count 730.0 730.0
mean 83.3 1041061.6
std 17.7 221419.6
min 11.0 137500.0
25% 72.0 900000.0
50% 84.0 1050000.0
75% 95.0 1187500.0
max 136.0 1700000.0

No.061: Visualize daily sales

Practical purpose

Daily trends are a starting point for checking short-term fluctuations that disappear from aggregates, business calendars, and sudden troughs. In manufacturing sites, it is important to record not only sales amounts but also quantities to avoid confusing price revisions with changes in quantity.

Method

The unit price is fixed at ¥12,500, so revenue and quantity have the same shape over time. Plot quantity here to make comparisons with stock planning easier. Check zeros, abrupt shifts, and unusual periods before deciding which patterns a model should learn.

Check with Python

[IN: 3]
fig, ax = plt.subplots()
ax.plot(df["date"], df["demand_units"], color="steelblue", linewidth=0.9)
ax.set_title("Daily Demand for PX-100")
ax.set_xlabel("Date")
ax.set_ylabel("Demand (units/day)")
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
print("Peak day:")
display(
    df.nlargest(3, "demand_units")[
        ["date", "demand_units", "promotion", "special_period"]
    ]
)
[OUT: 3]

No.061: Visualize daily sales

Peak day:
date demand_units promotion special_period
721 2025-12-22 136 0 year_end_rush
717 2025-12-18 133 0 year_end_rush
351 2024-12-17 129 0 year_end_rush

Interpreting the results

In addition to the regular weekend dip, there are peaks before promotions and year-end sales, and troughs during summer holidays and supply constraints. Therefore, it is inappropriate to determine daily production volume based solely on a simple full-period average. By cross-checking the background information of peak days in a table, you can distinguish whether the event is reproduced or transient.

No.062: Aggregating weekly and monthly sales

Practical purpose

The level of granularity required varies depending on the decision: daily on-site staffing, weekly material ordering, and monthly S&OP and budgeting. By distinguishing between total quantity and average daily sales, you can prevent misreading due to differences in the number of days in a month.

Method

Aggregate Monday–Sunday weeks with a Sunday date label and calendar months with a month-start label. Compare totals with daily averages. The final week contains only December 29–30, and the final month has 30 observed days; their totals are incomplete.

Check with Python

[IN: 4]
ts = df.set_index("date")
weekly = ts["demand_units"].resample("W-SUN").sum().rename("weekly_units")
monthly = ts["demand_units"].resample("MS").agg(["sum", "mean"])
monthly.columns = ["monthly_units", "avg_daily_units"]
display(monthly.tail(8).round(1))

fig, axes = plt.subplots(2, 1, figsize=(11, 7))
axes[0].plot(weekly.index, weekly, color="darkorange")
axes[0].set_title("Weekly Demand")
axes[0].set_xlabel("Week ending")
axes[0].set_ylabel("Demand (units/week)")
axes[0].grid(True, alpha=0.3)
axes[1].bar(monthly.index, monthly["monthly_units"], width=20, color="slateblue")
axes[1].set_title("Monthly Demand")
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Demand (units/month)")
axes[1].grid(True, axis="y", alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 4]
monthly_units avg_daily_units
date
2025-05-01 2519 81.3
2025-06-01 2702 90.1
2025-07-01 2864 92.4
2025-08-01 2091 67.5
2025-09-01 2810 93.7
2025-10-01 2802 90.4
2025-11-01 2901 96.7
2025-12-01 3161 105.4

No.062: Aggregating weekly and monthly sales

Interpreting the results

While the week’s operating days and event effects remain, the monthly trend shows gradual growth and makes it easier to read the variations from month to month. Even when signing purchase contracts on a monthly basis, it is necessary to check not only the monthly total but also the weekly peak, and consider delivery frequency and storage capacity.

Practical purpose

Frequently changing production plans in response to daily noise leads to more rescheduling and overtime. Moving averages are simple management indicators that smooth out short-term fluctuations and share a common pattern.

Method

The trailing kk-day moving average is

MAt(k)=1k∑i=0k−1yt−iMA_t^{(k)}=\frac{1}{k}\sum_{i=0}^{k-1}y_{t-i}

The 7-day average smooths out the weekly cycle, while the 28-day average represents a medium-term trend. However, moving averages respond to changes later and are distinguished from the actual forecast value.

Check with Python

[IN: 5]
df["ma_7"] = df["demand_units"].rolling(7).mean()
df["ma_28"] = df["demand_units"].rolling(28).mean()
view = df.tail(240)
fig, ax = plt.subplots()
ax.plot(
    view["date"], view["demand_units"], color="lightgray", label="Daily", linewidth=0.8
)
ax.plot(view["date"], view["ma_7"], label="7-day MA", linewidth=1.5)
ax.plot(view["date"], view["ma_28"], label="28-day MA", linewidth=2)
ax.set_title("Demand Trend with Moving Averages")
ax.set_xlabel("Date")
ax.set_ylabel("Demand (units/day)")
ax.grid(True, alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
print("Latest moving averages:")
latest_ma = df[["date", "demand_units", "ma_7", "ma_28"]].tail(5).copy()
latest_ma[["ma_7", "ma_28"]] = latest_ma[["ma_7", "ma_28"]].round(1)
display(latest_ma)
[OUT: 5]

No.063: Seeing Trends with Moving Averages

Latest moving averages:
date demand_units ma_7 ma_28
725 2025-12-26 112 108.0 104.8
726 2025-12-27 86 105.7 105.1
727 2025-12-28 85 103.3 105.5
728 2025-12-29 103 98.6 105.1
729 2025-12-30 105 99.4 104.9

Interpreting the results

The 7-day average captures recent changes in supply and demand, while the 28-day average shows a stable trend. When the gap between the two widens, it signals a change in demand levels or a temporary event. Window widths are set according to procurement lead times and plan review cycles.

No.064: Viewing Seasonality by Day of the Week and Month

Practical purpose

Day-of-week differences relate to daily delivery and shipping schedules, while monthly differences relate to regular maintenance, budget fulfillment, and seasonal demand. By incorporating recurring patterns in advance, you can reduce the waste that is treated as an “anomaly” each time.

Method

Divide the average values by day and month by the overall average to check the seasonal index. If the index is 1.10, the demand level is about 10% higher than average. Since the composition changes from year to year, we also check whether it remains stable over multiple years.

Check with Python

[IN: 6]
weekday_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
overall_mean = df["demand_units"].mean()
weekday_profile = df.groupby("weekday")["demand_units"].mean().reindex(range(7))
weekday_profile.index = weekday_names
month_profile = df.groupby("month")["demand_units"].mean().reindex(range(1, 13))
seasonality = pd.DataFrame(
    {"weekday_avg": weekday_profile, "weekday_index": weekday_profile / overall_mean}
)
display(seasonality.round(2))

fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].bar(weekday_profile.index, weekday_profile.values, color="teal")
axes[0].set_title("Average Demand by Weekday")
axes[0].set_xlabel("Weekday")
axes[0].set_ylabel("Average demand (units/day)")
axes[0].grid(True, axis="y", alpha=0.3)
axes[1].plot(month_profile.index, month_profile.values, marker="o", color="crimson")
axes[1].set_title("Average Demand by Month")
axes[1].set_xlabel("Month")
axes[1].set_ylabel("Average demand (units/day)")
axes[1].set_xticks(range(1, 13))
axes[1].grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
[OUT: 6]
weekday_avg weekday_index
Mon 91.85 1.10
Tue 93.90 1.13
Wed 91.88 1.10
Thu 89.88 1.08
Fri 85.79 1.03
Sat 66.80 0.80
Sun 62.72 0.75

No.064: Viewing Seasonality by Day of the Week and Month

Interpreting the results

Weekday demand is higher than weekend demand, with higher averages early in the week. Monthly averages show a year-end rise and an August dip. Use these patterns when reviewing capacity, while checking how promotions and other events affect the averages.

No.065: Forecasting Demand with Lag Features

Practical purpose

Recent observations and the same weekday in earlier weeks provide practical reference points. Lag features turn these comparisons into reproducible model inputs.

Method

An LL-day lag is xt(L)=yt−Lx_t^{(L)}=y_{t-L}. Use lags of 1, 7, 14, and 28 days. Apply shift so the current outcome is excluded. The seasonal naive baseline predicts the same quantity as seven days earlier.

Check with Python

[IN: 7]
for lag in [1, 7, 14, 28]:
    df[f"lag_{lag}"] = df["demand_units"].shift(lag)
df["rolling_7_past"] = df["demand_units"].shift(1).rolling(7).mean()

lag_data = df.dropna(
    subset=["lag_1", "lag_7", "lag_14", "lag_28", "rolling_7_past"]
).copy()
cutoff = pd.Timestamp("2025-09-01")
lag_test = lag_data[lag_data["date"] >= cutoff].copy()
lag_test["naive_pred"] = lag_test["lag_7"]
naive_mae = mean_absolute_error(lag_test["demand_units"], lag_test["naive_pred"])
naive_rmse = mean_squared_error(lag_test["demand_units"], lag_test["naive_pred"]) ** 0.5
print(f"Seasonal naive (lag 7) MAE: {naive_mae:.2f} units")
print(f"Seasonal naive (lag 7) RMSE: {naive_rmse:.2f} units")
display(
    lag_test[
        ["date", "demand_units", "lag_1", "lag_7", "rolling_7_past", "naive_pred"]
    ].head()
)
[OUT: 7]
Seasonal naive (lag 7) MAE: 9.92 units
Seasonal naive (lag 7) RMSE: 12.72 units
date demand_units lag_1 lag_7 rolling_7_past naive_pred
609 2025-09-01 102 47.0 90.0 75.714286 90.0
610 2025-09-02 96 102.0 82.0 77.428571 82.0
611 2025-09-03 102 96.0 81.0 79.428571 81.0
612 2025-09-04 91 102.0 85.0 82.428571 85.0
613 2025-09-05 98 91.0 83.0 83.285714 83.0

Interpreting the results

The seven-day seasonal naive forecast captures weekday patterns and provides a useful baseline. RMSE is always at least MAE; a large gap is a reason to inspect large individual errors. These are daily forecasts updated with previous actual demand, not a forecast of the whole test period made at its start.

No.066: Time Series Prediction Using Regression Models

Practical purpose

Demand is determined not only by recent performance but also by multiple factors such as the day of the week, month, promotions, and trends. The regression model integrates these and quantifies next-day demand.

Method

Use time-based cross-validation within the training period to select between linear regression and a random forest. Then evaluate all fixed candidates on the period from September 2025 onward. Inputs include observations available through the previous day and a promotion schedule assumed to be known in advance.

Check with Python

[IN: 8]
feature_cols = [
    "lag_1",
    "lag_7",
    "lag_14",
    "lag_28",
    "rolling_7_past",
    "weekday",
    "month",
    "promotion",
]
model_data = lag_data.copy()
train = model_data[model_data["date"] < cutoff]
test = model_data[model_data["date"] >= cutoff].copy()
X_train, y_train = train[feature_cols], train["demand_units"]
X_test, y_test = test[feature_cols], test["demand_units"]

models = {
    "LinearRegression": LinearRegression(),
    "RandomForest": RandomForestRegressor(
        n_estimators=250, max_depth=8, min_samples_leaf=4, random_state=SEED, n_jobs=-1
    ),
}
from sklearn.model_selection import cross_val_score

selection_cv = TimeSeriesSplit(n_splits=5, test_size=60)
selection_mae = {
    name: -cross_val_score(
        model, X_train, y_train, cv=selection_cv, scoring="neg_mean_absolute_error"
    ).mean()
    for name, model in models.items()
}
best_name = min(selection_mae, key=selection_mae.get)
display(pd.Series(selection_mae, name="training_cv_MAE").to_frame().round(2))

rows = []
for name, model in models.items():
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    rows.append(
        {
            "model": name,
            "MAE": mean_absolute_error(y_test, pred),
            "RMSE": mean_squared_error(y_test, pred) ** 0.5,
        }
    )
    test[f"pred_{name}"] = pred
comparison = pd.DataFrame(rows).set_index("model")
comparison.loc["SeasonalNaive"] = [naive_mae, naive_rmse]
display(comparison.sort_values("MAE").round(2))

best_model = models[best_name]
test["prediction"] = test[f"pred_{best_name}"]
print("Selected regression model:", best_name)
[OUT: 8]
training_cv_MAE
LinearRegression 6.73
RandomForest 7.39
MAE RMSE
model
RandomForest 6.17 8.29
LinearRegression 6.96 8.78
SeasonalNaive 9.92 12.72
Selected regression model: LinearRegression

Interpreting the results

Compare each candidate with the seasonal naive baseline. The model used below is selected by training-period cross-validation MAE, not by test MAE. Small gains may not justify additional maintenance and retraining costs.

No.067: Learning How to Verify Time Series Data

Practical purpose

A single test period may have coincided with a specific season. By verifying multiple past points in time and learning only from data up to that point and predicting what happens next, we estimate performance fluctuations during operation.

Method

Run expanding-window validation within the training period only. Record each fold’s MAE, RMSE, and daily residuals. The residuals will support a rough safety-stock estimate; these model-selection scores are not final test performance.

Check with Python

[IN: 9]
tscv = TimeSeriesSplit(n_splits=5, test_size=60)
from sklearn.base import clone

cv_rows = []
cv_residuals = []
X_all, y_all = X_train, y_train
for fold, (tr_idx, va_idx) in enumerate(tscv.split(X_all), start=1):
    fold_model = clone(models[best_name])
    fold_model.fit(X_all.iloc[tr_idx], y_all.iloc[tr_idx])
    fold_pred = fold_model.predict(X_all.iloc[va_idx])
    cv_residuals.extend(y_all.iloc[va_idx].to_numpy() - fold_pred)
    cv_rows.append(
        {
            "fold": fold,
            "train_end": train.iloc[tr_idx[-1]]["date"].date(),
            "valid_start": train.iloc[va_idx[0]]["date"].date(),
            "valid_end": train.iloc[va_idx[-1]]["date"].date(),
            "MAE": mean_absolute_error(y_all.iloc[va_idx], fold_pred),
            "RMSE": mean_squared_error(y_all.iloc[va_idx], fold_pred) ** 0.5,
        }
    )
cv_results = pd.DataFrame(cv_rows)
display(cv_results.round(2))
print(
    f"CV MAE mean: {cv_results['MAE'].mean():.2f}, worst: {cv_results['MAE'].max():.2f}"
)
[OUT: 9]
fold train_end valid_start valid_end MAE RMSE
0 1 2024-11-04 2024-11-05 2025-01-03 7.40 9.35
1 2 2025-01-03 2025-01-04 2025-03-04 5.95 7.36
2 3 2025-03-04 2025-03-05 2025-05-03 6.48 9.20
3 4 2025-05-03 2025-05-04 2025-07-02 5.93 7.16
4 5 2025-07-02 2025-07-03 2025-08-31 7.87 10.40
CV MAE mean: 6.73, worst: 7.87

Interpreting the results

The error difference between folds indicates that model performance depends on seasonal and event configuration. We do not promise stable management based solely on average MAE; we share worst-case values and variations with stakeholders. When the data structure changes, fixed-length learning windows are also compared.

No.068: Visualizing Prediction Errors

Practical purpose

With just the overall score, you can’t see the bias between overestimating and underestimating, or when the predictions are seriously off. By visualizing errors, you can determine whether order volumes should be continuously increased or decreased, or if exception management is necessary.

Method

Define residuals as et=yt−y^te_t=y_t-\hat y_t; positive values mean underprediction. Plot actual and predicted demand, daily residual bars, and summary statistics to locate persistent bias and large errors.

Check with Python

[IN: 10]
test["residual"] = test["demand_units"] - test["prediction"]
test["abs_error"] = test["residual"].abs()
fig, axes = plt.subplots(2, 1, figsize=(11, 7))
axes[0].plot(test["date"], test["demand_units"], label="Actual", color="black")
axes[0].plot(test["date"], test["prediction"], label="Predicted", color="royalblue")
axes[0].set_title("Actual vs Predicted Demand")
axes[0].set_xlabel("Date")
axes[0].set_ylabel("Demand (units/day)")
axes[0].grid(True, alpha=0.3)
axes[0].legend()
axes[1].bar(
    test["date"],
    test["residual"],
    color=np.where(test["residual"] >= 0, "tomato", "steelblue"),
)
axes[1].axhline(0, color="black", linewidth=0.8)
axes[1].set_title("Forecast Residuals (Actual - Predicted)")
axes[1].set_xlabel("Date")
axes[1].set_ylabel("Residual (units)")
axes[1].grid(True, axis="y", alpha=0.3)
plt.tight_layout()
plt.show()

display(test["residual"].describe(percentiles=[0.1, 0.5, 0.9]).to_frame().round(2))
[OUT: 10]

No.068: Visualizing Prediction Errors

residual
count 121.00
mean 1.97
std 8.59
min -31.24
10% -7.98
50% 2.18
90% 13.41
max 23.58

Interpreting the results

Check whether the forecasts follow normal daily patterns and where large errors occur. A residual mean near zero can still conceal a long positive tail and shortage risk. Stock planning needs the distribution of total errors over the lead time, not just average daily error.

No.069: Analyzing the Period When Predictions Fall Short

Practical purpose

Large errors may coincide with promotions, shutdowns, supply constraints, or incorrect master data. Match high-error dates to recorded events to decide whether features, rules, data, or a manual exception process need attention.

Method

The top 10% of absolute error is designated as the “review required date,” and MAE and the number of cases are aggregated by period segment. Thresholds are not for statistical convenience, but are ultimately determined based on operational criteria such as allowable shortages and express costs.

Check with Python

[IN: 11]
review_threshold = test["abs_error"].quantile(0.90)
test["review_flag"] = test["abs_error"] >= review_threshold
worst_days = test.nlargest(10, "abs_error")[
    [
        "date",
        "demand_units",
        "prediction",
        "residual",
        "abs_error",
        "promotion",
        "special_period",
    ]
]
worst_days_display = worst_days.copy()
worst_days_display[["prediction", "residual", "abs_error"]] = worst_days_display[
    ["prediction", "residual", "abs_error"]
].round(1)
display(worst_days_display)

period_error = (
    test.groupby("special_period")
    .agg(
        days=("date", "size"),
        MAE=("abs_error", "mean"),
        review_days=("review_flag", "sum"),
    )
    .sort_values("MAE", ascending=False)
)
display(period_error.round(2))
print(f"Review threshold (90th percentile): {review_threshold:.2f} units")
[OUT: 11]
date demand_units prediction residual abs_error promotion special_period
722 2025-12-23 99 130.2 -31.2 31.2 0 normal
717 2025-12-18 133 109.4 23.6 23.6 0 year_end_rush
609 2025-09-01 102 80.7 21.3 21.3 0 normal
676 2025-11-07 112 91.2 20.8 20.8 0 normal
721 2025-12-22 136 118.7 17.3 17.3 0 year_end_rush
613 2025-09-05 98 81.6 16.4 16.4 0 normal
630 2025-09-22 108 91.6 16.4 16.4 0 normal
700 2025-12-01 114 98.1 15.9 15.9 0 normal
715 2025-12-16 127 111.3 15.7 15.7 0 year_end_rush
718 2025-12-19 125 109.6 15.4 15.4 0 year_end_rush
days MAE review_days
special_period
year_end_rush 7 13.95 5
normal 114 6.53 8
Review threshold (90th percentile): 13.83 units

Interpreting the results

By looking at the event column for the review date, you can distinguish between recurring factors to be absorbed for model improvement and contingency factors that people should judge as exceptions. Since shipment performance under supply constraints does not represent latent demand, integration with out-of-stock and backlog data is necessary before model adjustments. The top margin of error table can also be used for retrospective meetings in sales, production, and purchasing.

No.070: Linking Demand Forecasting to Inventory and Order Planning

Practical purpose

Translate forecasts into a required-stock comparison, then compare the forecast method with a past-28-day-average baseline. This exercise does not simulate a continuous inventory balance or a fixed order quantity.

Method

At the start of decision day tt, estimate the quantity needed from that day through the next six days:

ROPt=∑h=0L−1y^t+h∣t−1+SS,SS=zσeL.ROP_t=\sum_{h=0}^{L-1}\hat y_{t+h\mid t-1}+SS,\qquad SS=z\sigma_e\sqrt L.

Use L=7L=7, z=1.65z=1.65, and daily residual standard deviation from training-period time-based validation. Recursively append predicted values to the history when forecasting later days; do not use their actual demand. The square-root rule assumes uncorrelated errors with constant variance. Recursive forecast errors may violate that approximation, so this does not guarantee a 95% service level.

Check with Python

[IN: 12]
lead_time = 7
z = 1.65
residual_std = np.std(cv_residuals, ddof=1)
safety_stock = z * residual_std * np.sqrt(lead_time)


# Update future lags with predictions; use future actuals only for evaluation.
def recursive_forecast(fitted_model, history, future_calendar):
    values = list(np.asarray(history, dtype=float))
    forecasts = []
    for day in future_calendar.itertuples():
        row = {f"lag_{lag}": values[-lag] for lag in [1, 7, 14, 28]}
        row.update(
            rolling_7_past=np.mean(values[-7:]),
            weekday=day.weekday,
            month=day.month,
            promotion=day.promotion,
        )
        prediction = max(
            0.0, float(fitted_model.predict(pd.DataFrame([row])[feature_cols])[0])
        )
        forecasts.append(prediction)
        values.append(prediction)
    return np.asarray(forecasts)


plan_rows = []
for date in test["date"].iloc[: -(lead_time - 1)]:
    history = df.loc[df["date"] < date, "demand_units"]
    future = df.loc[df["date"] >= date].head(lead_time)
    future_calendar = future[["weekday", "month", "promotion"]]
    forecasts = recursive_forecast(best_model, history, future_calendar)
    plan_rows.append(
        {
            "date": date,
            "actual_lead_demand": future["demand_units"].sum(),
            "forecast_lead_demand": forecasts.sum(),
            "fixed_lead_demand": history.tail(28).mean() * lead_time,
        }
    )
plan = pd.DataFrame(plan_rows)

for policy, expected in [
    ("Forecast", "forecast_lead_demand"),
    ("FixedAverage", "fixed_lead_demand"),
]:
    plan[f"stock_{policy}"] = plan[expected] + safety_stock
    plan[f"shortage_{policy}"] = (
        plan["actual_lead_demand"] - plan[f"stock_{policy}"]
    ).clip(lower=0)
    plan[f"surplus_{policy}"] = (
        plan[f"stock_{policy}"] - plan["actual_lead_demand"]
    ).clip(lower=0)

policy_results = pd.DataFrame(
    {
        "policy": ["Forecast", "FixedAverage"],
        "service_level_pct": [
            100 * (plan["shortage_Forecast"] == 0).mean(),
            100 * (plan["shortage_FixedAverage"] == 0).mean(),
        ],
        "avg_shortage_units": [
            plan["shortage_Forecast"].mean(),
            plan["shortage_FixedAverage"].mean(),
        ],
        "avg_surplus_units": [
            plan["surplus_Forecast"].mean(),
            plan["surplus_FixedAverage"].mean(),
        ],
    }
)
print(f"Safety stock: {safety_stock:.1f} units (z={z}, lead time={lead_time} days)")
display(policy_results.set_index("policy").round(2))

fig, ax = plt.subplots(figsize=(8, 4))
x = np.arange(len(policy_results))
ax.bar(x - 0.18, policy_results["avg_shortage_units"], 0.36, label="Shortage")
ax.bar(x + 0.18, policy_results["avg_surplus_units"], 0.36, label="Surplus")
ax.set_title("Inventory Policy Comparison")
ax.set_xlabel("Policy")
ax.set_ylabel("Average units per decision")
ax.set_xticks(x, policy_results["policy"])
ax.grid(True, axis="y", alpha=0.3)
ax.legend()
plt.tight_layout()
plt.show()
[OUT: 12]
Safety stock: 38.3 units (z=1.65, lead time=7 days)
service_level_pct avg_shortage_units avg_surplus_units
policy
Forecast 69.57 9.57 24.09
FixedAverage 65.22 23.91 27.27

No.070: Linking Demand Forecasting to Inventory and Order Planning

Interpreting the results

Compare the fraction of decision windows with no shortage, average shortage, and average surplus. The seven-day windows overlap, so they are not statistically independent observations. This compares stock requirements at each decision date; a full inventory simulation also needs on-hand stock, outstanding orders, lead times, order intervals, and lot constraints.

What the results mean in practice

  1. Aligning granularity with decision-making: Daily, weekly, and monthly are not superior or inferior; their uses differ.
  2. Setting a Reference Model: Advanced models that do not exceed the performance of one week ago do not justify the operating costs.
  3. Respect time order: Random splits and features containing future outcomes can make validation more optimistic than deployment.
  4. Don’t just look at average accuracy: The period of missed and the direction of error determine the risk of out-of-stock items.
  5. Connect metrics to operations: Connect from MAE to service levels, surplus, and express costs to make investment decisions.

Requirements for deployment

  • Standardize the definitions and granularity of orders, shipments, stockouts, lost orders, inventory, promotions, and business calendars
  • Set a forecast reference date and save only the data available at that time
  • Design forecast periods, update frequency, and evaluation metrics based on SKU characteristics and lead times
  • Monitor for accuracy degradation, missing measurements, and abnormal values, and record the reasons for personnel overwriting
  • Verify ordering rules including out-of-stock costs, storage costs, disposal costs, minimum lot sizes, and capacity constraints.
  • Compare the pilot with existing planning practices and define ownership, review procedures, and ongoing support.

Conclusion

No.061–No.070 connected daily observations, aggregation, seasonality, lag features, regression, chronological validation, and error analysis to a stock-requirement comparison. Start with a small set of SKUs, retain a simple baseline, and assess shortages and surplus alongside forecast accuracy.

Consulting for businesses

At Surikobo, we support everything from problem organization to PoC and operational design in manufacturing related to demand forecasting, inventory optimization, production planning, data infrastructure development, and in-house training. You can consult with us from the stage where you may feel like “We have data but it doesn’t lead to ordering decisions” or “We want to design evaluation indicators that can be used on site.”

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