· Charlotte Will · Amazon API · 8 min read
Real-Time Inventory Updates with Machine Learning and Amazon MWS API
Discover how real-time inventory updates with machine learning and Amazon MWS API can revolutionize your ecommerce business. Learn advanced techniques, benefits, and step-by-step guides to optimizing inventory management for improved customer satisfaction and operational efficiency.

Introduction
Real-time inventory work gets sold as a data problem. It is not. The hard part is deciding what to reorder before you sell out, which needs a forecast you trust.
Amazon’s Marketplace Web Service (MWS) API used to be how you pulled those numbers. Amazon ended MWS support on April 1, 2024, so the workflow below runs on the Selling Partner API (SP-API).
Here is the pipeline: pull inventory, build features, forecast, flag anomalies, then turn it into a PO.
What replaced MWS
Amazon launched SP-API in 2020 and announced the MWS end of life in July 2022, giving developers a phased migration through the end of 2023. The last MWS sections stopped responding on April 1, 2024. Old credentials are dead.
SP-API replaced it. Requests carry an AWS SigV4 signature built from your IAM credentials, every call names a marketplace, and quotas are tracked per operation. The order flow in How to Integrate Amazon MWS API for Order Management holds.
| Old MWS operation | SP-API equivalent |
|---|---|
GetInventorySummariesReport | getInventorySummaries on /fba/inventory/v1/summaries |
GetOrders | getOrders on /orders/v0/orders |
GetReport flat files | Reports API createReport and getReport |
The flat-file report has no successor. It becomes a JSON call.
Pulling FBA inventory from SP-API
SP-API does not hand you a spreadsheet. The FBA Inventory endpoint returns a payload keyed by granularity, and each item carries fulfillable, reserved, and inbound counts.
import time
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.session import get_session
MARKETPLACE_ID = 'ATVPDKIKX0DER'
def sp_api_get(path, params=None):
params = dict(params or {}, marketplaceIds=MARKETPLACE_ID)
request = AWSRequest(method='GET',
url=f'https://sellingpartnerapi-na.amazon.com{path}',
params=params)
SigV4Auth(get_session().get_credentials(), 'execute-api',
'us-east-1').add_auth(request)
response = requests.request(request.method, request.url,
headers=dict(request.headers.items()),
timeout=30)
if response.status_code == 429:
time.sleep(float(response.headers.get('Retry-After', 5)))
return sp_api_get(path, params)
response.raise_for_status()
return response.json()
def fetch_fba_inventory(seller_skus=None):
params = {'granularityType': 'Marketplace', 'granularityId': MARKETPLACE_ID}
payload = sp_api_get('/fba/inventory/v1/summaries', params)
return [{'sku': i['sellerSku'],
'fulfillable': int(i.get('fulfillableQuantity', 0)),
'inbound': int(i.get('inboundWorkingQuantity', 0)),
'total': int(i.get('totalQuantity', 0))}
for g in payload.get('granularitySummaries', [])
for i in g.get('granularitySummaryData', [])]
Two details matter. The Retry-After loop is not optional, since inventory calls run against a tight quota. And fulfillableQuantity is sellable, totalQuantity counts damaged units.
Building the training data
A forecast needs a table, not a stream: one row per SKU per day, with what you sold and what you had on hand. The Orders API omits line items, so pull orders, then items.
import time
from collections import defaultdict
from datetime import datetime, timedelta, timezone
def pull_order_history(days=180, seller_sku=None):
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
cursor, units_by_day = None, defaultdict(int)
while True:
params = {'CreatedAfter': cutoff.strftime('%Y-%m-%dT%H:%M:%SZ'),
'MarketplaceIds': MARKETPLACE_ID,
'OrderStatuses': 'Shipped', 'MaxResultsPerPage': 50}
if cursor:
params['NextToken'] = cursor
payload = sp_api_get('/orders/v0/orders', params).get('payload', {})
for order in payload.get('Orders', []):
items = sp_api_get(
f"/orders/v0/orders/{order['AmazonOrderId']}/orderItems")
for item in items.get('payload', {}).get('OrderItems', []):
if seller_sku and item.get('SellerSKU') != seller_sku:
continue
units_by_day[order['PurchaseDate'][:10]] += int(
item.get('QuantityOrdered', 0))
cursor = payload.get('NextToken')
if not cursor:
break
time.sleep(0.5)
return dict(units_by_day)
One call per order is the expensive part, so caching item lookups keeps you inside the quota. The fulfillment side sits in How to Automate Fulfillment Processes Using Amazon Selling Partner API.
Now assemble features. The shift inside the rolling window matters: velocity_7 uses the previous seven days, not the current one, since at forecast time you do not know what sold today. A feature that leaks future sales gives a model that looks fine in backtest and misses live.
import numpy as np
import pandas as pd
def assemble_features(history):
"""history: sku, date, units_sold, on_hand, promo."""
frame = history.copy()
frame['date'] = pd.to_datetime(frame['date'])
frame = frame.sort_values(['sku', 'date'])
grouped = frame.groupby('sku')['units_sold']
frame['velocity_7'] = grouped.transform(
lambda s: s.shift(1).rolling(7, min_periods=3).mean())
frame['velocity_28'] = grouped.transform(
lambda s: s.shift(1).rolling(28, min_periods=14).mean())
frame['dow'] = frame['date'].dt.dayofweek
frame['month'] = frame['date'].dt.month
frame['is_promo'] = frame.get(
'promo', pd.Series(0, index=frame.index)).astype(int)
frame['dow_mean'] = frame.groupby(['sku', 'dow'])['units_sold'].transform(
lambda s: s.shift(1).rolling(8, min_periods=4).mean())
frame['seasonal_index'] = (
frame['dow_mean'] / frame['velocity_28'].replace(0, np.nan))
frame['days_of_cover'] = (
frame['on_hand'] / frame['velocity_7'].clip(lower=0.1))
frame['target_units_7d'] = grouped.transform(
lambda s: s.shift(-7).rolling(7, min_periods=7).sum())
return frame.dropna(subset=['velocity_7', 'target_units_7d'])
days_of_cover is what operations reads. It answers how long you have left.
Forecasting demand
Start simple. A moving average and an exponential smoothing in plain numpy take five minutes to write and give you a number you can explain to a buyer. If they beat a boosting model, use those.
import numpy as np
def moving_average_forecast(history, window=14, horizon=7):
values = np.asarray(history, dtype=float)
if values.size < window:
return np.repeat(values[-1] if values.size else 0.0, horizon)
return np.repeat(values[-window:].mean(), horizon)
def exponential_smoothing(history, alpha=0.3, horizon=7):
values = np.asarray(history, dtype=float)
if values.size == 0:
return np.zeros(horizon)
level = float(values[0])
for value in values[1:]:
level = alpha * float(value) + (1 - alpha) * level
return np.repeat(level, horizon)
Exponential smoothing gives a flat level. On weekly traffic, a baseline repeating last week wins.
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import TimeSeriesSplit
FEATURES = ['velocity_7', 'velocity_28', 'dow_mean', 'seasonal_index',
'dow', 'month', 'is_promo', 'days_of_cover']
def train_demand_model(frame, features=FEATURES, target='target_units_7d'):
model = HistGradientBoostingRegressor(max_depth=6, learning_rate=0.05,
max_iter=400, l2_regularization=1.0, random_state=7)
splitter = TimeSeriesSplit(n_splits=4)
errors = []
for train_idx, valid_idx in splitter.split(frame):
model.fit(frame.iloc[train_idx][features], frame.iloc[train_idx][target])
predicted = model.predict(frame.iloc[valid_idx][features])
errors.append(mean_absolute_error(frame.iloc[valid_idx][target], predicted))
model.fit(frame[features], frame[target])
return model, float(np.mean(errors))
TimeSeriesSplit matters more than the hyperparameters. A random split trains on next week’s sales to predict this week’s, and the score means nothing. Rolling-origin splits respect order.
Flagging strange stock movements
Stock counts move for reasons unrelated to demand. A shipment arrives late, a listing gets suppressed, a transfer lands on the wrong day. Forecasts trained on raw counts absorb those shocks and predict them. A z-score catches the obvious ones, Isolation Forest the subtler ones.
import numpy as np
from sklearn.ensemble import IsolationForest
def zscore_flags(values, threshold=3.0):
values = np.asarray(values, dtype=float)
spread = values.std(ddof=0)
if spread == 0:
return np.zeros(values.shape, dtype=bool)
return np.abs(values - values.mean()) > threshold * spread
def daily_movement_flags(daily_frame, sku, threshold=3.0):
series = daily_frame[daily_frame['sku'] == sku].sort_values('date')
delta = series['on_hand'].diff().fillna(0.0)
return zscore_flags(delta.to_numpy(), threshold=threshold)
def isolation_forest_flags(feature_frame, contamination=0.01):
model = IsolationForest(n_estimators=200, contamination=contamination,
random_state=11)
return model.fit_predict(feature_frame) == -1
Run the flags before you trust the model. A SKU flagged three days running gets its window trimmed or its rows dropped, so one bad shipment does not rewrite a quarter.
Turning a forecast into a purchase order
A forecast becomes useful when it turns into a quantity. The standard form is a reorder point: expected demand over lead time plus a safety buffer sized from the variance.
import numpy as np
LEAD_TIME_DAYS, SAFETY_DAYS, MAX_STOCK_DAYS = 21, 5, 60
def reorder_plan(sku, on_hand, inbound, daily_forecast, unit_cost, case_pack=24):
forecast = np.asarray(daily_forecast, dtype=float)
if forecast.size == 0:
return {'sku': sku, 'reorder': False, 'qty': 0}
safety_stock = float(forecast.std(ddof=0)) * np.sqrt(SAFETY_DAYS)
reorder_point = float(forecast[:LEAD_TIME_DAYS].sum()) + safety_stock
projected = on_hand + inbound
if projected >= reorder_point:
return {'sku': sku, 'reorder': False, 'qty': 0}
deficit = max(float(forecast.mean()), 0.01) * MAX_STOCK_DAYS - projected
units = int(np.ceil(deficit / case_pack) * case_pack)
return {'sku': sku, 'reorder': True, 'qty': units,
'reorder_point': round(reorder_point, 1),
'unit_cost': round(units * unit_cost, 2)}
Case packs and lead times make this real. A supplier shipping in 21 days needs a different reorder point than one shipping overnight, and ordering in cases of 24 means rounding up. How to Automate Inventory Management with Amazon MWS API covers purchase order automation, and Advanced Techniques for Inventory Tracking Using Amazon MWS API covers reconciling against Amazon’s counts.
Where machine learning earns its keep
A catalogue of twenty SKUs does not need gradient boosting. A moving average and a reorder point will beat a poorly fed model, and often a well fed one, so the effort is not repaid.
Machine learning starts paying where traffic has structure a fixed rule cannot capture. High velocity SKUs with weekday peaks are the clearest case. Seasonality that shifts year to year is another, since a hand-tuned factor gets rewritten each quarter.
Backtest before you deploy. Hold out the most recent weeks, forecast them with the pipeline you intend to run in production, and compare against a moving average baseline. If the model cannot beat that on your catalogue, you have added a dependency and a monitoring burden for nothing. Watch stale features, since an unrefreshed table means old data.
Conclusion
The MWS API is gone, and the workflow that used to sit on top of it now runs on SP-API with SigV4 signing and per-operation quotas. Pull inventory and order history, assemble features that respect the order of time, forecast with plain exponential smoothing until the data proves you need more, then order.
Where the machine learning goes is your call, and it should be a measured one. Backtest against a moving average, keep the baseline as fallback, and remember that a small catalogue gains nothing from complexity it cannot feed.
FAQs
Is the Amazon MWS API still available? No. Amazon announced the MWS end of life in July 2022 and stopped serving the last sections on April 1, 2024. New work targets SP-API.
What SP-API endpoint replaces an MWS inventory report? The FBA Inventory API.
getInventorySummarieson/fba/inventory/v1/summariesreturns per-SKU quantities, the closest thing to MWS’s flat-file report.Do I need machine learning for a small catalogue? Usually not. A moving average forecast plus a reorder point formula is simpler and often just as accurate for a handful of SKUs. Machine learning earns its cost on high-velocity items.
How do I detect unusual inventory movements? Track the daily change in on-hand stock per SKU and flag anything beyond three standard deviations with a z-score. When the pattern spreads across features, an isolation forest catches it too.
How often should a demand forecasting model be retrained? Often enough that its features are fresh. High-velocity SKUs want daily refreshes, slower sellers weekly. Keep a build timestamp on every feature row, since a stale table degrades forecasts.


