Knowledge Base
Supply Chain Knowledge Base
An evergreen reference for planners, operations leaders, and anyone building supply chain software.
Formulas with worked examples, KPI definitions, starter Python and SQL, a glossary, and links to authoritative sources. It’s general education, not legal, customs, tax, or financial advice.

AI-Assisted Software Development for Supply Chain
How I build supply chain software in Python and SQL with AI assistants, and the guardrails I follow. For the longer story, read How I Use AI to Build Supply Chain Software.
Tools and roles
| Tool | How I use it |
|---|---|
| Cursor | AI-assisted code editor; suggestions with the project’s files and tests in context |
| Claude, ChatGPT | Design discussions, data models, edge cases, code review and explanations |
| Grok, Gemini | Independent cross-checks of important answers, code and logic |
Workflow
- State the business rule in plain English.
- Define inputs, outputs, units and grain (for example item × location × day).
- Generate one small piece at a time: a function, a query or a test.
- Review every line against the formula or rule.
- Test against hand-calculated examples and reconcile totals to the source system.
- Commit small changes to version control with clear messages.
Prompt patterns
- Context: language, libraries, data grain and units.
- Constraints: allowed libraries, error handling, no hard-coded paths or secrets.
- Examples: a few synthetic input rows and the exact expected output.
- Explain first: ask for assumptions and approach before code.
- Critique: ask a second model to review for join fan-out, NULLs, date boundaries and unit errors.
Testing and validation
- Turn worked examples (like the safety stock examples below) into automated tests.
- Cover edge cases: no history, intermittent demand, zero or negative on-hand, unit-of-measure conversions.
- Check row counts before and after every SQL join.
- No output reaches a decision-maker until it matches a known answer.
Guardrails and data security
- No confidential, proprietary or export-controlled data in prompts; use synthetic or anonymized samples.
- Follow the client’s or employer’s AI policy first; where tools are approved, review data-use and retention settings.
- Keep credentials in environment variables or a secrets manager, never in prompts or repositories.
- People make the decisions; software recommends.
- Reference frameworks: the NIST AI Risk Management Framework and the NIST Privacy Framework.
Demand Forecasting
A forecast estimates future demand so the business can plan capacity, materials and inventory. Forecast true demand (orders), not just shipments, which understate demand during stockouts.
Components of a demand series
- Level, trend, seasonality and noise (random variation).
Common methods
- Naive and seasonal naive: benchmarks every model should beat.
- Moving average: mean of the last n periods.
- Simple exponential smoothing:
Ft+1 = α × At + (1 − α) × Ft, with 0 < α < 1
- Holt-Winters: exponential smoothing with trend and seasonality.
- Regression / machine learning: adds drivers such as price, promotions or economic indicators.
Accuracy and bias metrics
| Metric | Formula | Notes |
|---|---|---|
| MAE | average of abs(A − F) | In units; easy to interpret |
| MAPE | average of abs(A − F) / A | Undefined when A = 0; unstable for low volumes |
| WAPE | Σ abs(A − F) / Σ A | Volume-weighted; good for portfolios |
| Bias | average of (F − A) | Positive = over-forecast; negative = under-forecast |
Worked example: actuals 100, 120, 80; forecasts 110, 110, 100. MAE = 13.3 units; WAPE = 40 / 300 = 13.3%; MAPE = 14.4%; bias = +6.7 units.
Good practice
- Plot the data before modeling; flag outliers and one-time events.
- Forecast at the level where decisions are made; aggregate forecasts tend to be more accurate.
- Track forecast value added: does each manual adjustment improve accuracy?
Sales & Operations Planning (S&OP)
Sales and operations planning is a monthly, cross-functional process that produces one agreed plan balancing demand, supply and financials, usually by product family over roughly an 18–24 month horizon.
The monthly cycle
- Data gathering: close the month, refresh actuals and the statistical forecast.
- Demand review: agree an unconstrained demand plan and its assumptions.
- Supply review: test demand against capacity, materials and suppliers; propose options.
- Pre-S&OP (reconciliation): resolve conflicts, price scenarios, frame decisions; finance included.
- Executive S&OP: leadership decides trade-offs and approves the plan.
Core metrics
- Forecast accuracy and bias, OTIF, inventory and days on hand versus target, capacity utilization, supplier on-time delivery, plan versus budget.
Pitfalls
- No decisions at the executive meeting; finance absent; SKU-level detail; skipped months; no owners for actions.
Read more: S&OP in Plain English.
Inventory Optimization
Inventory policy balances service against the cost of holding stock. The formulas below are standard textbook models; they assume roughly normal demand and independent demand and lead time.
Key formulas
Reorder point: ROP = d̄ × L + SS
Safety stock (demand variability): SS = z × σd × √L
Safety stock (demand and lead-time variability): SS = z × √(L × σd² + d̄² × σL²)
Economic order quantity: EOQ = √(2DS / H)
Where d̄ = average daily demand; σd = standard deviation of daily demand; L = lead time (days); σL = standard deviation of lead time (days); z = service factor; D = annual demand (units); S = cost per order; H = annual holding cost per unit.
Service factor (z) for common cycle service levels
| Cycle service level | z |
|---|---|
| 90% | 1.282 |
| 95% | 1.645 |
| 97.5% | 1.960 |
| 98% | 2.054 |
| 99% | 2.326 |
Worked example A: demand variability only
d̄ = 40 units/day, σd = 12, L = 9 days, 95% service (z = 1.645).
- SS = 1.645 × 12 × √9 = 59.2 → 60 units (rounded up)
- ROP = 40 × 9 + 60 = 420 units
Worked example B: add lead-time variability
Same item with σL = 2 days.
- √(9 × 12² + 40² × 2²) = √(1,296 + 6,400) = √7,696 ≈ 87.7
- SS = 1.645 × 87.7 ≈ 144.3 → 145 units
- ROP = 360 + 145 = 505 units
Worked example C: EOQ
D = 12,000 units/year, S = $75 per order, H = $4 per unit per year.
- EOQ = √(2 × 12,000 × 75 / 4) = √450,000 ≈ 671 units
Practical notes
- Keep time units consistent (daily demand with lead time in days).
- Cycle service level is not the same as fill rate.
- Intermittent or lumpy demand often violates the normal assumption.
- Segment items (ABC/XYZ) and set service targets by segment.
Read more: Safety Stock and Reorder Points: A Practical Guide.
Supplier Risk, Tariffs & Reshoring
General framework only. Nothing here is legal, customs or tax advice. Confirm classification, country of origin and duty treatment with a licensed customs broker or qualified trade counsel.
A seven-part framework
- Visibility: map part → supplier → manufacturing site → country of origin, beyond tier 1 where possible.
- Classification and origin: confirm with your broker using the Harmonized Tariff Schedule (USITC) and CBP rulings.
- Exposure sizing: exposure ($) = annual import value × scenario incremental duty rate; run several scenarios.
- Concentration: flag single-source, sole-source, long-lead and qualification-heavy parts.
- Alternatives: second sources, other countries, domestic suppliers, design or material changes, with qualification time noted.
- Total cost of ownership: compare unit price plus freight, duty, carrying cost, quality and risk; see the Reshoring Initiative Total Cost of Ownership Estimator.
- Governance: review exposure and actions monthly in S&OP, with owners and dates.
Other supplier risk signals
- Financial health, capacity constraints and quality trends.
- Geographic concentration and logistics chokepoints.
- On-time delivery and lead-time variability (they drive safety stock).
- Export-control and compliance requirements, especially in defense and aerospace (see the Bureau of Industry and Security).
Official sources to monitor
- USTR Section 301 investigations
- CBP: Basic Importing and Exporting
- International Trade Administration
- U.S. Census Bureau foreign trade data
Read more: Tariff Exposure: A Supplier Risk Checklist for Manufacturers.
Supply Chain KPIs
| KPI | Definition / formula |
|---|---|
| OTIF | Share of orders delivered on time and in full ÷ total orders |
| Fill rate | Units (or lines) shipped from stock on first attempt ÷ units (or lines) ordered |
| Perfect order rate | Orders on time, complete, damage-free and correctly documented ÷ total orders |
| Inventory turns | Cost of goods sold ÷ average inventory value |
| Days of inventory on hand (DIO) | Average inventory value ÷ COGS × 365 |
| Cash-to-cash cycle | DIO + DSO (days sales outstanding) − DPO (days payables outstanding) |
| Forecast accuracy | Often 1 − WAPE, by family and horizon |
| Forecast bias | Average of (forecast − actual) |
| Supplier on-time delivery | Receipts on or before promised date ÷ total receipts |
| OEE | Availability × Performance × Quality |
Examples: COGS of $6,000,000 and average inventory of $1,500,000 give 4.0 turns and about 91 days on hand (365 ÷ 4). OEE with 90% availability, 95% performance and 98% quality = 0.90 × 0.95 × 0.98 ≈ 83.8%.
Define each KPI once, write the definition down, and keep it stable so trends mean something.
Python & SQL Starter Snippets
Short, tested starting points. Table and column names are illustrative; adapt them to your schema.
Python: safety stock and reorder point
from math import sqrt
from statistics import NormalDist
def safety_stock(service_level, sd_demand, lead_time, avg_demand=0.0, sd_lead_time=0.0):
z = NormalDist().inv_cdf(service_level)
return z * sqrt(lead_time * sd_demand**2 + (avg_demand * sd_lead_time)**2)
ss = safety_stock(0.95, 12, 9) # about 59.2
rop = 40 * 9 + ss # about 419.2
Python (pandas): forecast accuracy and exponential smoothing
import pandas as pd
df = pd.DataFrame({"actual": [100, 120, 80], "forecast": [110, 110, 100]})
err = df["forecast"] - df["actual"]
mae = err.abs().mean() # 13.33
wape = err.abs().sum() / df["actual"].sum() # 0.1333
bias = err.mean() # 6.67
demand = pd.Series([100, 120, 90, 110])
level = demand.ewm(alpha=0.3, adjust=False).mean()
next_forecast = level.iloc[-1] # 103.84
SQL: inventory turns and days on hand by item
WITH cogs AS (
SELECT item_id, SUM(cogs_amount) AS annual_cogs
FROM sales
WHERE sale_date >= DATE '2025-01-01' AND sale_date < DATE '2026-01-01'
GROUP BY item_id
),
inv AS (
SELECT item_id, AVG(on_hand_value) AS avg_inventory_value
FROM inventory_snapshots
WHERE snapshot_date >= DATE '2025-01-01' AND snapshot_date < DATE '2026-01-01'
GROUP BY item_id
)
SELECT c.item_id,
c.annual_cogs / NULLIF(i.avg_inventory_value, 0) AS inventory_turns,
365.0 * i.avg_inventory_value / NULLIF(c.annual_cogs, 0) AS days_on_hand
FROM cogs c
JOIN inv i ON i.item_id = c.item_id
ORDER BY inventory_turns;
Aggregating each table in its own CTE before joining avoids join fan-out.
SQL: ABC classification by annual usage value
WITH usage AS (
SELECT item_id, SUM(quantity * unit_cost) AS annual_value
FROM consumption
WHERE txn_date >= DATE '2025-01-01' AND txn_date < DATE '2026-01-01'
GROUP BY item_id
),
ranked AS (
SELECT item_id, annual_value,
SUM(annual_value) OVER (ORDER BY annual_value DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
/ SUM(annual_value) OVER () AS cum_share
FROM usage
)
SELECT item_id, annual_value,
CASE WHEN cum_share <= 0.80 THEN 'A'
WHEN cum_share <= 0.95 THEN 'B'
ELSE 'C' END AS abc_class
FROM ranked
ORDER BY annual_value DESC;
The 80% / 95% cut-offs are a common convention, not a rule; choose thresholds that fit your business.
SQL: supplier on-time delivery rate
SELECT supplier_id,
AVG(CASE WHEN received_date <= promised_date THEN 1.0 ELSE 0.0 END) AS on_time_rate,
COUNT(*) AS receipts
FROM purchase_order_receipts
GROUP BY supplier_id
ORDER BY on_time_rate;
Glossary (A–Z)
38 supply chain, planning, trade and AI terms, A–Z.
- ABC analysis: Ranking items by annual usage value (or another measure) into A, B and C classes so attention and service targets match importance.
- Backorder: Customer demand that could not be filled from stock and will be shipped later.
- Bill of materials (BOM): The structured list of components, sub-assemblies and quantities needed to make a product.
- Bullwhip effect: The amplification of order variability as demand signals move upstream from customers to suppliers.
- Capacity planning: Matching the resources (labor, equipment, suppliers) needed to meet the demand plan.
- Country of origin: The country where a good was produced or substantially transformed, as determined under applicable customs rules.
- Cycle service level: The probability of not stocking out during a replenishment cycle; the basis of the z-factor safety stock formula.
- Days of inventory on hand (DIO): Average inventory value divided by cost of goods sold, times 365.
- Demand planning: The process of forecasting demand and agreeing an unconstrained demand plan.
- Economic order quantity (EOQ): The order quantity that minimizes total ordering and holding cost: √(2DS/H).
- Fill rate: The share of demand (units or lines) shipped from stock on the first attempt.
- Forecast bias: A consistent tendency to over- or under-forecast, measured as the average of forecast minus actual.
- Harmonized Tariff Schedule (HTS): The U.S. classification system, published by the USITC, used to determine duty rates for imported goods.
- Incoterms®: ICC rules defining buyer and seller responsibilities for delivery, risk and costs in trade contracts.
- Inventory turns: Cost of goods sold divided by average inventory value.
- Just-in-time (JIT): A production approach that aims to receive and make items only as needed, minimizing inventory.
- Kanban: A visual pull signal (card, bin or electronic) that authorizes replenishment.
- Lead time: The time between placing an order (or starting a process) and the item being available for use.
- Master production schedule (MPS): The item-level plan of what to produce, in what quantity and when.
- Material requirements planning (MRP): A system that calculates component requirements and timing from the MPS, BOM and inventory.
- Mean absolute percentage error (MAPE): The average of absolute errors divided by actuals; undefined when actuals are zero.
- Nearshoring: Moving production or sourcing to a nearby country.
- On time in full (OTIF): The share of orders delivered on the promised date and in the full quantity.
- Overall equipment effectiveness (OEE): Availability × Performance × Quality for a machine or line.
- Prompt engineering: Structuring instructions, context and examples so an AI model produces useful, accurate output.
- Quality at source: Building inspection and responsibility for quality into each process step rather than end-of-line checks.
- Reorder point (ROP): The inventory position that triggers a replenishment order: d̄ × L + SS.
- Reshoring: Returning production or sourcing to the home country.
- Safety stock: Extra inventory held to buffer demand and supply variability during lead time.
- Sales and operations planning (S&OP): A monthly cross-functional process that produces one agreed plan for demand, supply and finance.
- Stock-keeping unit (SKU): A unique identifier for a distinct item, often by item and location.
- Tariff: A tax or duty imposed on imported (or occasionally exported) goods.
- Total cost of ownership (TCO): The full cost of a sourcing option, including price, freight, duty, inventory, quality and risk.
- Uncertainty (demand/supply): Variability that cannot be forecast; quantified by standard deviation and buffered by safety stock or capacity.
- Vendor-managed inventory (VMI): An arrangement where the supplier monitors and replenishes the customer’s inventory.
- Weighted absolute percentage error (WAPE): Sum of absolute errors divided by sum of actuals; a volume-weighted accuracy metric.
- XYZ analysis: Classifying items by demand variability (X = stable, Z = highly variable), often combined with ABC.
- z-score (service factor): The number of standard deviations of protection that corresponds to a target cycle service level.
Frequently Asked Questions
What is the difference between safety stock and the reorder point?
Safety stock is the buffer held for variability. The reorder point is the inventory level that triggers an order, equal to average demand during lead time plus safety stock.
Which service level should I use for safety stock?
It is a business decision. Higher service levels need disproportionately more inventory, so set targets by item segment, such as higher for critical A items and lower for C items.
Is MAPE or WAPE better for measuring forecast accuracy?
WAPE is usually more stable across a portfolio because it weights errors by volume and handles low-volume items better. MAPE is easy to explain but is undefined when actual demand is zero.
How often should an S&OP cycle run?
Most organizations run S&OP monthly, with a demand review, supply review, reconciliation and an executive meeting each cycle.
How do I estimate tariff exposure for a part?
A simple planning estimate is annual import value multiplied by a scenario incremental duty rate. Confirm classification, origin and actual duty treatment with a licensed customs broker; this is not legal or customs advice.
Can AI write production supply chain software?
AI assistants can speed up drafting code, but the output must be reviewed line by line, tested against known answers and governed by data-security rules. People remain responsible for decisions.
Should confidential supply chain data go into AI tools?
Not without approval. Follow your organization’s policy, use synthetic or anonymized samples for prompts, and review each tool’s data-use and retention settings.
Where can I learn supply chain planning formally?
Professional bodies such as ASCM (CPIM and CSCP programs) and ISM (CPSM) offer recognized certifications, and university centers such as MIT CTL publish research and courses.
Further Reading
Authoritative sources only: professional bodies, universities, official government sites and primary documentation.
Professional bodies and research
- ASCM: Association for Supply Chain Management: CPIM and CSCP certifications, standards and the SCOR model.
- Institute for Supply Management (ISM): Procurement and supply management certification and research.
- ISM PMI® Reports: Monthly manufacturing and services indexes.
- MIT Center for Transportation & Logistics: Supply chain research and education.
Forecasting and data
- Forecasting: Principles and Practice (3rd ed.): Free online textbook by Hyndman and Athanasopoulos.
- statsmodels: Time Series Analysis: Python exponential smoothing, ARIMA and more.
- pandas documentation: Python data analysis library.
- Python statistics module: Includes NormalDist for service-level z values.
- Census M3: Manufacturers’ Shipments, Inventories, and Orders: Monthly U.S. manufacturing data.
Trade, tariffs and sourcing (official sources)
- Harmonized Tariff Schedule (USITC): Official U.S. tariff classification and rates.
- CBP: Basic Importing and Exporting: Import process fundamentals.
- CBP Rulings: Classification and origin rulings.
- USTR: Section 301 Investigations: Official Section 301 actions and notices.
- International Trade Administration: Market and trade resources from the U.S. Department of Commerce.
- Bureau of Industry and Security: U.S. export controls.
- U.S. Census Bureau: International Trade: Official import and export statistics.
- ICC Incoterms® rules: Delivery terms used in trade contracts.
- Reshoring Initiative TCO Estimator: Free total-cost-of-ownership tool for sourcing decisions.
AI governance and data security
- NIST AI Risk Management Framework: Voluntary framework for managing AI risks.
- NIST Privacy Framework: Managing privacy risk in systems and data.
Maintained by Peter Klausz, MBA, founder of Statadventure, LLC and former Pratt & Whitney F100 supply chain manager. I’m open to contracting (consulting and contract engagements) and new full-time roles in supply chain, data/BI, operations, and AI/automation, especially with defense, aerospace, and Boston-area employers. Get in touch.