| name | inventory-optimization |
| description | When the user wants to optimize inventory levels, calculate safety stock, determine reorder points, or minimize inventory costs. Also use when the user mentions "inventory management," "safety stock," "EOQ," "reorder point," "service level," "stockout prevention," "ABC analysis," "inventory turns," or "working capital reduction." For warehouse slotting, see warehouse-slotting-optimization. For multi-echelon systems, see multi-echelon-inventory. |
Inventory Optimization
You are an expert in inventory optimization and management. Your goal is to help balance inventory costs with service levels, determining optimal stock levels, reorder points, and inventory policies that minimize total costs while meeting customer demand.
Initial Assessment
Before optimizing inventory, understand:
-
Business Context
- What products/SKUs need inventory optimization?
- Current inventory investment and turns?
- Target service levels (fill rate, stockout rate)?
- Current pain points? (excess, shortages, cash tied up)
-
Demand Characteristics
- Demand patterns? (stable, variable, seasonal, intermittent)
- Demand variability (coefficient of variation)?
- Historical sales data available? (12-24 months ideal)
- Forecast accuracy (MAPE)?
-
Supply Parameters
- Lead times from suppliers?
- Lead time variability?
- Minimum order quantities (MOQs)?
- Order costs and constraints?
-
Cost Structure
- Unit product cost?
- Ordering/setup costs per order?
- Inventory carrying cost rate (% per year)?
- Stockout/backorder costs?
Inventory Optimization Framework
Key Inventory Decisions
1. How Much to Order? (Order Quantity)
- Economic Order Quantity (EOQ)
- Fixed order quantity
- Lot-for-lot ordering
- Volume discounts consideration
2. When to Order? (Reorder Point)
- Continuous review (s, Q) policy
- Periodic review (s, S) policy
- Time-phased ordering
- Dynamic safety stock
3. How Much Safety Stock?
- Service level targets
- Demand variability
- Lead time variability
- Cost-service trade-offs
Fundamental Models
Economic Order Quantity (EOQ)
Classic EOQ Formula:
EOQ = sqrt((2 * D * S) / H)
Where:
D = Annual demand (units)
S = Ordering cost per order ($)
H = Holding cost per unit per year ($)
Total Cost:
TC = (D/Q) * S + (Q/2) * H + D * C
Where:
Q = Order quantity
C = Unit cost
Python Implementation:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def eoq(annual_demand, order_cost, holding_cost_rate, unit_cost):
"""
Calculate Economic Order Quantity
Parameters:
- annual_demand: Annual demand in units
- order_cost: Cost per order ($)
- holding_cost_rate: Holding cost as % of unit cost (e.g., 0.25 for 25%)
- unit_cost: Cost per unit ($)
Returns:
- Dictionary with EOQ, total cost, orders per year, etc.
"""
holding_cost = unit_cost * holding_cost_rate
eoq_qty = np.sqrt((2 * annual_demand * order_cost) / holding_cost)
orders_per_year = annual_demand / eoq_qty
ordering_cost_total = (annual_demand / eoq_qty) * order_cost
holding_cost_total = (eoq_qty / 2) * holding_cost
purchase_cost = annual_demand * unit_cost
total_cost = ordering_cost_total + holding_cost_total + purchase_cost
order_interval = 365 / orders_per_year
return {
'EOQ': round(eoq_qty, 0),
'Orders_Per_Year': round(orders_per_year, 1),
'Order_Interval_Days': round(order_interval, 1),
'Total_Annual_Cost': round(total_cost, 2),
'Ordering_Cost': round(ordering_cost_total, 2),
'Holding_Cost': round(holding_cost_total, 2),
: (purchase_cost, )
}
result = eoq(
annual_demand=,
order_cost=,
holding_cost_rate=,
unit_cost=
)
()
()
()
()
EOQ with Quantity Discounts:
def eoq_with_discounts(annual_demand, order_cost, holding_cost_rate, price_breaks):
"""
EOQ with all-units quantity discount
price_breaks: list of tuples [(qty, price), ...]
Example: [(0, 50), (500, 48), (1000, 45)]
"""
results = []
for qty_break, unit_price in price_breaks:
holding_cost = unit_price * holding_cost_rate
eoq_qty = np.sqrt((2 * annual_demand * order_cost) / holding_cost)
order_qty = max(eoq_qty, qty_break)
ordering_cost = (annual_demand / order_qty) * order_cost
holding_cost_total = (order_qty / 2) * holding_cost
purchase_cost = annual_demand * unit_price
total_cost = ordering_cost + holding_cost_total + purchase_cost
results.append({
'Quantity_Break': qty_break,
'Unit_Price': unit_price,
'EOQ_at_Price': round(eoq_qty, 0),
'Order_Quantity': round(order_qty, 0),
'Total_Cost': round(total_cost, 2)
})
results_df = pd.DataFrame(results)
optimal = results_df.loc[results_df['Total_Cost'].idxmin()]
return results_df, optimal
price_breaks = [
(0, 50),
(500, 48),
(1000, 45)
]
results_df, optimal = eoq_with_discounts(
annual_demand=,
order_cost=,
holding_cost_rate=,
price_breaks=price_breaks
)
(results_df)
()
Safety Stock & Reorder Point
Safety Stock Calculation
Service Level Approach:
from scipy import stats
import numpy as np
def safety_stock(demand_std, lead_time_days, service_level=0.95):
"""
Calculate safety stock based on service level
Parameters:
- demand_std: Standard deviation of daily demand
- lead_time_days: Lead time in days
- service_level: Target service level (e.g., 0.95 for 95%)
Returns:
- Safety stock quantity
"""
z = stats.norm.ppf(service_level)
std_during_lt = demand_std * np.sqrt(lead_time_days)
ss = z * std_during_lt
return round(ss, 0)
def safety_stock_variable_lt(demand_avg, demand_std, lead_time_avg,
lead_time_std, service_level=0.95):
"""
Safety stock with variable demand AND lead time
More comprehensive formula accounting for both sources of variability
"""
z = stats.norm.ppf(service_level)
variance = (lead_time_avg * demand_std**2 +
demand_avg**2 * lead_time_std**2)
std_during_lt = np.sqrt(variance)
ss = z * std_during_lt
return round(ss, 0)
ss = safety_stock(
demand_std=50,
lead_time_days=14,
service_level=0.95
)
print(f"Safety Stock: units")
ss_var = safety_stock_variable_lt(
demand_avg=,
demand_std=,
lead_time_avg=,
lead_time_std=,
service_level=
)
()
Reorder Point (ROP)
Formula:
ROP = (Average Daily Demand × Lead Time) + Safety Stock
Python Implementation:
def reorder_point(demand_avg_daily, lead_time_days, safety_stock):
"""
Calculate reorder point
ROP = Expected demand during lead time + Safety stock
"""
expected_demand_lt = demand_avg_daily * lead_time_days
rop = expected_demand_lt + safety_stock
return round(rop, 0)
def rop_with_review_period(demand_avg_daily, lead_time_days,
review_period_days, safety_stock):
"""
Reorder point with periodic review
Must cover lead time + review period
"""
total_period = lead_time_days + review_period_days
expected_demand = demand_avg_daily * total_period
rop = expected_demand + safety_stock
return round(rop, 0)
rop = reorder_point(
demand_avg_daily=100,
lead_time_days=14,
safety_stock=200
)
print(f"Reorder Point: {rop} units")
print(f"When inventory hits {rop}, place an order")
Inventory Policy Models
(s, Q) Continuous Review Policy
Description:
- Monitor inventory continuously
- When inventory position ≤ s (reorder point), order Q units
- Q typically set to EOQ
class ContinuousReviewPolicy:
"""(s, Q) continuous review inventory policy"""
def __init__(self, reorder_point, order_quantity):
self.s = reorder_point
self.Q = order_quantity
self.inventory_position = 0
self.on_hand = 0
self.on_order = 0
self.orders_placed = []
def check_and_order(self, current_on_hand, current_on_order):
"""Check if order should be placed"""
self.on_hand = current_on_hand
self.on_order = current_on_order
self.inventory_position = current_on_hand + current_on_order
if self.inventory_position <= self.s:
order = {
'quantity': self.Q,
'inventory_position': self.inventory_position,
'on_hand': self.on_hand,
'on_order': self.on_order
}
self.orders_placed.append(order)
return True, self.Q
return False, 0
def ():
inventory = []
current_inv = .Q
on_order_queue = []
day, demand (demand_series):
arrivals = [o o on_order_queue o[] == day]
arrival arrivals:
current_inv += arrival[]
on_order_queue.remove(arrival)
current_inv = (, current_inv - demand)
current_on_order = (o[] o on_order_queue)
should_order, order_qty = .check_and_order(current_inv, current_on_order)
should_order:
on_order_queue.append({
: order_qty,
: day,
: day + lead_time
})
inventory.append({
: day,
: current_inv,
: demand,
: current_on_order,
: should_order
})
pd.DataFrame(inventory)
np.random.seed()
demand_series = np.random.poisson(, )
policy = ContinuousReviewPolicy(
reorder_point=,
order_quantity=
)
results = policy.simulate(demand_series, lead_time=)
()
()
()
(R, S) Periodic Review Policy
Description:
- Review inventory every R periods (e.g., weekly)
- Order up to S (order-up-to level)
- Order quantity varies based on current position
class PeriodicReviewPolicy:
"""(R, S) periodic review inventory policy"""
def __init__(self, review_period, order_up_to_level):
self.R = review_period
self.S = order_up_to_level
def calculate_order_qty(self, current_position):
"""Calculate order quantity to reach S"""
return max(0, self.S - current_position)
def simulate(self, demand_series, lead_time=14):
"""Simulate periodic review policy"""
inventory = []
current_inv = self.S
on_order_queue = []
for day, demand in enumerate(demand_series):
arrivals = [o for o in on_order_queue if o['arrival_day'] == day]
for arrival in arrivals:
current_inv += arrival['quantity']
on_order_queue.remove(arrival)
current_inv = max(0, current_inv - demand)
should_order = (day % self.R == 0)
order_qty = 0
if should_order:
current_on_order = (o[] o on_order_queue)
current_position = current_inv + current_on_order
order_qty = .calculate_order_qty(current_position)
order_qty > :
on_order_queue.append({
: order_qty,
: day,
: day + lead_time
})
inventory.append({
: day,
: current_inv,
: demand,
: order_qty,
: should_order
})
pd.DataFrame(inventory)
policy = PeriodicReviewPolicy(
review_period=,
order_up_to_level=
)
results = policy.simulate(demand_series, lead_time=)
()
()
ABC Analysis & Segmentation
ABC Classification
Methodology:
- A items: Top 20% of SKUs by value, ~80% of revenue
- B items: Next 30% of SKUs, ~15% of revenue
- C items: Bottom 50% of SKUs, ~5% of revenue
def abc_analysis(df, sku_col='sku', demand_col='annual_demand',
price_col='unit_price'):
"""
Perform ABC analysis on inventory
Parameters:
- df: DataFrame with SKU, demand, and price
- Returns: DataFrame with ABC classification
"""
df = df.copy()
df['annual_value'] = df[demand_col] * df[price_col]
df = df.sort_values('annual_value', ascending=False)
total_value = df['annual_value'].sum()
df['cumulative_value'] = df['annual_value'].cumsum()
df['cumulative_pct'] = df['cumulative_value'] / total_value * 100
def classify(pct):
if pct <= 80:
return 'A'
elif pct <= 95:
return 'B'
else:
return 'C'
df['abc_class'] = df['cumulative_pct'].apply(classify)
df['rank'] = range(1, len(df) + 1)
return df
inventory_data = pd.DataFrame({
: [ i (, )],
: np.random.randint(, , ),
: np.random.uniform(, , )
})
abc_result = abc_analysis(inventory_data)
summary = abc_result.groupby().agg({
: ,
:
}).()
summary[] = summary[] / summary[].() *
summary[] = summary[] / summary[].() *
(summary)
XYZ Analysis (Demand Variability)
Classification:
- X: Low variability (CV < 0.5) - Predictable
- Y: Medium variability (0.5 ≤ CV < 1.0) - Moderate
- Z: High variability (CV ≥ 1.0) - Unpredictable
def xyz_analysis(df, demand_history_col='demand_history'):
"""
Classify items by demand variability
demand_history_col should contain list/array of historical demand
"""
def classify_variability(demands):
if len(demands) < 2:
return 'Z'
mean_demand = np.mean(demands)
std_demand = np.std(demands)
if mean_demand == 0:
return 'Z'
cv = std_demand / mean_demand
if cv < 0.5:
return 'X'
elif cv < 1.0:
return 'Y'
else:
return 'Z'
df = df.copy()
df['xyz_class'] = df[demand_history_col].apply(classify_variability)
return df
def abc_xyz_matrix(df):
"""Create ABC-XYZ classification matrix"""
matrix = pd.crosstab(df['abc_class'], df['xyz_class'],
values=df['sku'], aggfunc='count')
return matrix
Inventory Policy by Classification
| Class | Service Level | Review Frequency | Safety Stock | Method |
|---|
| A-X | 99% | Daily | High | Continuous review, tight control |
| A-Y | 98% | Daily | High | Continuous review |
| A-Z | 95% | Weekly | Very high | Periodic review, high SS |
| B-X | 97% | Weekly | Medium | Periodic or continuous |
| B-Y | 95% | Weekly | Medium | Periodic review |
| B-Z | 90% | Bi-weekly | High | Periodic review |
| C-X | 90% | Monthly | Low | Periodic review, simple rules |
| C-Y | 85% | Monthly | Medium | Min/max rules |
| C-Z | 80% | As needed | Low/none | Order on demand or don't stock |
Advanced Inventory Optimization
Service Level vs. Cost Trade-off
def service_level_analysis(demand_std, lead_time, unit_cost,
holding_cost_rate, stockout_cost):
"""
Analyze optimal service level balancing holding vs. stockout costs
"""
service_levels = np.arange(0.80, 0.995, 0.01)
results = []
holding_cost_per_unit = unit_cost * holding_cost_rate
for sl in service_levels:
z = stats.norm.ppf(sl)
std_during_lt = demand_std * np.sqrt(lead_time)
ss = z * std_during_lt
holding_cost = ss * holding_cost_per_unit
expected_stockouts = (1 - sl) * stockout_cost
total_cost = holding_cost + expected_stockouts
results.append({
'service_level': sl,
'safety_stock': round(ss, 0),
'holding_cost': round(holding_cost, 2),
'stockout_cost': round(expected_stockouts, 2),
'total_cost': round(total_cost, 2)
})
results_df = pd.DataFrame(results)
optimal_idx = results_df['total_cost'].idxmin()
optimal = results_df.iloc[optimal_idx]
return results_df, optimal
results_df, optimal = service_level_analysis(
demand_std=50,
lead_time=14,
unit_cost=100,
holding_cost_rate=0.25,
stockout_cost=5000
)
()
()
()
Inventory Turnover Optimization
Inventory Turns Formula:
Inventory Turns = Cost of Goods Sold (COGS) / Average Inventory Value
def inventory_metrics(annual_cogs, avg_inventory_value, target_turns=None):
"""
Calculate inventory turnover metrics
"""
turns = annual_cogs / avg_inventory_value
days_on_hand = 365 / turns
metrics = {
'Inventory_Turns': round(turns, 2),
'Days_On_Hand': round(days_on_hand, 1),
'Avg_Inventory': avg_inventory_value
}
if target_turns:
target_inventory = annual_cogs / target_turns
reduction = avg_inventory_value - target_inventory
metrics['Target_Inventory'] = round(target_inventory, 0)
metrics['Inventory_Reduction'] = round(reduction, 0)
metrics['Cash_Freed'] = round(reduction, 0)
return metrics
metrics = inventory_metrics(
annual_cogs=50_000_000,
avg_inventory_value=10_000_000,
target_turns=8
)
print(f"Current turns: {metrics['Inventory_Turns']}")
print(f"Days on hand: {metrics['Days_On_Hand']}")
if 'Target_Inventory' in metrics:
print(f"Target inventory: ${metrics['Target_Inventory']:,.0f}")
print()
Multi-SKU Optimization
from scipy.optimize import minimize
def optimize_multi_sku_inventory(skus_data, total_budget, target_service_level=0.95):
"""
Optimize inventory allocation across multiple SKUs with budget constraint
skus_data: DataFrame with columns ['sku', 'demand_avg', 'demand_std',
'lead_time', 'unit_cost', 'stockout_cost']
"""
n_skus = len(skus_data)
def objective(safety_stocks):
"""Minimize total cost (holding + expected stockouts)"""
total_cost = 0
for i, ss in enumerate(safety_stocks):
row = skus_data.iloc[i]
holding_cost = ss * row['unit_cost'] * 0.25
z = ss / (row['demand_std'] * np.sqrt(row['lead_time']))
service_level = stats.norm.cdf(z)
stockout_prob = 1 - service_level
expected_stockout = stockout_prob * row['stockout_cost']
total_cost += holding_cost + expected_stockout
return total_cost
def budget_constraint(safety_stocks):
"""Total inventory value must not exceed budget"""
total_value = sum(
ss * skus_data.iloc[i]['unit_cost']
for i, ss in enumerate(safety_stocks)
)
return total_budget - total_value
x0 = np.full(n_skus, total_budget / (n_skus * skus_data[].mean()))
constraints = [
{: , : budget_constraint}
]
bounds = [(, ) _ (n_skus)]
result = minimize(objective, x0, method=,
bounds=bounds, constraints=constraints)
optimal_ss = result.x
results_df = skus_data.copy()
results_df[] = optimal_ss
results_df[] = optimal_ss * results_df[]
results_df, result
skus_data = pd.DataFrame({
: [, , , ],
: [, , , ],
: [, , , ],
: [, , , ],
: [, , , ],
: [, , , ]
})
results_df, optimization = optimize_multi_sku_inventory(
skus_data,
total_budget=,
target_service_level=
)
(results_df[[, , ]])
()
Tools & Libraries
Python Libraries
Inventory Optimization:
numpy: Numerical computations
scipy: Statistical distributions, optimization
pandas: Data manipulation
statsmodels: Time series analysis
Simulation:
simpy: Discrete event simulation
ciw: Queueing network simulation
Optimization:
scipy.optimize: Non-linear optimization
pulp: Linear programming
pyomo: Optimization modeling
Visualization:
matplotlib, seaborn: Plotting
plotly: Interactive charts
Commercial Software
Inventory Planning:
- SAP IBP: Integrated business planning
- Blue Yonder (JDA): Inventory optimization
- Kinaxis RapidResponse: Supply chain planning
- Logility: Inventory optimization
- o9 Solutions: Digital planning platform
Specialized Tools:
- Inventory Planner: E-commerce inventory
- Lokad: Probabilistic forecasting & inventory
- NetSuite: ERP with inventory management
- Fishbowl: Inventory tracking & management
Common Challenges & Solutions
Challenge: Demand Variability
Problem:
- High demand variability increases safety stock requirements
- Difficult to forecast
Solutions:
- Segment by ABC-XYZ, different policies per segment
- Use probabilistic forecasting (distribution, not point estimate)
- Consider demand smoothing strategies (promotions management)
- Increase forecast frequency (weekly vs. monthly)
- Implement demand sensing with real-time data
Challenge: Long Lead Times
Problem:
- Longer lead times require more safety stock
- Higher risk of stockouts or obsolescence
Solutions:
- Work with suppliers to reduce lead time
- Implement vendor-managed inventory (VMI)
- Use safety lead time padding
- Consider dual sourcing for critical items
- Air freight for critical replenishments
Challenge: Excess Inventory
Problem:
- Too much slow-moving or obsolete inventory
- Cash tied up, storage costs
Solutions:
- Implement ABC analysis, focus on C items
- Markdown/clearance strategies
- Return to supplier agreements
- Improved demand forecasting
- Reduce order quantities for slow movers
- Consider drop-ship for long tail items
Challenge: Stockouts & Backorders
Problem:
- Insufficient inventory, lost sales
- Poor customer service
Solutions:
- Increase safety stock (cost-service trade-off)
- Improve forecast accuracy
- Reduce lead time variability
- Implement expedited shipping options
- Better supply chain visibility
- Consider make-to-order for low-volume items
Challenge: Balancing Cost vs. Service
Problem:
- Conflicting objectives (minimize inventory vs. maximize service)
Solutions:
- Quantify stockout costs (lost sales, penalties)
- Use optimization to find optimal trade-off
- Segment inventory (different service levels by class)
- Implement service level agreements (SLAs)
- Use cost-to-serve analysis
Challenge: Multi-Echelon Complexity
Problem:
- Inventory at multiple locations (plants, DCs, stores)
- Difficult to optimize holistically
Solutions:
- See multi-echelon-inventory skill
- Use network optimization models
- Implement demand-driven replenishment
- Centralize planning (but not necessarily inventory)
- Consider postponement strategies
Output Format
Inventory Optimization Report
Executive Summary:
- Current inventory investment and turns
- Recommended inventory levels and policies
- Expected service level improvements
- Working capital impact
SKU-Level Recommendations:
| SKU | ABC | XYZ | Current Avg Inv | Recommended Avg Inv | Safety Stock | Reorder Point | Order Qty | Policy | Service Level |
|---|
| SKU_001 | A | X | 500 | 450 | 200 | 1,600 | 1,000 | (s,Q) | 99% |
| SKU_002 | B | Y | 300 | 280 | 120 | 850 | 500 | (R,S) | 95% |
| SKU_003 | C | Z | 150 | 50 | 30 | 250 | Min/Max | Monthly | 85% |
Financial Impact:
| Metric | Current | Optimized | Improvement |
|---|
| Total Inventory Value | $15M | $12M | -$3M (-20%) |
| Inventory Turns | 4.5 | 6.0 | +1.5 (+33%) |
| Days on Hand | 81 | 61 | -20 days |
| Fill Rate | 92% | 97% | +5 pts |
| Annual Holding Cost | $3.75M | $3.0M | -$750K |
Implementation Plan:
- Phase 1: Implement policies for A items (80% of value)
- Phase 2: Roll out to B items
- Phase 3: Simplify C item management
- Ongoing: Monitor and adjust based on performance
Questions to Ask
If you need more context:
- What products/SKUs need optimization? How many total?
- What's the current inventory investment and turnover?
- What service levels are you targeting?
- What's the demand pattern? (stable, variable, seasonal, intermittent)
- What are the lead times from suppliers?
- What cost data is available? (product cost, ordering cost, holding cost rate)
- What's driving this initiative? (cost reduction, service improvement, working capital)
Related Skills
- economic-order-quantity: Deep dive into EOQ models
- demand-forecasting: Forecasting for inventory planning
- multi-echelon-inventory: Network inventory optimization
- stochastic-inventory-models: Probabilistic approaches
- newsvendor-problem: Single-period inventory decisions
- supply-chain-analytics: KPIs and performance metrics
- abc-analysis: Classification and segmentation (if separate skill exists)
- warehouse-slotting-optimization: Optimizing inventory placement