PD03 commited on
Commit
4a1e4c5
·
verified ·
1 Parent(s): 98d76ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -242
app.py CHANGED
@@ -1,4 +1,3 @@
1
-
2
  import streamlit as st
3
  import numpy as np
4
  import pandas as pd
@@ -30,7 +29,6 @@ def generate_synthetic_data(days=60, seed=42, rows_per_day=600):
30
  regions = ["AMER", "EMEA", "APAC"]
31
  channels = ["Direct", "Distributor", "Online"]
32
 
33
- # Base economics
34
  base_price = {"A": 120, "B": 135, "C": 110, "D": 150}
35
  base_cost = {"A": 70, "B": 88, "C": 60, "D": 95}
36
 
@@ -40,12 +38,10 @@ def generate_synthetic_data(days=60, seed=42, rows_per_day=600):
40
  channel_discount_mean = {"Direct": 0.06, "Distributor": 0.12, "Online": 0.04}
41
  channel_discount_std = {"Direct": 0.02, "Distributor": 0.03, "Online": 0.02}
42
 
43
- # True (hidden) elasticities per segment product×region×channel
44
  seg_epsilon = {}
45
  for p in products:
46
  for r in regions:
47
  for c in channels:
48
- # Inelastic online, more elastic distributor
49
  base_eps = rng.uniform(-0.9, -0.25)
50
  if c == "Distributor":
51
  base_eps -= rng.uniform(0.1, 0.3)
@@ -55,11 +51,8 @@ def generate_synthetic_data(days=60, seed=42, rows_per_day=600):
55
 
56
  records = []
57
  for d in dates:
58
- # Seasonality/day-of-week effect
59
  dow = d.weekday()
60
- dow_mult = 1.0 + (0.06 if dow in (5, 6) else 0) # weekend lift
61
-
62
- # Random macro shock (slow drift)
63
  macro = 1.0 + 0.03*np.sin((d.toordinal()%365)/365*2*np.pi)
64
 
65
  n = rows_per_day
@@ -70,17 +63,14 @@ def generate_synthetic_data(days=60, seed=42, rows_per_day=600):
70
  base_p = np.array([base_price[x] for x in prod]) * np.array([region_price_bump[x] for x in reg])
71
  base_c = np.array([base_cost[x] for x in prod]) * np.array([region_cost_bump[x] for x in reg])
72
 
73
- # Realized price & cost
74
  discount = np.clip(
75
  np.array([channel_discount_mean[x] for x in ch]) +
76
  rng.normal(0, [channel_discount_std[x] for x in ch]), 0, 0.45
77
  )
78
  list_price = rng.normal(base_p, 5)
79
  net_price = np.clip(list_price * (1 - discount), 20, None)
80
-
81
  unit_cost = np.clip(rng.normal(base_c, 4), 10, None)
82
 
83
- # Quantity via elasticity around a reference price
84
  eps = np.array([seg_epsilon[(pp, rr, cc)] for pp, rr, cc in zip(prod, reg, ch)])
85
  ref_price = np.array([base_price[x] for x in prod])
86
  qty_mu = np.exp(eps * (net_price - ref_price) / np.maximum(ref_price, 1e-6))
@@ -108,13 +98,12 @@ def generate_synthetic_data(days=60, seed=42, rows_per_day=600):
108
  "gm_pct": float(gm_pct[i]),
109
  "dow": dow
110
  })
111
- df = pd.DataFrame(records)
112
- return df
113
 
114
  # -----------------------------
115
  # 2) Modeling utilities
116
  # -----------------------------
117
- def build_features(df: pd.DataFrame):
118
  feats_num = ["net_price", "unit_cost", "qty", "discount_pct", "list_price", "dow"]
119
  feats_cat = ["product", "region", "channel"]
120
 
@@ -128,288 +117,116 @@ def build_features(df: pd.DataFrame):
128
  df["roll7_cost"] = df.groupby(seg)["cost_per_unit"].transform(lambda s: s.rolling(7, min_periods=1).median())
129
 
130
  feats_num += ["price_per_unit", "cost_per_unit", "roll7_qty", "roll7_price", "roll7_cost"]
131
- target = "gm_pct"
132
- return df, feats_num, feats_cat, target
133
 
134
  @st.cache_resource(show_spinner=False)
135
- def train_model(df: pd.DataFrame, feats_num, feats_cat, target, n_estimators=250):
136
  X = df[feats_num + feats_cat]
137
  y = df[target]
138
-
139
- pre = ColumnTransformer(
140
- transformers=[
141
- ("cat", OneHotEncoder(handle_unknown="ignore"), feats_cat),
142
- ("num", "passthrough", feats_num),
143
- ]
144
- )
145
- model = RandomForestRegressor(n_estimators=n_estimators, max_depth=None, random_state=42, n_jobs=-1, min_samples_leaf=3)
146
  pipe = Pipeline([("pre", pre), ("rf", model)])
147
-
148
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, shuffle=False)
149
  pipe.fit(X_train, y_train)
150
  pred = pipe.predict(X_test)
151
-
152
- r2 = r2_score(y_test, pred)
153
- mae = mean_absolute_error(y_test, pred)
154
-
155
- # Store components for SHAP later (on-demand)
156
- return pipe, {"r2": r2, "mae": mae}, X_test
157
 
158
  @st.cache_resource(show_spinner=False)
159
- def compute_shap(pipe, X_sample, feats_num, feats_cat, shap_sample=800, seed=42):
160
  np.random.seed(seed)
161
- preproc = pipe.named_steps["pre"]
162
- rf = pipe.named_steps["rf"]
163
  feature_names = list(preproc.named_transformers_["cat"].get_feature_names_out(feats_cat)) + feats_num
164
 
165
  if len(X_sample) > shap_sample:
166
- sample_idx = np.random.choice(len(X_sample), size=shap_sample, replace=False)
167
- X_sample = X_sample.iloc[sample_idx]
168
-
169
  X_t = preproc.transform(X_sample)
170
  try:
171
  X_t = X_t.toarray()
172
  except Exception:
173
  pass
174
-
175
  explainer = shap.TreeExplainer(rf)
176
  shap_values = explainer.shap_values(X_t)
177
- expected_value = explainer.expected_value
178
-
179
- shap_df = pd.DataFrame(shap_values, columns=feature_names)
180
- return shap_df, expected_value, X_sample.reset_index(drop=True), feature_names
181
 
182
- def estimate_segment_elasticity(df: pd.DataFrame, product, region, channel):
183
  seg_df = df[(df["product"]==product)&(df["region"]==region)&(df["channel"]==channel)]
184
- if len(seg_df) < 100 or seg_df["net_price"].std() < 1e-6 or seg_df["qty"].std() < 1e-6:
185
  return -0.5, False
186
  x = np.log(np.clip(seg_df["net_price"].values, 1e-6, None)).reshape(-1,1)
187
  y = np.log(np.clip(seg_df["qty"].values, 1e-6, None))
188
  lin = LinearRegression().fit(x, y)
189
  return float(lin.coef_[0]), True
190
 
191
- def simulate_action(segment_df: pd.DataFrame, elasticity, delta_discount=0.0, delta_unit_cost=0.0):
192
  if segment_df.empty:
193
  return None
194
  base = segment_df.iloc[-1]
195
- p0 = base["net_price"]
196
- c0 = base["unit_cost"]
197
- q0 = base["qty"]
198
- d0 = base["discount_pct"]
199
-
200
  new_discount = np.clip(d0 + delta_discount, 0.0, 0.45)
201
  p1 = max(0.01, base["list_price"] * (1 - new_discount))
202
  c1 = max(0.01, c0 + delta_unit_cost)
203
-
204
- if p0 <= 0:
205
- q1 = q0
206
- else:
207
- q1 = max(0.0, q0 * (p1 / p0) ** elasticity)
208
-
209
- rev0 = p0 * q0
210
- cogs0 = c0 * q0
211
- rev1 = p1 * q1
212
- cogs1 = c1 * q1
213
-
214
- gm_delta_value = (rev1 - cogs1) - (rev0 - cogs0)
215
- gm0_pct = (rev0 - cogs0)/rev0 if rev0>0 else 0.0
216
- gm1_pct = (rev1 - cogs1)/rev1 if rev1>0 else 0.0
217
  return {
 
 
 
 
218
  "baseline_price": p0, "new_price": p1,
219
  "baseline_cost": c0, "new_cost": c1,
220
  "baseline_qty": q0, "new_qty": q1,
221
- "gm_delta_value": gm_delta_value,
222
- "gm0_pct": gm0_pct, "gm1_pct": gm1_pct,
223
- "new_discount": new_discount
224
  }
225
 
226
  # -----------------------------
227
  # 3) UI
228
  # -----------------------------
229
  st.title("📈 AI-Driven Daily Gross Margin — Analysis & What-if Simulator")
230
- st.caption("Synthetic demo: Revenue − COGS focus • Driver analysis with SHAP • What-if recommendations")
231
-
232
  with st.sidebar:
233
  st.header("⚙️ Controls")
234
- fast_mode = st.toggle("Fast mode (recommended on Spaces)", value=True)
235
- if fast_mode:
236
- days = st.slider("History (days)", 30, 120, 60, 1)
237
- rows_per_day = st.slider("Rows per day", 300, 2000, 600, 100)
238
- else:
239
- days = st.slider("History (days)", 45, 180, 90, 1)
240
- rows_per_day = st.slider("Rows per day", 300, 3000, 1200, 100)
241
-
242
- seed = st.number_input("Random seed", value=42, step=1)
243
- st.markdown("---")
244
- st.markdown("**Training**")
245
- n_trees = st.slider("RandomForest trees", 100, 600, 250 if fast_mode else 400, 50)
246
- st.caption("Model: RandomForestRegressor (SHAP via TreeExplainer)")
247
- st.markdown("---")
248
- st.markdown("**SHAP computation**")
249
- shap_sample = st.slider("SHAP sample size", 200, 3000, 800 if fast_mode else 1800, 100)
250
- st.markdown("---")
251
- st.markdown("**What-if Defaults**")
252
- default_disc_step = st.slider("Default discount step (points)", -5.0, 5.0, -1.5, 0.1)
253
- default_cost_step = st.slider("Default unit cost change", -5.0, 5.0, 0.0, 0.1)
254
-
255
- # Data
256
- with st.spinner("Generating realistic synthetic data..."):
257
- df = generate_synthetic_data(days=days, seed=int(seed), rows_per_day=int(rows_per_day))
258
-
259
  df_feat, feats_num, feats_cat, target = build_features(df)
260
 
261
  # KPI panel
262
  daily = df.groupby("date").agg(revenue=("revenue","sum"), cogs=("cogs","sum"), gm_value=("gm_value","sum")).reset_index()
263
- daily["gm_pct"] = np.where(daily["revenue"]>0, daily["gm_value"]/daily["revenue"], 0.0)
264
  today_row = daily.iloc[-1]
265
- roll7 = daily["gm_pct"].tail(7).mean() if len(daily)>=7 else daily["gm_pct"].mean()
266
- delta_pts = (today_row["gm_pct"] - roll7)*100
267
-
268
- kpi_cols = st.columns(4)
269
- kpi_cols[0].metric("GM% (today)", f"{today_row['gm_pct']*100:.2f}%",
270
- f"{delta_pts:+.2f} pts vs 7D avg")
271
- kpi_cols[1].metric("Revenue (today)", f"{today_row['revenue']/1e6:.2f} M")
272
- kpi_cols[2].metric("COGS (today)", f"{today_row['cogs']/1e6:.2f} M")
273
- kpi_cols[3].metric("GM Value (today)", f"{today_row['gm_value']/1e6:.2f} M")
274
 
275
- fig = px.line(daily, x="date", y="gm_pct", title="Daily GM% (history)")
276
- fig.update_yaxes(tickformat=".1%")
277
- st.plotly_chart(fig, use_container_width=True)
278
 
279
- # Train
280
- with st.spinner("Training model…"):
281
- pipe, metrics, X_test = train_model(df_feat, feats_num, feats_cat, target, n_estimators=int(n_trees))
 
 
 
282
 
283
- st.success(f"Model trained • R²={metrics['r2']:.3f} • MAE={metrics['mae']:.4f} (GM% points)")
284
-
285
- # SHAP: compute on demand
286
- st.subheader("🔍 Driver Analysis (Global)")
287
- if "shap_imp_df" not in st.session_state:
288
- st.session_state["shap_imp_df"] = None
289
- if "shap_joined" not in st.session_state:
290
- st.session_state["shap_joined"] = None
291
-
292
- compute_now = st.button("Compute / Refresh SHAP drivers")
293
- if compute_now or st.session_state["shap_imp_df"] is None:
294
- with st.spinner("Computing SHAP (sampled)…"):
295
- shap_df, expected_value, X_test_sample, feature_names = compute_shap(pipe, X_test, feats_num, feats_cat, shap_sample=int(shap_sample))
296
- mean_abs = shap_df.abs().mean().sort_values(ascending=False)
297
- imp_df = pd.DataFrame({"feature": mean_abs.index, "mean_abs_shap": mean_abs.values})
298
- st.session_state["shap_imp_df"] = imp_df
299
- # Keep a joined frame for segment view
300
- cat_cols = ["product","region","channel"]
301
- joined = pd.concat([X_test_sample.reset_index(drop=True), shap_df.reset_index(drop=True)], axis=1)
302
- st.session_state["shap_joined"] = joined
303
-
304
- imp_df = st.session_state["shap_imp_df"]
305
- if imp_df is not None:
306
- st.dataframe(imp_df.head(15), use_container_width=True)
307
- fig2, ax = plt.subplots(figsize=(8,5))
308
- imp_df.head(20).iloc[::-1].plot(kind="barh", x="feature", y="mean_abs_shap", ax=ax)
309
- ax.set_title("Top Drivers — Mean |SHAP| (GM%)")
310
- ax.set_xlabel("Mean |SHAP| contribution")
311
- st.pyplot(fig2, clear_figure=True)
312
- else:
313
- st.info("Click **Compute / Refresh SHAP drivers** to see driver importance.")
314
-
315
- # Segment analysis
316
- st.subheader("🧭 Where did it happen? (Segment view)")
317
- joined = st.session_state["shap_joined"]
318
- if joined is not None:
319
- key_feats = [c for c in joined.columns if any(k in c for k in ["discount", "price_per_unit", "cost_per_unit","unit_cost","net_price"])]
320
- grp = joined.groupby(["product","region","channel"]).mean(numeric_only=True)
321
- rank_cols = [c for c in grp.columns if c in key_feats]
322
- top_bad = grp[rank_cols].sum(axis=1).sort_values().head(10)
323
- top_good = grp[rank_cols].sum(axis=1).sort_values(ascending=False).head(10)
324
-
325
- c1, c2 = st.columns(2)
326
- with c1:
327
- st.caption("Segments dragging GM% (more negative net SHAP)")
328
- st.write(top_bad.to_frame("net_shap_sum").round(4))
329
- with c2:
330
- st.caption("Segments lifting GM% (more positive net SHAP)")
331
- st.write(top_good.to_frame("net_shap_sum").round(4))
332
- else:
333
- st.info("Compute SHAP first to populate the segment view.")
334
-
335
- # -----------------------------
336
- # What-if Simulator
337
- # -----------------------------
338
- st.header("🧪 What-if Simulator & Recommendations")
339
 
 
340
  last_day = df["date"].max()
341
- seg_today = df[df["date"]==last_day][["product","region","channel"]].drop_duplicates().sort_values(["product","region","channel"])
342
- seg_choice = st.selectbox("Choose a segment (product × region × channel):",
343
- seg_today.apply(lambda r: f"{r['product']} • {r['region']} • {r['channel']}", axis=1))
344
-
345
- prod_sel, reg_sel, ch_sel = [s.strip() for s in seg_choice.split("•")]
346
- seg_hist = df[(df["product"]==prod_sel)&(df["region"]==reg_sel)&(df["channel"]==ch_sel)].sort_values("date")
347
-
348
- elasticity, ok = estimate_segment_elasticity(seg_hist, prod_sel, reg_sel, ch_sel)
349
- st.caption(f"Estimated price elasticity for segment: **{elasticity:.2f}** ({'ok' if ok else 'fallback'})")
350
-
351
- c3, c4 = st.columns(2)
352
- with c3:
353
- delta_disc = st.slider("Change discount (percentage points)", -10.0, 10.0, -1.5, 0.1)
354
- with c4:
355
- delta_cost = st.slider("Change unit cost (absolute)", -5.0, 5.0, 0.0, 0.1)
356
-
357
- sim_res = simulate_action(seg_hist, elasticity, delta_discount=delta_disc/100.0, delta_unit_cost=delta_cost)
358
-
359
- if sim_res is not None:
360
- st.markdown(f"""
361
- **Simulated outcome (today’s baseline for {seg_choice}):**
362
- - New discount: **{sim_res['new_discount']*100:.2f}%**
363
- - Price: {sim_res['baseline_price']:.2f} → **{sim_res['new_price']:.2f}**
364
- - Cost: {sim_res['baseline_cost']:.2f} → **{sim_res['new_cost']:.2f}**
365
- - Qty: {sim_res['baseline_qty']:.1f} → **{sim_res['new_qty']:.1f}**
366
- - GM%: {sim_res['gm0_pct']*100:.2f}% → **{sim_res['gm1_pct']*100:.2f}%**
367
- - **GM uplift (value)**: **{sim_res['gm_delta_value']:.2f}**
368
- """)
369
-
370
- # -----------------------------
371
- # Auto Recommendations
372
- # -----------------------------
373
- st.subheader("💡 Top Recommendations (ranked by expected uplift)")
374
- if joined is not None:
375
- recent_join = joined.copy()
376
- recent_join["key"] = recent_join["product"] + "|" + recent_join["region"] + "|" + recent_join["channel"]
377
- cand_cols = [c for c in recent_join.columns if ("discount" in c or "cost" in c or "price" in c)]
378
- seg_scores = recent_join.groupby("key")[cand_cols].mean().sum(axis=1)
379
- worst_keys = seg_scores.sort_values().head(20).index.tolist()
380
-
381
- recs = []
382
- seen = set()
383
- for key in worst_keys:
384
- p, r, c = key.split("|")
385
- if key in seen:
386
- continue
387
- seen.add(key)
388
- hist = df[(df["product"]==p)&(df["region"]==r)&(df["channel"]==c)].sort_values("date")
389
- if hist.empty:
390
- continue
391
- eps, _ = estimate_segment_elasticity(hist, p, r, c)
392
- prop_disc_pts = -np.clip(abs(seg_scores[key])*10, 0.5, 2.0) # propose 0.5–2.0 pts tightening
393
- sim = simulate_action(hist, eps, delta_discount=prop_disc_pts/100.0, delta_unit_cost=0.0)
394
- if sim is None:
395
- continue
396
- recs.append({
397
- "segment": f"{p} • {r} • {c}",
398
- "action": f"Reduce discount by {abs(prop_disc_pts):.1f} pts",
399
- "expected_gm_uplift": sim["gm_delta_value"],
400
- "new_discount_pct": sim["new_discount"]*100,
401
- "elasticity": eps,
402
- "notes": "Driven by negative discount/price SHAP"
403
- })
404
-
405
- rec_df = pd.DataFrame(recs).sort_values("expected_gm_uplift", ascending=False)
406
- st.dataframe(rec_df.head(15), use_container_width=True)
407
- st.download_button("⬇️ Download recommendations (CSV)",
408
- data=rec_df.to_csv(index=False).encode("utf-8"),
409
- file_name="gm_recommendations.csv",
410
- mime="text/csv")
411
- else:
412
- st.info("Compute SHAP first to generate recommendation candidates.")
413
-
414
- st.markdown("---")
415
- st.caption("Demo only — synthetic data & simplified economics. For production, plug in your CDS feed and business constraints.")
 
 
1
  import streamlit as st
2
  import numpy as np
3
  import pandas as pd
 
29
  regions = ["AMER", "EMEA", "APAC"]
30
  channels = ["Direct", "Distributor", "Online"]
31
 
 
32
  base_price = {"A": 120, "B": 135, "C": 110, "D": 150}
33
  base_cost = {"A": 70, "B": 88, "C": 60, "D": 95}
34
 
 
38
  channel_discount_mean = {"Direct": 0.06, "Distributor": 0.12, "Online": 0.04}
39
  channel_discount_std = {"Direct": 0.02, "Distributor": 0.03, "Online": 0.02}
40
 
 
41
  seg_epsilon = {}
42
  for p in products:
43
  for r in regions:
44
  for c in channels:
 
45
  base_eps = rng.uniform(-0.9, -0.25)
46
  if c == "Distributor":
47
  base_eps -= rng.uniform(0.1, 0.3)
 
51
 
52
  records = []
53
  for d in dates:
 
54
  dow = d.weekday()
55
+ dow_mult = 1.0 + (0.06 if dow in (5, 6) else 0)
 
 
56
  macro = 1.0 + 0.03*np.sin((d.toordinal()%365)/365*2*np.pi)
57
 
58
  n = rows_per_day
 
63
  base_p = np.array([base_price[x] for x in prod]) * np.array([region_price_bump[x] for x in reg])
64
  base_c = np.array([base_cost[x] for x in prod]) * np.array([region_cost_bump[x] for x in reg])
65
 
 
66
  discount = np.clip(
67
  np.array([channel_discount_mean[x] for x in ch]) +
68
  rng.normal(0, [channel_discount_std[x] for x in ch]), 0, 0.45
69
  )
70
  list_price = rng.normal(base_p, 5)
71
  net_price = np.clip(list_price * (1 - discount), 20, None)
 
72
  unit_cost = np.clip(rng.normal(base_c, 4), 10, None)
73
 
 
74
  eps = np.array([seg_epsilon[(pp, rr, cc)] for pp, rr, cc in zip(prod, reg, ch)])
75
  ref_price = np.array([base_price[x] for x in prod])
76
  qty_mu = np.exp(eps * (net_price - ref_price) / np.maximum(ref_price, 1e-6))
 
98
  "gm_pct": float(gm_pct[i]),
99
  "dow": dow
100
  })
101
+ return pd.DataFrame(records)
 
102
 
103
  # -----------------------------
104
  # 2) Modeling utilities
105
  # -----------------------------
106
+ def build_features(df):
107
  feats_num = ["net_price", "unit_cost", "qty", "discount_pct", "list_price", "dow"]
108
  feats_cat = ["product", "region", "channel"]
109
 
 
117
  df["roll7_cost"] = df.groupby(seg)["cost_per_unit"].transform(lambda s: s.rolling(7, min_periods=1).median())
118
 
119
  feats_num += ["price_per_unit", "cost_per_unit", "roll7_qty", "roll7_price", "roll7_cost"]
120
+ return df, feats_num, feats_cat, "gm_pct"
 
121
 
122
  @st.cache_resource(show_spinner=False)
123
+ def train_model(df, feats_num, feats_cat, target, n_estimators=250):
124
  X = df[feats_num + feats_cat]
125
  y = df[target]
126
+ pre = ColumnTransformer([
127
+ ("cat", OneHotEncoder(handle_unknown="ignore"), feats_cat),
128
+ ("num", "passthrough", feats_num),
129
+ ])
130
+ model = RandomForestRegressor(n_estimators=n_estimators, random_state=42, n_jobs=-1, min_samples_leaf=3)
 
 
 
131
  pipe = Pipeline([("pre", pre), ("rf", model)])
 
132
  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, shuffle=False)
133
  pipe.fit(X_train, y_train)
134
  pred = pipe.predict(X_test)
135
+ return pipe, {"r2": r2_score(y_test, pred), "mae": mean_absolute_error(y_test, pred)}, X_test
 
 
 
 
 
136
 
137
  @st.cache_resource(show_spinner=False)
138
+ def compute_shap(_pipe, X_sample, feats_num, feats_cat, shap_sample=800, seed=42):
139
  np.random.seed(seed)
140
+ preproc = _pipe.named_steps["pre"]
141
+ rf = _pipe.named_steps["rf"]
142
  feature_names = list(preproc.named_transformers_["cat"].get_feature_names_out(feats_cat)) + feats_num
143
 
144
  if len(X_sample) > shap_sample:
145
+ X_sample = X_sample.sample(shap_sample, random_state=seed)
 
 
146
  X_t = preproc.transform(X_sample)
147
  try:
148
  X_t = X_t.toarray()
149
  except Exception:
150
  pass
 
151
  explainer = shap.TreeExplainer(rf)
152
  shap_values = explainer.shap_values(X_t)
153
+ return pd.DataFrame(shap_values, columns=feature_names), explainer.expected_value, X_sample.reset_index(drop=True), feature_names
 
 
 
154
 
155
+ def estimate_segment_elasticity(df, product, region, channel):
156
  seg_df = df[(df["product"]==product)&(df["region"]==region)&(df["channel"]==channel)]
157
+ if len(seg_df) < 100 or seg_df["net_price"].std() < 1e-6:
158
  return -0.5, False
159
  x = np.log(np.clip(seg_df["net_price"].values, 1e-6, None)).reshape(-1,1)
160
  y = np.log(np.clip(seg_df["qty"].values, 1e-6, None))
161
  lin = LinearRegression().fit(x, y)
162
  return float(lin.coef_[0]), True
163
 
164
+ def simulate_action(segment_df, elasticity, delta_discount=0.0, delta_unit_cost=0.0):
165
  if segment_df.empty:
166
  return None
167
  base = segment_df.iloc[-1]
168
+ p0, c0, q0, d0 = base["net_price"], base["unit_cost"], base["qty"], base["discount_pct"]
 
 
 
 
169
  new_discount = np.clip(d0 + delta_discount, 0.0, 0.45)
170
  p1 = max(0.01, base["list_price"] * (1 - new_discount))
171
  c1 = max(0.01, c0 + delta_unit_cost)
172
+ q1 = q0 if p0 <= 0 else max(0.0, q0 * (p1 / p0) ** elasticity)
173
+ rev0, rev1 = p0*q0, p1*q1
174
+ cogs0, cogs1 = c0*q0, c1*q1
175
+ gm_delta = (rev1 - cogs1) - (rev0 - cogs0)
 
 
 
 
 
 
 
 
 
 
176
  return {
177
+ "gm_delta_value": gm_delta,
178
+ "gm0_pct": (rev0 - cogs0)/rev0 if rev0>0 else 0,
179
+ "gm1_pct": (rev1 - cogs1)/rev1 if rev1>0 else 0,
180
+ "new_discount": new_discount,
181
  "baseline_price": p0, "new_price": p1,
182
  "baseline_cost": c0, "new_cost": c1,
183
  "baseline_qty": q0, "new_qty": q1,
 
 
 
184
  }
185
 
186
  # -----------------------------
187
  # 3) UI
188
  # -----------------------------
189
  st.title("📈 AI-Driven Daily Gross Margin — Analysis & What-if Simulator")
 
 
190
  with st.sidebar:
191
  st.header("⚙️ Controls")
192
+ fast_mode = st.toggle("Fast mode", value=True)
193
+ days = 60 if fast_mode else 90
194
+ rows_per_day = 600 if fast_mode else 1200
195
+ seed = 42
196
+ n_trees = 250 if fast_mode else 400
197
+ shap_sample = 800 if fast_mode else 1800
198
+
199
+ df = generate_synthetic_data(days, seed, rows_per_day)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  df_feat, feats_num, feats_cat, target = build_features(df)
201
 
202
  # KPI panel
203
  daily = df.groupby("date").agg(revenue=("revenue","sum"), cogs=("cogs","sum"), gm_value=("gm_value","sum")).reset_index()
204
+ daily["gm_pct"] = daily["gm_value"]/daily["revenue"]
205
  today_row = daily.iloc[-1]
206
+ st.metric("GM% (today)", f"{today_row['gm_pct']*100:.2f}%")
 
 
 
 
 
 
 
 
207
 
208
+ # Train model
209
+ pipe, metrics, X_test = train_model(df_feat, feats_num, feats_cat, target, n_estimators=n_trees)
210
+ st.success(f"Model trained R²={metrics['r2']:.3f} • MAE={metrics['mae']:.4f}")
211
 
212
+ # SHAP compute
213
+ if st.button("Compute / Refresh SHAP drivers"):
214
+ shap_df, expected_value, X_test_sample, feature_names = compute_shap(pipe, X_test, feats_num, feats_cat, shap_sample)
215
+ st.session_state["shap_df"] = shap_df
216
+ st.session_state["X_test_sample"] = X_test_sample
217
+ st.session_state["feature_names"] = feature_names
218
 
219
+ if "shap_df" in st.session_state:
220
+ shap_df = st.session_state["shap_df"]
221
+ mean_abs = shap_df.abs().mean().sort_values(ascending=False)
222
+ st.dataframe(pd.DataFrame({"feature": mean_abs.index, "mean_abs_shap": mean_abs.values}).head(15))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
 
224
+ # What-if simulation
225
  last_day = df["date"].max()
226
+ seg = df[df["date"]==last_day][["product","region","channel"]].drop_duplicates().iloc[0]
227
+ prod_sel, reg_sel, ch_sel = seg
228
+ seg_hist = df[(df["product"]==prod_sel)&(df["region"]==reg_sel)&(df["channel"]==ch_sel)]
229
+ elasticity, _ = estimate_segment_elasticity(seg_hist, prod_sel, reg_sel, ch_sel)
230
+ res = simulate_action(seg_hist, elasticity, delta_discount=-0.015, delta_unit_cost=0.0)
231
+ if res:
232
+ st.write(f"Simulated GM%: {res['gm0_pct']*100:.2f}% → {res['gm1_pct']*100:.2f}% (ΔGM: {res['gm_delta_value']:.2f})")