PROJECT 005 · PYTHON SOURCE
Product ABC inventory priorities
Study-specific code. Shared modules, dependency versions, and reproduction instructions are included in all project files.
Download Python file ↓from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.decomposition import PCA
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, precision_score, recall_score
from portfolio.data import load
from portfolio.constants import *
from portfolio.methods import result, sql, rates, associations, distribution, regression, classification, cluster
from portfolio.engine import execute
META = {'id': 5, 'dataset': 'retail', 'title': 'Product ABC inventory priorities', 'question': 'How many product codes account for the first 80% of invoiced product value?', 'method': 'Cumulative revenue ranking with 80% and 95% ABC boundaries.', 'action': 'Prioritize review effort across the assortment; stock levels and holding costs are needed for an inventory policy.', 'limitations': 'Historical invoice lines; credits are not reliably matched to original sales. Gross purchases are not profit. Unidentified customers cannot support customer-level conclusions. Exact repeated lines remain unless the study explicitly compares removal. '}
def analyze():
df = load('retail').copy()
t=df[df.is_sale].groupby('stockcode').agg(gross_gbp=('value','sum'),units=('quantity','sum')).sort_values('gross_gbp',ascending=False).reset_index()
t['share']=t.gross_gbp/t.gross_gbp.sum(); t['prior_cumulative_share']=t.share.cumsum()-t.share
t['class']=np.select([t.prior_cumulative_share<.8,t.prior_cumulative_share<.95],['A','B'],default='C')
s=t.groupby('class').agg(product_codes=('stockcode','size'),gross_gbp=('gross_gbp','sum')).reset_index()
s['sales_share']=s.gross_gbp/s.gross_gbp.sum()
out=result(s,'class','sales_share','Share','Include the boundary-crossing code in the earlier class. Source product codes can include charges.',extra={'product_ranking':t})
return out
if __name__ == "__main__":
execute(Path(__file__).parent, META, analyze)