Spaces:
Sleeping
Sleeping
| # app.py | |
| # Interactive MF churn explorer | |
| # - Chart is client-side interactive: clicking a node hides everything except that node + its neighbors (Option A) | |
| # - AMC/company inspect sections remain unchanged | |
| # Requirements: gradio, networkx, plotly, pandas, numpy | |
| 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 | |
| # --------------------------- | |
| # Sample dataset (same as before) | |
| # --------------------------- | |
| 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) | |
| # --------------------------- | |
| # Build edges & infer transfers | |
| # --------------------------- | |
| 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) | |
| company_to_sellers = defaultdict(list) | |
| company_to_buyers = defaultdict(list) | |
| for amc, comps in sell_map.items(): | |
| for c in comps: | |
| company_to_sellers[c].append(amc) | |
| for amc, comps in buy_map.items(): | |
| for c in comps: | |
| company_to_buyers[c].append(amc) | |
| for c in set(company_to_sellers.keys()) | set(company_to_buyers.keys()): | |
| sellers = company_to_sellers[c] | |
| buyers = company_to_buyers[c] | |
| for s in sellers: | |
| for b in buyers: | |
| transfers[(s, b)] += 1 | |
| edge_list = [] | |
| for (s, b), w in transfers.items(): | |
| edge_list.append((s, b, {"action": "transfer", "weight": w})) | |
| return edge_list | |
| 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") | |
| for u, v, attr in company_edges: | |
| if u in G.nodes and v in G.nodes: | |
| 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"]]) | |
| if include_transfers: | |
| for s, b, attr in transfer_edges: | |
| if s in G.nodes and b in G.nodes: | |
| 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 | |
| # --------------------------- | |
| # Build Plotly figure (Python-side) | |
| # --------------------------- | |
| 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, | |
| show_labels=True): | |
| 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) | |
| # edges: one trace per edge to allow individual styling in JS | |
| edge_traces = [] | |
| edge_source_index = [] | |
| edge_target_index = [] | |
| edge_colors = [] | |
| edge_widths = [] | |
| for u, v, attrs in G.edges(data=True): | |
| x0, y0 = pos[u]; x1, y1 = pos[v] | |
| acts = attrs.get("actions", []) | |
| weight = attrs.get("weight", 1) | |
| if "complete_exit" in acts: | |
| color = edge_color_sell; dash = "solid"; width = edge_thickness_base * 3 | |
| elif "fresh_buy" in acts: | |
| color = edge_color_buy; dash = "solid"; width = edge_thickness_base * 3 | |
| elif "transfer" in acts: | |
| color = edge_color_transfer; dash = "dash"; width = edge_thickness_base * (1 + np.log1p(weight)) | |
| elif "sell" in acts: | |
| color = edge_color_sell; dash = "dot"; width = edge_thickness_base * (1 + np.log1p(weight)) | |
| else: | |
| color = edge_color_buy; dash = "solid"; width = edge_thickness_base * (1 + np.log1p(weight)) | |
| # create trace for this edge | |
| 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_index.append(node_names.index(u)) | |
| edge_target_index.append(node_names.index(v)) | |
| edge_colors.append(color) | |
| edge_widths.append(width) | |
| # single node trace | |
| node_trace = go.Scatter( | |
| x=node_x, y=node_y, | |
| mode="markers+text" if show_labels else "markers", | |
| marker=dict(color=node_color, size=node_size, line=dict(width=2, color="#222")), | |
| text=node_names if show_labels else None, | |
| textposition="top center", | |
| hoverinfo="text" | |
| ) | |
| # assemble traces: edges first, nodes last | |
| 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) | |
| ) | |
| # We package helper arrays for JS (node names, edge source/target indices, original edge colors/widths) | |
| meta = { | |
| "node_names": node_names, | |
| "edge_source_index": edge_source_index, | |
| "edge_target_index": edge_target_index, | |
| "edge_colors": edge_colors, | |
| "edge_widths": edge_widths, | |
| "node_colors": node_color, | |
| "node_sizes": node_size | |
| } | |
| return fig, meta | |
| # --------------------------- | |
| # Helper to produce embeddable HTML with JS click handlers | |
| # --------------------------- | |
| def make_network_html(fig, meta, div_id="network-plot-div"): | |
| # serialize plotly figure and metadata | |
| fig_json = fig.to_plotly_json() | |
| fig_json_text = json.dumps(fig_json) # safe to embed | |
| meta_text = json.dumps(meta) | |
| # Build HTML string that: | |
| # - creates a div with id | |
| # - loads Plotly (cdn) | |
| # - creates the plot via Plotly.newPlot | |
| # - sets up click handler that: when a node is clicked, only the node + its neighbors remain visible | |
| # - adds a reset button | |
| html = f""" | |
| <div id="{div_id}" style="width:100%;height:520px;"></div> | |
| <div style="margin-top:6px;margin-bottom:8px;"> | |
| <button id="{div_id}-reset" style="padding:8px 12px;border-radius:6px;">Reset view</button> | |
| </div> | |
| <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> | |
| <script> | |
| const fig = {fig_json_text}; | |
| const meta = {meta_text}; | |
| // create plot | |
| const container = document.getElementById("{div_id}"); | |
| Plotly.newPlot(container, fig.data, fig.layout, {{responsive: true}}); | |
| // identify traces: node trace is last | |
| const nodeTraceIndex = fig.data.length - 1; | |
| const edgeCount = fig.data.length - 1; | |
| // helper: get node name -> index | |
| const nameToIndex = {{}}; | |
| meta.node_names.forEach((n,i) => nameToIndex[n] = i); | |
| // helper: when focusing nodeName, hide all traces/nodes not connected | |
| function focusNode(nodeName) {{ | |
| const idx = nameToIndex[nodeName]; | |
| // neighbors = nodes that are sources or targets with edges to/from idx | |
| const keepSet = new Set([idx]); | |
| for (let e = 0; e < meta.edge_source_index.length; e++) {{ | |
| const s = meta.edge_source_index[e]; | |
| const t = meta.edge_target_index[e]; | |
| if (s === idx) {{ keepSet.add(t); }} | |
| if (t === idx) {{ keepSet.add(s); }} | |
| }} | |
| // Prepare new marker opacity and text visibility arrays for nodes | |
| const nodeCount = meta.node_names.length; | |
| const newMarkerOpacity = Array(nodeCount).fill(0.0); | |
| const newTextOpacity = Array(nodeCount).fill(0.0); | |
| for (let i=0;i<nodeCount;i++) {{ | |
| if (keepSet.has(i)) {{ | |
| newMarkerOpacity[i] = 1.0; | |
| newTextOpacity[i] = 1.0; | |
| }} else {{ | |
| newMarkerOpacity[i] = 0.0; | |
| newTextOpacity[i] = 0.0; | |
| }} | |
| }} | |
| // Update node trace opacity and text via single restyle | |
| Plotly.restyle(container, {{ | |
| 'marker.opacity': [newMarkerOpacity], | |
| 'textfont': [{{'color': ['rgba(0,0,0,0)']}}] // optional - hide text for non-kept | |
| }}, [nodeTraceIndex]); | |
| // Update each edge trace: show only if both ends in keepSet | |
| for (let e=0; e < edgeCount; e++) {{ | |
| const s = meta.edge_source_index[e]; | |
| const t = meta.edge_target_index[e]; | |
| const show = (keepSet.has(s) && keepSet.has(t)); | |
| const color = show ? meta.edge_colors[e] : 'rgba(0,0,0,0)'; | |
| const width = show ? meta.edge_widths[e] : 0.1; | |
| Plotly.restyle(container, {{ | |
| 'line.color': [color], | |
| 'line.width': [width] | |
| }}, [e]); | |
| }} | |
| // Optionally zoom to bounding box of kept nodes | |
| // compute bbox | |
| let xs = [], ys = []; | |
| const nodes = fig.data[nodeTraceIndex]; | |
| for (let j=0;j<meta.node_names.length;j++) {{ | |
| if (keepSet.has(j)) {{ | |
| xs.push(nodes.x[j]); ys.push(nodes.y[j]); | |
| }} | |
| }} | |
| if (xs.length>0) {{ | |
| const xmin = Math.min(...xs), xmax = Math.max(...xs); | |
| const ymin = Math.min(...ys), ymax = Math.max(...ys); | |
| const padX = (xmax - xmin) * 0.4 + 0.1; | |
| const padY = (ymax - ymin) * 0.4 + 0.1; | |
| const newLayout = {{ | |
| xaxis: {{ range: [xmin - padX, xmax + padX] }}, | |
| yaxis: {{ range: [ymin - padY, ymax + padY] }} | |
| }}; | |
| Plotly.relayout(container, newLayout); | |
| }} | |
| }} | |
| // Reset function: restore original colors/widths/opacities | |
| function resetView() {{ | |
| // restore nodes opacity to 1 | |
| const nodeCount = meta.node_names.length; | |
| const fullOpacity = Array(nodeCount).fill(1.0); | |
| Plotly.restyle(container, {{ 'marker.opacity': [fullOpacity] }}, [nodeTraceIndex]); | |
| // restore edge colors and widths | |
| for (let e=0; e < edgeCount; e++) {{ | |
| Plotly.restyle(container, {{ | |
| 'line.color': [meta.edge_colors[e]], | |
| 'line.width': [meta.edge_widths[e]] | |
| }}, [e]); | |
| }} | |
| // restore axes auto-range | |
| Plotly.relayout(container, {{ xaxis: {{autorange: true}}, yaxis: {{autorange: true}} }} ); | |
| }} | |
| // attach click handler on plot: if a node is clicked, focus that node | |
| container.on('plotly_click', function(eventData) {{ | |
| // eventData.points[0].curveNumber is trace index, pointNumber is marker index for node trace | |
| const p = eventData.points[0]; | |
| if (p.curveNumber === nodeTraceIndex) {{ | |
| const nodeIndex = p.pointNumber; | |
| const nodeName = meta.node_names[nodeIndex]; | |
| focusNode(nodeName); | |
| }} | |
| }}); | |
| // attach reset button | |
| document.getElementById("{div_id}-reset").addEventListener('click', function() {{ | |
| resetView(); | |
| }}); | |
| </script> | |
| """ | |
| return html | |
| # --------------------------- | |
| # Company / AMC inspection helpers (unchanged) | |
| # --------------------------- | |
| def company_trade_summary(company_name): | |
| buyers = [a for a, comps in BUY_MAP.items() if company_name in comps] | |
| sellers = [a for a, comps in SELL_MAP.items() if company_name in comps] | |
| fresh = [a for a, comps in FRESH_BUY.items() if company_name in comps] | |
| exits = [a for a, comps in COMPLETE_EXIT.items() if company_name in comps] | |
| df = pd.DataFrame({ | |
| "Role": ["Buyer"] * len(buyers) + ["Seller"] * len(sellers) + ["Fresh buy"] * len(fresh) + ["Complete exit"] * len(exits), | |
| "AMC": buyers + sellers + fresh + exits | |
| }) | |
| if df.empty: | |
| return None, pd.DataFrame([], columns=["Role", "AMC"]) | |
| counts = df.groupby("Role").size().reset_index(name="Count") | |
| fig = go.Figure(go.Bar(x=counts["Role"], y=counts["Count"], marker_color=["green", "red", "orange", "black"][:len(counts)])) | |
| fig.update_layout(title_text=f"Trade summary for {company_name}", autosize=True, margin=dict(t=30,b=10)) | |
| return fig, df | |
| def amc_transfer_summary(amc_name): | |
| sold = SELL_MAP.get(amc_name, []) | |
| transfers = [] | |
| for s in sold: | |
| buyers = [a for a, comps in BUY_MAP.items() if s in comps] | |
| for b in buyers: | |
| transfers.append({"security": s, "buyer_amc": b}) | |
| df = pd.DataFrame(transfers) | |
| if df.empty: | |
| return None, pd.DataFrame([], columns=["security", "buyer_amc"]) | |
| counts = df["buyer_amc"].value_counts().reset_index() | |
| counts.columns = ["Buyer AMC", "Count"] | |
| fig = go.Figure(go.Bar(x=counts["Buyer AMC"], y=counts["Count"], marker_color="lightslategray")) | |
| fig.update_layout(title_text=f"Inferred transfers from {amc_name}", autosize=True, margin=dict(t=30,b=10)) | |
| return fig, df | |
| # --------------------------- | |
| # Initial graph HTML (server builds figure & meta, client handles clicks) | |
| # --------------------------- | |
| def build_network_html(node_color_company="#FFCF9E", node_color_amc="#9EC5FF", | |
| edge_color_buy="#2ca02c", edge_color_sell="#d62728", | |
| edge_color_transfer="#888888", edge_thickness=1.4, include_transfers=True): | |
| G = build_graph(include_transfers=include_transfers) | |
| fig, meta = build_plotly_figure(G, | |
| node_color_amc=node_color_amc, | |
| node_color_company=node_color_company, | |
| edge_color_buy=edge_color_buy, | |
| edge_color_sell=edge_color_sell, | |
| edge_color_transfer=edge_color_transfer, | |
| edge_thickness_base=edge_thickness, | |
| show_labels=True) | |
| html = make_network_html(fig, meta, div_id="network-plot-div") | |
| return html | |
| initial_html = build_network_html() | |
| # --------------------------- | |
| # Mobile-friendly CSS (embed) | |
| # --------------------------- | |
| responsive_css = """ | |
| /* remove iframe padding inside HF spaces */ | |
| .gradio-container { padding: 0 !important; margin: 0 !important; } | |
| .plotly-graph-div, .js-plotly-plot, .output_plot { width: 100% !important; max-width: 100% !important; } | |
| .js-plotly-plot { height: 460px !important; } | |
| @media only screen and (max-width: 780px) { | |
| .js-plotly-plot { height: 420px !important; } | |
| } | |
| body, html { overflow-x: hidden !important; } | |
| """ | |
| # --------------------------- | |
| # Gradio UI | |
| # --------------------------- | |
| with gr.Blocks(css=responsive_css, title="MF Churn Explorer (interactive chart)") as demo: | |
| gr.Markdown("## Mutual Fund Churn Explorer — Interactive Chart (click nodes)") | |
| # HTML-based interactive Plotly (client-side click handling) | |
| network_html = gr.HTML(value=initial_html) | |
| # Controls below (unchanged behaviour) | |
| with gr.Accordion("Network Customization — expand to edit", open=False): | |
| node_color_company = gr.ColorPicker("#FFCF9E", label="Company node color") | |
| node_color_amc = gr.ColorPicker("#9EC5FF", label="AMC node color") | |
| edge_color_buy = gr.ColorPicker("#2ca02c", label="BUY edge color") | |
| edge_color_sell = gr.ColorPicker("#d62728", label="SELL edge color") | |
| edge_color_transfer = gr.ColorPicker("#888888", label="Transfer edge color") | |
| edge_thickness = gr.Slider(0.5, 6.0, value=1.4, step=0.1, label="Edge thickness base") | |
| include_transfers = gr.Checkbox(value=True, label="Show AMC→AMC inferred transfers") | |
| update_button = gr.Button("Update Network Graph") | |
| gr.Markdown("### Inspect a Company (buyers / sellers)") | |
| select_company = gr.Dropdown(choices=COMPANIES, label="Select company (buyers / sellers)") | |
| company_out_plot = gr.Plot(label="Company trade summary") | |
| company_out_table = gr.DataFrame(label="Company trade table") | |
| gr.Markdown("### Inspect an AMC (inferred transfers)") | |
| # AMC inspect unchanged; kept for server-side analysis below chart | |
| select_amc = gr.Dropdown(choices=AMCS, label="Select AMC (inferred transfers)") | |
| amc_out_plot = gr.Plot(label="AMC transfer summary") | |
| amc_out_table = gr.DataFrame(label="AMC transfer table") | |
| # --------------------------- | |
| # Callbacks | |
| # --------------------------- | |
| def update_network_html(node_color_company_val, node_color_amc_val, | |
| edge_color_buy_val, edge_color_sell_val, edge_color_transfer_val, | |
| edge_thickness_val, include_transfers_val): | |
| html = build_network_html(node_color_company=node_color_company_val, | |
| node_color_amc=node_color_amc_val, | |
| edge_color_buy=edge_color_buy_val, | |
| edge_color_sell=edge_color_sell_val, | |
| edge_color_transfer=edge_color_transfer_val, | |
| edge_thickness=edge_thickness_val, | |
| include_transfers=include_transfers_val) | |
| return html | |
| def on_company_select(cname): | |
| fig, df = company_trade_summary(cname) | |
| if fig is None: | |
| return None, pd.DataFrame([], columns=["Role", "AMC"]) | |
| return fig, df | |
| def on_amc_select(aname): | |
| fig, df = amc_transfer_summary(aname) | |
| if fig is None: | |
| return None, pd.DataFrame([], columns=["security", "buyer_amc"]) | |
| return fig, df | |
| update_button.click(fn=update_network_html, | |
| inputs=[node_color_company, node_color_amc, | |
| edge_color_buy, edge_color_sell, edge_color_transfer, | |
| edge_thickness, include_transfers], | |
| outputs=[network_html]) | |
| select_company.change(fn=on_company_select, inputs=[select_company], outputs=[company_out_plot, company_out_table]) | |
| select_amc.change(fn=on_amc_select, inputs=[select_amc], outputs=[amc_out_plot, amc_out_table]) | |
| # --------------------------- | |
| # Run | |
| # --------------------------- | |
| if __name__ == "__main__": | |
| demo.launch() | |