Upload 8 files
Browse filesFiles changed (9)
- .gitattributes+1
- README.md+44-14
- app.pyAdded+309
- config.jsonAdded+39
- model_a_pipeline.joblibAdded+3
- model_b_pipeline.joblibAdded+3
- payee_profile_store.csvAdded+3
- requirements.txt+7-3
- simulator.pyAdded+184
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textpayee_profile_store.csv filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920---title: Fraud Detection Multi Modelemoji: πcolorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: A Multi-Layer Decision Framework for Real-Time Financial Scalicense: mit---# Welcome to Streamlit!Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950---title: Fraud Detection Multi-Modelemoji: π‘οΈcolorFrom: redcolorTo: bluesdk: streamlitsdk_version: 1.35.0app_file: app.pypinned: true---# Fraud Detection β Multi-Model Live MonitorReal-time transaction fraud detection using a 3-layer ensemble pipeline.## Architecture```TransactionββΌLayer 1 β Hard Rulesβ Rule 1: Accessibility + Remote App β Block immediatelyβ Rule 2: Hesitation > 45s + New recipient β bias score β₯ 0.6ββΌLayer 2 β Ensemble Scoringβ Model A (Sender Behavioral): LightGBM / XGBoostβ Model B (Payee Risk Profile): LightGBMβ final_score = 0.3 Γ prob_a + 0.7 Γ prob_bββΌLayer 3 β Threshold Decisionscore β₯ 0.80 β Blockscore β₯ 0.50 β Alert + OTPscore < 0.50 β Pass```## Files required| File | Purpose ||------|---------|| `model_a_pipeline.joblib` | Sender behavioral model || `model_b_pipeline.joblib` | Payee risk profile model || `config.json` | Feature list, weights, thresholds || `payee_profile_store.csv` | Historical payee lookup table |## GitHub[Fraud-Detection-Multi-Model](https://github.com/PlamGG/Fraud-Detection-Multi-Model-)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309import timeimport randomimport streamlit as stfrom simulator import generate_accounts, generate_transaction, score_transaction
# βββ Page config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββst.set_page_config( page_title="Fraud Detection β Multi-Model", page_icon="π‘οΈ", layout="wide", initial_sidebar_state="expanded",)
# βββ Styling ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββst.markdown("""<style>/* Feed card base */.tx-card { padding: 10px 14px; border-radius: 8px; border: 0.5px solid #e2e8f0; margin-bottom: 6px; background: #ffffff; font-size: 13px;}.tx-card.fraud { border-left: 3px solid #ef4444; background: #fff5f5; }.tx-card.alert { border-left: 3px solid #f59e0b; background: #fffbeb; }.tx-card.rule1 { border-left: 3px solid #8b5cf6; background: #f5f3ff; }.tx-card.pass { border-left: 3px solid #22c55e; background: #f0fdf4; }
.badge { display: inline-block; font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 100px; margin-right: 4px;}.badge-block { background:#ef4444; color:#fff; }.badge-alert { background:#f59e0b; color:#fff; }.badge-rule1 { background:#8b5cf6; color:#fff; }.badge-pass { background:#22c55e; color:#fff; }
.score-row { font-size: 11px; color: #64748b; margin-top: 4px; }.tx-meta { font-size: 11px; color: #94a3b8; margin-top: 2px; }
.alert-card { padding: 10px 12px; border-radius: 8px; border: 0.5px solid; margin-bottom: 8px; font-size: 12px;}.alert-card.block { border-color:#ef4444; background:#fff5f5; }.alert-card.otp { border-color:#f59e0b; background:#fffbeb; }.alert-card.rule { border-color:#8b5cf6; background:#f5f3ff; }
/* KPI strip */.kpi-val { font-size: 28px; font-weight: 600; }.kpi-lbl { font-size: 12px; color: #64748b; }</style>""", unsafe_allow_html=True)
# βββ Session state init βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _init(): st.session_state.setdefault("running", False) st.session_state.setdefault("accounts", []) st.session_state.setdefault("feed", []) # list of scored tx dicts st.session_state.setdefault("alerts", []) # fraud/alert only st.session_state.setdefault("step", 1) st.session_state.setdefault("tx_counter", 1) st.session_state.setdefault("total_tx", 0) st.session_state.setdefault("total_block", 0) st.session_state.setdefault("total_alert", 0) st.session_state.setdefault("total_pass", 0) st.session_state.setdefault("amount_risk", 0.0)
_init()
# βββ Sidebar ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββwith st.sidebar: st.markdown("### Fraud Detection\n**Multi-Model System**") st.caption("Sender Γ Payee ensemble Β· 3-layer pipeline") st.divider()
speed = st.slider("Speed (seconds / transaction)", 0.3, 3.0, 1.0, 0.1) fraud_pct = st.slider("High-risk account ratio (%)", 5, 40, 12, 1) n_accs = st.slider("Accounts to monitor", 3, 8, 5, 1)
st.divider()
col1, col2 = st.columns(2) start_btn = col1.button("βΆ Start", use_container_width=True, type="primary") stop_btn = col2.button("βΉ Stop", use_container_width=True) reset_btn = st.button("βΊ Reset session", use_container_width=True)
if start_btn: seed = random.randint(0, 99999) st.session_state.accounts = generate_accounts(n=n_accs, seed=seed) st.session_state.running = True st.session_state.feed = [] st.session_state.alerts = [] st.session_state.step = 1 st.session_state.tx_counter = 1 st.session_state.total_tx = 0 st.session_state.total_block = 0 st.session_state.total_alert = 0 st.session_state.total_pass = 0 st.session_state.amount_risk = 0.0
if stop_btn: st.session_state.running = False
if reset_btn: for k in ["running","accounts","feed","alerts","step","tx_counter", "total_tx","total_block","total_alert","total_pass","amount_risk"]: st.session_state.pop(k, None) _init() st.rerun()
st.divider() st.markdown("**Thresholds**") st.markdown("π΄ Block `β₯ 0.80` \nπ‘ Alert+OTP `β₯ 0.50` \nπ’ Pass `< 0.50`")
st.divider() st.markdown("**Accounts**") for acc in st.session_state.accounts: icon = {"normal": "π’", "alert": "π‘", "blocked": "π΄"}.get(acc["status"], "βͺ") risk_tag = {"low": "", "medium": " β οΈ", "high": " π₯"}.get(acc["risk_level"], "") st.caption(f"{icon} `{acc['account_id']}` {acc['risk_level']}{risk_tag}")
st.divider() st.link_button( "GitHub β Fraud-Detection-Multi-Model", "https://github.com/PlamGG/Fraud-Detection-Multi-Model-", use_container_width=True, )
# βββ Main header βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββst.markdown("## Fraud Detection β Multi-Model Β· Live Monitor")status_txt = "π’ Running" if st.session_state.running else "βΈ Paused"st.caption(f"{status_txt} Β· Model version 2026-05-24 Β· w\\* = 0.30 Β· Ensemble: Model A Γ Model B")
# βββ KPI strip βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββk1, k2, k3, k4, k5 = st.columns(5)k1.metric("Total transactions", st.session_state.total_tx)k2.metric("Blocked", st.session_state.total_block, delta=None)k3.metric("Alert+OTP", st.session_state.total_alert, delta=None)k4.metric("Passed", st.session_state.total_pass, delta=None)k5.metric("Amount at risk (ΰΈΏ)", f"{st.session_state.amount_risk:,.0f}")
st.divider()
# βββ Two-column layout ββββββββββββββββββββββββββββββββββββββββββββββββββββββββfeed_col, alert_col = st.columns([3, 2], gap="medium")
feed_placeholder = feed_col.empty()alert_placeholder = alert_col.empty()
# βββ Render helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _decision_class(tx: dict) -> str: d = tx["decision"] if "Rule" in d: return "rule1" if "Block" in d: return "fraud" if "Alert" in d: return "alert" return "pass"
def _badge(tx: dict) -> str: d = tx["decision"] if "Rule" in d: return '<span class="badge badge-rule1">Rule 1</span>' if "Block" in d: return '<span class="badge badge-block">Block</span>' if "Alert" in d: return '<span class="badge badge-alert">Alert+OTP</span>' return '<span class="badge badge-pass">Pass</span>'
def render_feed(feed: list): html = "" for tx in feed[:40]: cls = _decision_class(tx) badge = _badge(tx) score_color = ( "#ef4444" if tx["final_score"] >= 0.8 else "#f59e0b" if tx["final_score"] >= 0.5 else "#22c55e" ) flags = [] if tx["rule1"]: flags.append("Accessibility+Remote") if tx["rule2"]: flags.append("Hesitation+NewRecipient") flag_txt = " Β· ".join(flags) if flags else "No hard rule"
html += f"""<div class="tx-card {cls}"> <div style="display:flex;justify-content:space-between;align-items:center"> <div>{badge} <strong>{tx['tx_id']}</strong></div> <div style="font-weight:600">ΰΈΏ {tx['amount']:,.0f}</div> </div> <div class="tx-meta">{tx['account_id']} β {tx['dest_id']} Β· step {tx['step']}</div> <div class="score-row"> Model A: <b>{tx['prob_a']:.3f}</b> Model B: <b>{tx['prob_b']:.3f}</b> Score: <b style="color:{score_color}">{tx['final_score']:.3f}</b> Β· {flag_txt} </div></div>""" return html
def render_alerts(alerts: list): html = "" for tx in alerts[:25]: d = tx["decision"] if "Rule" in d: cls, label = "rule", "Rule 1 β Hard Block" detail = "Accessibility Service + Remote Access Application both active. Blocked before ML scoring." elif "Block" in d: cls, label = "block", "Block" detail = f"Ensemble score {tx['final_score']:.3f} β₯ 0.80. Model A={tx['prob_a']:.3f} Β· Model B={tx['prob_b']:.3f}." else: cls, label = "otp", "Alert + OTP" detail = f"Score {tx['final_score']:.3f} β₯ 0.50. OTP challenge triggered."
html += f"""<div class="alert-card {cls}"> <div style="display:flex;align-items:center;gap:6px;margin-bottom:4px"> <span class="badge badge-{'rule1' if cls=='rule' else cls}">{label}</span> <strong style="font-size:12px">{tx['tx_id']} Β· {tx['account_id']}</strong> </div> <div style="font-size:11px;color:#374151">{detail}</div> <div style="font-size:10px;color:#94a3b8;margin-top:3px"> ΰΈΏ {tx['amount']:,.0f} Β· step {tx['step']} Β· {tx['layer']} </div></div>""" return html
# βββ Simulation loop ββββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββif st.session_state.running and st.session_state.accounts: while st.session_state.running: # Pick a random account account = random.choice(st.session_state.accounts)
# Generate + score raw_tx = generate_transaction( account, step=st.session_state.step, tx_counter=st.session_state.tx_counter, ) tx = score_transaction(raw_tx)
# Update account status d = tx["decision"] if "Block" in d: account["status"] = "blocked" elif "Alert" in d: account["status"] = "alert"
# Prepend to feed (newest first) st.session_state.feed = [tx] + st.session_state.feed st.session_state.total_tx += 1 st.session_state.tx_counter += 1
if "Block" in d: st.session_state.total_block += 1 st.session_state.alerts = [tx] + st.session_state.alerts st.session_state.amount_risk += tx["amount"] elif "Alert" in d: st.session_state.total_alert += 1 st.session_state.alerts = [tx] + st.session_state.alerts st.session_state.amount_risk += tx["amount"] * 0.5 else: st.session_state.total_pass += 1
# Advance step every 6 transactions if st.session_state.tx_counter % 6 == 0: st.session_state.step += 1
# Render with feed_placeholder.container(): st.markdown("#### Transaction feed") st.caption("Newest first Β· showing last 40") st.markdown(render_feed(st.session_state.feed), unsafe_allow_html=True)
with alert_placeholder.container(): n_alerts = len(st.session_state.alerts) st.markdown(f"#### Alerts ({n_alerts})") st.caption("Ordered by detection time") if st.session_state.alerts: st.markdown(render_alerts(st.session_state.alerts), unsafe_allow_html=True) else: st.info("No alerts yet.")
time.sleep(speed)
else: # Static render when not running with feed_placeholder.container(): st.markdown("#### Transaction feed") if st.session_state.feed: st.markdown(render_feed(st.session_state.feed), unsafe_allow_html=True) else: st.info("Press **βΆ Start** in the sidebar to begin the simulation.")
with alert_placeholder.container(): st.markdown(f"#### Alerts ({len(st.session_state.alerts)})") if st.session_state.alerts: st.markdown(render_alerts(st.session_state.alerts), unsafe_allow_html=True) else: st.info("No alerts yet.")123456789101112131415161718192021222324252627282930313233343536373839{ "model_version": "2026-05-27", "optimal_weight": 0.1, "feature_list": { "model_a": [ "is_accessibility_enabled", "is_remote_app_running", "hesitation_time_sec", "tx_count_per_step", "dest_tx_count_24step", "amount_vs_avg_ratio", "is_odd_hours", "is_first_time_recipient" ], "model_b": [ "dest_is_new_account", "is_accessibility_enabled", "is_remote_app_running", "is_first_time_recipient", "is_odd_hours", "dest_cashout_ratio", "dest_avg_step_to_cashout", "dest_tx_count_received", "hesitation_time_sec", "amount_vs_avg_ratio", "tx_count_per_step", "dest_tx_count_24step" ] }, "threshold_layer3": { "block": 0.8, "alert_otp": 0.5, "pass": 0.0 }, "hard_rules": { "rule1_bot": "is_accessibility_enabled=1 AND is_remote_app_running=1 β Block", "rule2_victim": "hesitation_time_sec>45 AND is_first_time_recipient=1 β bias score >= 0.6" }}123version https://git-lfs.github.com/spec/v1oid sha256:e48106ff1e7ac90863e130113c526d54de5fceb62a2e5036b01ef38e1f22054esize 1050966123version https://git-lfs.github.com/spec/v1oid sha256:6ed236d7dfe4f86c498435f904f0ad8da4342ff6b82489f1ae66b66ada81cb44size 1062518123version https://git-lfs.github.com/spec/v1oid sha256:3610d403f3db7f6cad09bc99d9794ffabe76910d1099279cc1e1f3f768e0ad7fsize 75385099123altairpandasstreamlit1234567streamlit==1.35.0pandas==2.2.2numpy==1.26.4scikit-learn==1.5.0lightgbm==4.3.0xgboost==2.0.3joblib==1.4.2
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184import numpy as npimport pandas as pdimport randomimport stringimport jsonimport joblibfrom pathlib import Path
# βββ Load artifacts βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββBASE = Path(__file__).parent
with open(BASE / "config.json") as f: CONFIG = json.load(f)
W_STAR = CONFIG["optimal_weight"] # 0.3THR_BLOCK = CONFIG["threshold_layer3"]["block"] # 0.8THR_ALERT = CONFIG["threshold_layer3"]["alert_otp"] # 0.5FEAT_A = CONFIG["feature_list"]["model_a"]FEAT_B = CONFIG["feature_list"]["model_b"]
MODEL_A = joblib.load(BASE / "model_a_pipeline.joblib")MODEL_B = joblib.load(BASE / "model_b_pipeline.joblib")
PAYEE_PROFILE = pd.read_csv(BASE / "payee_profile_store.csv")# Normalise column name β support both 'mule_account_id' and 'nameDest'_id_col = "mule_account_id" if "mule_account_id" in PAYEE_PROFILE.columns else PAYEE_PROFILE.columns[0]PAYEE_PROFILE = PAYEE_PROFILE.set_index(_id_col)
# βββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _rand_id(prefix: str, n: int = 4) -> str: return prefix + "".join(random.choices(string.digits, k=n))
def generate_accounts(n: int = 5, seed: int = None) -> list[dict]: """ Create n random sender accounts with a risk profile each. Called once per simulation session. """ if seed is not None: random.seed(seed) np.random.seed(seed)
profiles = [] for _ in range(n): risk = random.choices( ["low", "medium", "high"], weights=[0.60, 0.28, 0.12] )[0] profiles.append( { "account_id": _rand_id("ACC-"), "risk_level": risk, "balance": round(random.uniform(5_000, 500_000), 2), "avg_tx_amount": round(random.uniform(1_000, 80_000), 2), "tx_history_steps": random.randint(50, 400), "accessibility_prob": {"low": 0.04, "medium": 0.15, "high": 0.55}[risk], "remote_app_prob": {"low": 0.02, "medium": 0.08, "high": 0.40}[risk], "status": "normal", } ) return profiles
def _lookup_payee(dest_id: str) -> dict: """Return payee profile row or cold-start defaults.""" if dest_id in PAYEE_PROFILE.index: row = PAYEE_PROFILE.loc[dest_id] return { "dest_cashout_ratio": float(row.get("dest_cashout_ratio", 0.0)), "dest_avg_step_to_cashout": float(row.get("dest_avg_step_to_cashout", 0.0)), "dest_tx_count_received": float(row.get("dest_tx_count_received", 0.0)), "dest_is_new_account": int(row.get("dest_is_new_account", 1)), } return { "dest_cashout_ratio": 0.0, "dest_avg_step_to_cashout": 0.0, "dest_tx_count_received": 0.0, "dest_is_new_account": 1, }
def generate_transaction(account: dict, step: int, tx_counter: int) -> dict: """ Simulate one TRANSFER transaction for the given account. Returns a feature dict ready for model scoring. """ risk = account["risk_level"] avg = account["avg_tx_amount"]
# Device signals is_acc = int(random.random() < account["accessibility_prob"]) is_rem = int(random.random() < account["remote_app_prob"]) hesit = round(np.clip(np.random.lognormal(3.2 if risk == "low" else 4.0, 0.9), 5, 300), 1)
# Velocity features tx_count_per_step = max(1, int(np.random.poisson(2 if risk == "low" else 4))) dest_tx_count_24step = max(0, int(np.random.poisson(1 if risk == "low" else 3)))
# Amount anomaly multiplier = np.random.lognormal(0, 0.4) if risk == "low" else np.random.lognormal(0.8, 0.9) amount = round(avg * multiplier, 2) amount_vs_avg_ratio = round(amount / avg, 4)
# Temporal hour = random.randint(0, 23) is_odd_hours = int(hour < 6 or hour >= 22)
# Recipient is_first_time = int(random.random() < (0.10 if risk == "low" else 0.45))
# Pick a payee β sometimes from profile store, sometimes new if random.random() < 0.3 and len(PAYEE_PROFILE) > 0: dest_id = random.choice(PAYEE_PROFILE.index.tolist()) else: dest_id = _rand_id("C", 6)
payee = _lookup_payee(dest_id)
return { "tx_id": f"TX-{tx_counter:05d}", "step": step, "account_id": account["account_id"], "dest_id": dest_id, "amount": amount, "hour": hour, # Model A features "is_accessibility_enabled": is_acc, "is_remote_app_running": is_rem, "hesitation_time_sec": hesit, "tx_count_per_step": tx_count_per_step, "dest_tx_count_24step": dest_tx_count_24step, "amount_vs_avg_ratio": amount_vs_avg_ratio, "is_odd_hours": is_odd_hours, "is_first_time_recipient": is_first_time, # Model B features (payee profile) **payee, }
def score_transaction(tx: dict) -> dict: """ Run 3-layer scoring pipeline on a single transaction dict. Returns tx enriched with scores and decision. """ row_a = pd.DataFrame([{f: tx[f] for f in FEAT_A}]) row_b = pd.DataFrame([{f: tx[f] for f in FEAT_B}])
prob_a = float(MODEL_A.predict_proba(row_a)[0, 1]) prob_b = float(MODEL_B.predict_proba(row_b)[0, 1])
# Layer 1 β Hard Rules rule1 = tx["is_accessibility_enabled"] == 1 and tx["is_remote_app_running"] == 1 rule2 = tx["hesitation_time_sec"] > 45 and tx["is_first_time_recipient"] == 1
# Ensemble score final_score = W_STAR * prob_a + (1 - W_STAR) * prob_b
# Rule 2 bias if rule2: final_score = max(final_score, 0.6)
# Layer 3 β Threshold decision if rule1: decision = "Block (Rule 1)" layer = "Layer 1" elif final_score >= THR_BLOCK: decision = "Block" layer = "Layer 3" elif final_score >= THR_ALERT: decision = "Alert + OTP" layer = "Layer 3" else: decision = "Pass" layer = "Layer 3"
return { **tx, "prob_a": round(prob_a, 4), "prob_b": round(prob_b, 4), "final_score": round(final_score, 4), "rule1": rule1, "rule2": rule2, "decision": decision, "layer": layer, }.gitattributes+1
README.md+44-14
app.pyAdded+309
config.jsonAdded+39
model_a_pipeline.joblibAdded+3
model_b_pipeline.joblibAdded+3
payee_profile_store.csvAdded+3
requirements.txt+7-3
simulator.pyAdded+184