PROJECT 078 · PYTHON SOURCE
Customer spending concentration
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': 78, 'dataset': 'wholesale', 'title': 'Customer spending concentration', 'question': 'What fraction of aggregate annual spending is associated with the highest-spending customers?', 'method': 'Rank customers by total observed spending and compute concentration at fixed top fractions.', 'action': 'Consider account-service concentration while avoiding assumptions about profitability.', 'limitations': 'Annual customer spending uses source monetary units, not an assumed currency. There are no margins, transactions or dates. Customer segments are descriptive and do not establish promotion response. '}
def analyze():
df = load('wholesale').copy()
total=df[SPEND].sum(axis=1).sort_values(ascending=False)
t=pd.DataFrame([{'top_customer_fraction':f,'customers':int(np.ceil(len(total)*f)),'spend_share':total.head(int(np.ceil(len(total)*f))).sum()/total.sum()} for f in [.01,.05,.1,.2,.5,1.]])
out=result(t,'top_customer_fraction','spend_share','Share of annual spending','No margin or exposure data are supplied; customer concentration is not the same as credit risk.')
return out
if __name__ == "__main__":
execute(Path(__file__).parent, META, analyze)