# app.py # Interactive MF churn explorer — Plotly graph with node click-to-focus # + Legend # + Fixed JS (labels hide properly) # + Mobile-friendly # + HF iframe safe import gradio as gr import pandas as pd import networkx as nx import plotly.graph_objects as go import numpy as np import json from collections import defaultdict # ============================================================ # DATA # ============================================================ AMCS = [ "SBI MF", "ICICI Pru MF", "HDFC MF", "Nippon India MF", "Kotak MF", "UTI MF", "Axis MF", "Aditya Birla SL MF", "Mirae MF", "DSP MF" ] COMPANIES = [ "HDFC Bank", "ICICI Bank", "Bajaj Finance", "Bajaj Finserv", "Adani Ports", "Tata Motors", "Shriram Finance", "HAL", "TCS", "AU Small Finance Bank", "Pearl Global", "Hindalco", "Tata Elxsi", "Cummins India", "Vedanta" ] BUY_MAP = { "SBI MF": ["Bajaj Finance", "AU Small Finance Bank"], "ICICI Pru MF": ["HDFC Bank"], "HDFC MF": ["Tata Elxsi", "TCS"], "Nippon India MF": ["Hindalco"], "Kotak MF": ["Bajaj Finance"], "UTI MF": ["Adani Ports", "Shriram Finance"], "Axis MF": ["Tata Motors", "Shriram Finance"], "Aditya Birla SL MF": ["AU Small Finance Bank"], "Mirae MF": ["Bajaj Finance", "HAL"], "DSP MF": ["Tata Motors", "Bajaj Finserv"] } SELL_MAP = { "SBI MF": ["Tata Motors"], "ICICI Pru MF": ["Bajaj Finance", "Adani Ports"], "HDFC MF": ["HDFC Bank"], "Nippon India MF": ["Hindalco"], "Kotak MF": ["AU Small Finance Bank"], "UTI MF": ["Hindalco", "TCS"], "Axis MF": ["TCS"], "Aditya Birla SL MF": ["Adani Ports"], "Mirae MF": ["TCS"], "DSP MF": ["HAL", "Shriram Finance"] } COMPLETE_EXIT = {"DSP MF": ["Shriram Finance"]} FRESH_BUY = {"HDFC MF": ["Tata Elxsi"], "UTI MF": ["Adani Ports"], "Mirae MF": ["HAL"]} def sanitize_map(m): out = {} for k, vals in m.items(): out[k] = [v for v in vals if v in COMPANIES] return out BUY_MAP = sanitize_map(BUY_MAP) SELL_MAP = sanitize_map(SELL_MAP) COMPLETE_EXIT = sanitize_map(COMPLETE_EXIT) FRESH_BUY = sanitize_map(FRESH_BUY) # ============================================================ # GRAPH BUILDING # ============================================================ company_edges = [] for amc, comps in BUY_MAP.items(): for c in comps: company_edges.append((amc, c, {"action": "buy", "weight": 1})) for amc, comps in SELL_MAP.items(): for c in comps: company_edges.append((amc, c, {"action": "sell", "weight": 1})) for amc, comps in COMPLETE_EXIT.items(): for c in comps: company_edges.append((amc, c, {"action": "complete_exit", "weight": 3})) for amc, comps in FRESH_BUY.items(): for c in comps: company_edges.append((amc, c, {"action": "fresh_buy", "weight": 3})) def infer_amc_transfers(buy_map, sell_map): transfers = defaultdict(int) c2s = defaultdict(list) c2b = defaultdict(list) for amc, comps in sell_map.items(): for c in comps: c2s[c].append(amc) for amc, comps in buy_map.items(): for c in comps: c2b[c].append(amc) for c in set(c2s.keys()) | set(c2b.keys()): for s in c2s[c]: for b in c2b[c]: transfers[(s, b)] += 1 output = [] for (s, b), w in transfers.items(): output.append((s, b, {"action": "transfer", "weight": w})) return output transfer_edges = infer_amc_transfers(BUY_MAP, SELL_MAP) def build_graph(include_transfers=True): G = nx.DiGraph() for a in AMCS: G.add_node(a, type="amc") for c in COMPANIES: G.add_node(c, type="company") # company edges for u, v, attr in company_edges: if G.has_edge(u, v): G[u][v]["weight"] += attr["weight"] G[u][v]["actions"].append(attr["action"]) else: G.add_edge(u, v, weight=attr["weight"], actions=[attr["action"]]) # inferred transfer edges if include_transfers: for s, b, attr in transfer_edges: if G.has_edge(s, b): G[s][b]["weight"] += attr["weight"] G[s][b]["actions"].append("transfer") else: G.add_edge(s, b, weight=attr["weight"], actions=["transfer"]) return G # ============================================================ # PLOTLY FIGURE # ============================================================ def build_plotly_figure( G, node_color_amc="#9EC5FF", node_color_company="#FFCF9E", edge_color_buy="#2ca02c", edge_color_sell="#d62728", edge_color_transfer="#888888", edge_thickness_base=1.4 ): pos = nx.spring_layout(G, seed=42, k=1.2) node_names = [] node_x = [] node_y = [] node_color = [] node_size = [] for n, d in G.nodes(data=True): node_names.append(n) x, y = pos[n] node_x.append(x) node_y.append(y) if d["type"] == "amc": node_color.append(node_color_amc) node_size.append(36) else: node_color.append(node_color_company) node_size.append(56) edge_traces = [] edge_source = [] edge_target = [] edge_colors = [] edge_widths = [] for u, v, attrs in G.edges(data=True): x0, y0 = pos[u] x1, y1 = pos[v] acts = attrs["actions"] weight = attrs["weight"] if "complete_exit" in acts: color = edge_color_sell width = edge_thickness_base * 3 dash = "solid" elif "fresh_buy" in acts: color = edge_color_buy width = edge_thickness_base * 3 dash = "solid" elif "transfer" in acts: color = edge_color_transfer width = edge_thickness_base * (1 + np.log1p(weight)) dash = "dash" elif "sell" in acts: color = edge_color_sell width = edge_thickness_base * (1 + np.log1p(weight)) dash = "dot" else: color = edge_color_buy width = edge_thickness_base * (1 + np.log1p(weight)) dash = "solid" edge_traces.append( go.Scatter( x=[x0, x1], y=[y0, y1], mode="lines", line=dict(color=color, width=width, dash=dash), hoverinfo="none", opacity=1.0 ) ) edge_source.append(node_names.index(u)) edge_target.append(node_names.index(v)) edge_colors.append(color) edge_widths.append(width) node_trace = go.Scatter( x=node_x, y=node_y, mode="markers+text", marker=dict(color=node_color, size=node_size, line=dict(width=2, color="#333")), text=node_names, textposition="top center", hoverinfo="text" ) fig = go.Figure(data=edge_traces + [node_trace]) fig.update_layout( showlegend=False, autosize=True, margin=dict(l=8, r=8, t=36, b=8), xaxis=dict(visible=False), yaxis=dict(visible=False) ) meta = { "node_names": node_names, "edge_source_index": edge_source, "edge_target_index": edge_target, "edge_colors": edge_colors, "edge_widths": edge_widths } return fig, meta # ================= PART 2 / 3 ================= # HTML builder and JS (with escaped braces for f-string) def make_network_html(fig, meta, div_id="network-plot-div"): fig_json = json.dumps(fig.to_plotly_json()) meta_json = json.dumps(meta) html = f"""