Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345674 unmodified lines1213141516171847 unmodified lines6667686970717273747576777879808182838485864 unmodified lines9192939495969798991001011021 unmodified line1041051061071081091101 unmodified line1121131141151161171182 unmodified lines1211221231241251261271281 unmodified line1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343351 unmodified line3373383393403413423433443453463473483493503513523533543553563573583593601 unmodified line3623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044052 unmodified lines4084094104114124134144154164174184194204211 unmodified line4234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564573 unmodified lines4614624634644654664674684694704714724734744754764774784794804814824834844854864879 unmodified lines497498499500501502503504505506507# app.py# Mutual Fund Churn Explorer — Smooth organic motion, short-lived (L1)# D3 + Plotly hybrid layout optimized for phones (simulation stops after ~0.8s)# Works in Hugging Face Spaces (Gradio)import gradio as grimport pandas as pd4 unmodified linesfrom collections import defaultdict# ---------------------------# Data# ---------------------------AMCS = ["SBI MF", "ICICI Pru MF", "HDFC MF", "Nippon India MF", "Kotak MF",47 unmodified linesFRESH_BUY = sanitize_map(FRESH_BUY)# ---------------------------# Graph building & transfer inference# ---------------------------def infer_amc_transfers(buy_map, sell_map):transfers = defaultdict(int)comp_sellers = defaultdict(list)comp_buyers = defaultdict(list)for amc, comps in sell_map.items():for c in comps:comp_sellers[c].append(amc)for amc, comps in buy_map.items():for c in comps:comp_buyers[c].append(amc)for c in set(comp_sellers.keys()) | set(comp_buyers.keys()):for s in comp_sellers[c]:for b in comp_buyers[c]:transfers[(s,b)] += 1out = []for (s,b), w in transfers.items():4 unmodified linesdef 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")# buys and sellsfor amc, comps in BUY_MAP.items():for c in comps:if G.has_edge(amc, c):1 unmodified lineG[amc][c]["actions"].append("buy")else:G.add_edge(amc, c, weight=1, actions=["buy"])for amc, comps in SELL_MAP.items():for c in comps:if G.has_edge(amc, c):1 unmodified lineG[amc][c]["actions"].append("sell")else:G.add_edge(amc, c, weight=1, actions=["sell"])# complete exitsfor amc, comps in COMPLETE_EXIT.items():for c in comps:2 unmodified linesG[amc][c]["actions"].append("complete_exit")else:G.add_edge(amc, c, weight=3, actions=["complete_exit"])# fresh buysfor amc, comps in FRESH_BUY.items():for c in comps:if G.has_edge(amc, c):1 unmodified lineG[amc][c]["actions"].append("fresh_buy")else:G.add_edge(amc, c, weight=3, actions=["fresh_buy"])# inferred transfersif 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# ---------------------------# Build plotly figure (positions are placeholders)# ---------------------------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=1.4):node_names = []node_x = []node_y = []node_colors = []node_sizes = []for n, d in G.nodes(data=True):node_names.append(n)node_x.append(0)node_y.append(0)if d["type"] == "amc":node_colors.append(node_color_amc)node_sizes.append(36)else:node_colors.append(node_color_company)node_sizes.append(56)edge_traces = []src_idx = []tgt_idx = []e_colors = []e_widths = []for u, v, attrs in G.edges(data=True):edge_traces.append(go.Scatter(x=[0,0], y=[0,0], mode="lines",line=dict(color="#aaa", width=1), hoverinfo="none"))src_idx.append(node_names.index(u))tgt_idx.append(node_names.index(v))acts = attrs.get("actions", [])w = attrs.get("weight", 1)if "complete_exit" in acts:e_colors.append(edge_color_sell); e_widths.append(edge_thickness*3)elif "fresh_buy" in acts:e_colors.append(edge_color_buy); e_widths.append(edge_thickness*3)elif "transfer" in acts:e_colors.append(edge_color_transfer); e_widths.append(edge_thickness*(1+np.log1p(w)))elif "sell" in acts:e_colors.append(edge_color_sell); e_widths.append(edge_thickness*(1+np.log1p(w)))else:e_colors.append(edge_color_buy); e_widths.append(edge_thickness*(1+np.log1p(w)))node_trace = go.Scatter(x=node_x, y=node_y, mode="markers+text",marker=dict(color=node_colors, size=node_sizes, 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=5,r=5,t=30,b=5),xaxis=dict(visible=False), yaxis=dict(visible=False))meta = {"node_names": node_names,"edge_source_index": src_idx,"edge_target_index": tgt_idx,"edge_colors": e_colors,"edge_widths": e_widths,"node_sizes": node_sizes}return fig, meta# ---------------------------# HTML maker: D3 + short-lived smooth motion# ---------------------------def make_network_html(fig, meta, div_id="network-plot-div"):fig_json = json.dumps(fig.to_plotly_json())meta_json = json.dumps(meta)# Short-lived simulation parameters:# - run for about 0.8s (or until alpha cools)# - throttle Plotly updates for performancehtml = f"""<div id="{div_id}" style="width:100%; height:560px;"></div><div style="margin-top:6px;"><button id="{div_id}-reset" style="padding:8px 12px; border-radius:6px;">Reset</button><button id="{div_id}-stop" style="padding:8px 12px; margin-left:8px; border-radius:6px;">Stop Layout</button></div><script src="https://d3js.org/d3.v7.min.js"></script><script src="https://cdn.plot.ly/plotly-latest.min.js"></script><script>const fig = {fig_json};const meta = {meta_json};const container = document.getElementById("{div_id}");Plotly.newPlot(container, fig.data, fig.layout, {{responsive:true}});const nodeTraceIndex = fig.data.length - 1;const edgeCount = fig.data.length - 1;// build lightweight nodes and linksconst nodes = meta.node_names.map((name,i) => ({{id: i, name: name, r: meta.node_sizes[i] || 20,displayX: 0, displayY: 0, vx_smooth: 0, vy_smooth: 0}}));const links = meta.edge_source_index.map((s,i) => ({{source: s, target: meta.edge_target_index[i]}}));// Gentle simulation tuned to settle quicklyconst simulation = d3.forceSimulation(nodes).force("link", d3.forceLink(links).id(d => d.id).distance(120).strength(0.32)).force("charge", d3.forceManyBody().strength(-40)).force("collision", d3.forceCollide().radius(d => d.r * 0.9)).force("center", d3.forceCenter(0,0)).velocityDecay(0.48);// Smoothing interpolation factor for organic motionconst interp = 0.16;// Throttle updates to Plotly for performancelet tickCounter = 0;const TICKS_PER_UPDATE = 3; // update Plotly every 3 tickslet frameCount = 0;const MAX_TICKS = 120; // safety cap (~0.8-1.0s depending on device)let stoppedManually = false;simulation.on("tick", () => {{frameCount++;tickCounter++;// apply smooth interpolation (organic)nodes.forEach(n => {{const tx = n.x || 0;const ty = n.y || 0;n.vx_smooth = n.vx_smooth * 0.80 + (tx - n.displayX) * interp;n.vy_smooth = n.vy_smooth * 0.80 + (ty - n.displayY) * interp;// mild dampingn.vx_smooth *= 0.92;n.vy_smooth *= 0.92;n.displayX += n.vx_smooth;n.displayY += n.vy_smooth;}});if (tickCounter % TICKS_PER_UPDATE === 0) {{const xs = nodes.map(n => n.displayX);const ys = nodes.map(n => n.displayY);Plotly.restyle(container, {{ x: [xs], y: [ys] }}, [nodeTraceIndex]);for (let e = 0; e < edgeCount; e++) {{const s = meta.edge_source_index[e];const t = meta.edge_target_index[e];const sx = nodes[s].displayX || 0;const sy = nodes[s].displayY || 0;const tx = nodes[t].displayX || 0;const ty = nodes[t].displayY || 0;Plotly.restyle(container, {{x: [[sx, tx]],y: [[sy, ty]],"line.color": [meta.edge_colors[e]],"line.width": [meta.edge_widths[e]]}}, [e]);}}}}// stop conditions: either alpha cooled or reached tick cap or stopped manuallyif (simulation.alpha() < 0.03 || frameCount > MAX_TICKS || stoppedManually) {{simulation.stop();}}}});// Stop buttondocument.getElementById("{div_id}-stop").addEventListener("click", () => {{stoppedManually = true;simulation.stop();}});// map name -> indexconst nameToIndex = {{}};meta.node_names.forEach((n,i) => nameToIndex[n] = i);// focus node: keep node + direct neighbors (Option A)function focusNode(name) {{const idx = nameToIndex[name];const keep = new Set([idx]);for (let e=0; e < meta.edge_source_index.length; e++) {{const s = meta.edge_source_index[e], t = meta.edge_target_index[e];if (s === idx) keep.add(t);1 unmodified line}}const N = meta.node_names.length;const op = Array(N).fill(0.0);const txt = Array(N).fill("rgba(0,0,0,0)");for (let i=0;i<N;i++) {{if (keep.has(i)) {{ op[i] = 1.0; txt[i] = "black"; }}}}Plotly.restyle(container, {{ "marker.opacity": [op], "textfont.color": [txt] }}, [nodeTraceIndex]);for (let e=0; e<edgeCount; e++) {{const s = meta.edge_source_index[e], t = meta.edge_target_index[e];const show = keep.has(s) && keep.has(t);Plotly.restyle(container, {{"line.color": [ show ? meta.edge_colors[e] : "rgba(0,0,0,0)" ],"line.width": [ show ? meta.edge_widths[e] : 0.1 ]}}, [e]);}}}}// reset view: restore everything and run a short settling simulationfunction resetView() {{const N = meta.node_names.length;Plotly.restyle(container, {{1 unmodified line"textfont.color": [Array(N).fill("black")]}}, [nodeTraceIndex]);for (let e=0;e<edgeCount;e++) {{Plotly.restyle(container, {{"line.color": [meta.edge_colors[e]],"line.width": [meta.edge_widths[e]]}}, [e]);}}// restart a very short simulation to gently re-space nodesstoppedManually = false;frameCount = 0;simulation.alpha(0.6);simulation.restart();}}// click handler to focuscontainer.on("plotly_click", (evt) => {{const p = evt.points && evt.points[0];if (p && p.curveNumber === nodeTraceIndex) {{const idx = p.pointNumber;const name = meta.node_names[idx];focusNode(name);}}}});// reset button hookupdocument.getElementById("{div_id}-reset").addEventListener("click", resetView);</script>"""return html# ---------------------------# Company / AMC summaries# ---------------------------def company_trade_summary(company):buyers = [a for a, cs in BUY_MAP.items() if company in cs]sellers = [a for a, cs in SELL_MAP.items() if company in cs]fresh = [a for a, cs in FRESH_BUY.items() if company in cs]exits = [a for a, cs in COMPLETE_EXIT.items() if company in cs]df = pd.DataFrame({"Role": ["Buyer"]*len(buyers) + ["Seller"]*len(sellers) + ["Fresh buy"]*len(fresh) + ["Complete exit"]*len(exits),"AMC": buyers + sellers + fresh + exits2 unmodified linesreturn 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}", autosize=True, margin=dict(t=30,b=10))return fig, dfdef amc_transfer_summary(amc):sold = SELL_MAP.get(amc, [])transfers = []for s in sold:buyers = [a for a, cs in BUY_MAP.items() if s in cs]for b in buyers:transfers.append({"security": s, "buyer_amc": b})df = pd.DataFrame(transfers)1 unmodified linereturn 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}", autosize=True, margin=dict(t=30,b=10))return fig, df# ---------------------------# Glue: build initial html & Gradio UI# ---------------------------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=edge_thickness)return make_network_html(fig, meta)initial_html = build_network_html()responsive_css = """.js-plotly-plot { height:560px !important; }@media(max-width:780px){ .js-plotly-plot{ height:540px !important; } }"""with gr.Blocks(css=responsive_css, title="MF Churn Explorer (Smooth Short Motion)") as demo:gr.Markdown("## Mutual Fund Churn Explorer — Smooth organic motion (short-lived)")network_html = gr.HTML(value=initial_html)3 unmodified lines<div><span style="display:inline-block;width:28px;border-bottom:3px solid #2ca02c;"></span> BUY (green solid)</div><div><span style="display:inline-block;width:28px;border-bottom:3px dotted #d62728;"></span> SELL (red dotted)</div><div><span style="display:inline-block;width:28px;border-bottom:3px dashed #888;"></span> TRANSFER (grey dashed — inferred)</div><div><span style="display:inline-block;width:28px;border-bottom:5px solid #2ca02c;"></span> FRESH BUY</div><div><span style="display:inline-block;width:28px;border-bottom:5px solid #d62728;"></span> COMPLETE EXIT</div></div>""")with gr.Accordion("Customize Network", 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, 1.4, step=0.1, label="Edge thickness")include_transfers = gr.Checkbox(True, label="Show inferred AMC→AMC transfers")update_btn = gr.Button("Update Graph")gr.Markdown("### Company Summary")select_company = gr.Dropdown(choices=COMPANIES, label="Select company")company_plot = gr.Plot()company_table = gr.DataFrame()gr.Markdown("### AMC Summary (Inferred Transfers)")select_amc = gr.Dropdown(choices=AMCS, label="Select AMC")amc_plot = gr.Plot()amc_table = gr.DataFrame()9 unmodified linesedge_thickness=edge_thickness_val,include_transfers=include_transfers_val)update_btn.click(fn=update_network,inputs=[node_color_company, node_color_amc,edge_color_buy, edge_color_sell, edge_color_transfer,edge_thickness, include_transfers],outputs=[network_html])def on_company(c):fig, df = company_trade_summary(c)1234564 unmodified lines1112131415161747 unmodified lines6566676869707172737475767778798081828384854 unmodified lines9091929394959697981 unmodified line1001011021031041051061 unmodified line1081091101111121132 unmodified lines1161171181191201211221 unmodified line1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982991 unmodified line3013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303311 unmodified line3333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693702 unmodified lines3733743753763773783793803813823833843853861 unmodified line3883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304313 unmodified lines4354364374384394404414424434444454464474484494504514524534544554564574584594604619 unmodified lines471472473474475476477478479480481# app.py# Static bipartite network for Mutual Fund Churn Explorer# Left = AMCs, Right = Companies. Static positions (no animation). Mobile-safe.import gradio as grimport pandas as pd4 unmodified linesfrom collections import defaultdict# ---------------------------# DATA# ---------------------------AMCS = ["SBI MF", "ICICI Pru MF", "HDFC MF", "Nippon India MF", "Kotak MF",47 unmodified linesFRESH_BUY = sanitize_map(FRESH_BUY)# ---------------------------# Build graph + inferred transfers# ---------------------------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)] += 1out = []for (s,b), w in transfers.items():4 unmodified linesdef 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")# buysfor amc, comps in BUY_MAP.items():for c in comps:if G.has_edge(amc, c):1 unmodified lineG[amc][c]["actions"].append("buy")else:G.add_edge(amc, c, weight=1, actions=["buy"])# sellsfor amc, comps in SELL_MAP.items():for c in comps:if G.has_edge(amc, c):1 unmodified lineG[amc][c]["actions"].append("sell")else:G.add_edge(amc, c, weight=1, actions=["sell"])# complete exitsfor amc, comps in COMPLETE_EXIT.items():for c in comps:2 unmodified linesG[amc][c]["actions"].append("complete_exit")else:G.add_edge(amc, c, weight=3, actions=["complete_exit"])# fresh buyfor amc, comps in FRESH_BUY.items():for c in comps:if G.has_edge(amc, c):1 unmodified lineG[amc][c]["actions"].append("fresh_buy")else:G.add_edge(amc, c, weight=3, actions=["fresh_buy"])# inferred transfersif include_transfers:for s,b,attr in transfer_edges:if G.has_edge(s,b):G[s][b]["weight"] += attr.get("weight",1)G[s][b]["actions"].append("transfer")else:G.add_edge(s,b, weight=attr.get("weight",1), actions=["transfer"])return G# ---------------------------# Static bipartite layout generator# ---------------------------def bipartite_positions(G, left_nodes, right_nodes, x_left=-1.0, x_right=1.0, y_pad=0.1):"""Place left_nodes at x_left and right_nodes at x_right.Spread nodes vertically from -1..1 with padding y_pad.Returns dict {node: (x,y)}"""pos = {}# left columnnL = len(left_nodes)if nL == 1:ysL = [0.0]else:span = 2.0 - 2*y_padysL = [ -1 + y_pad + i * (span/(nL-1)) for i in range(nL) ]for n, y in zip(left_nodes, ysL):pos[n] = (x_left, y)# right columnnR = len(right_nodes)if nR == 1:ysR = [0.0]else:span = 2.0 - 2*y_padysR = [ -1 + y_pad + i * (span/(nR-1)) for i in range(nR) ]for n, y in zip(right_nodes, ysR):pos[n] = (x_right, y)return pos# ---------------------------# Build static Plotly figure# ---------------------------def build_plotly_static_figure(G,node_color_amc="#9EC5FF",node_color_company="#FFCF9E",edge_color_buy="#2ca02c",edge_color_sell="#d62728",edge_color_transfer="#888888",edge_thickness=1.6):# positions: left=AMCS, right=COMPANIESpos = bipartite_positions(G, AMCS, COMPANIES, x_left=-1.0, x_right=1.0, y_pad=0.06)node_names = []node_x = []node_y = []node_color = []node_size = []node_type = []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); node_type.append("amc")else:node_color.append(node_color_company); node_size.append(52); node_type.append("company")# create edge traces (one per edge for easy restyle)edge_traces = []edge_src_idx = []edge_tgt_idx = []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", [])w = attrs.get("weight", 1)if "complete_exit" in acts:color = edge_color_sell; width = edge_thickness * 3; dash = "solid"elif "fresh_buy" in acts:color = edge_color_buy; width = edge_thickness * 3; dash = "solid"elif "transfer" in acts:color = edge_color_transfer; width = edge_thickness * (1 + np.log1p(w)); dash = "dash"elif "sell" in acts:color = edge_color_sell; width = edge_thickness * (1 + np.log1p(w)); dash = "dot"else:color = edge_color_buy; width = edge_thickness * (1 + np.log1p(w)); dash = "solid"edge_traces.append(go.Scatter(x=[x0, x1], y=[y0, y1],mode="lines",line=dict(color=color, width=width, dash=dash),hoverinfo="text",text=f"{u} → {v} ({', '.join(acts)})"))edge_src_idx.append(node_names.index(u))edge_tgt_idx.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="#222")),text=node_names,textposition="middle right",hoverinfo="text")fig = go.Figure(data=edge_traces + [node_trace])fig.update_layout(title="Mutual Fund Churn — Static Bipartite Layout",showlegend=False,autosize=True,margin=dict(l=10, r=10, t=40, b=10),xaxis=dict(visible=False),yaxis=dict(visible=False))meta = {"node_names": node_names,"edge_source_index": edge_src_idx,"edge_target_index": edge_tgt_idx,"edge_colors": edge_colors,"edge_widths": edge_widths,"node_x": node_x,"node_y": node_y,}return fig, meta# ---------------------------# Make HTML (static) with JS click handlers# ---------------------------def make_static_html(fig, meta, div_id="network-plot-div"):fig_json = json.dumps(fig.to_plotly_json())meta_json = json.dumps(meta)# NOTE: inside this f-string we must double braces for JS object blockshtml = f"""<div id="{div_id}" style="width:100%; height:580px;"></div><div style="margin-top:6px;"><button id="{div_id}-reset" style="padding:8px 12px; border-radius:6px;">Reset</button></div><script src="https://cdn.plot.ly/plotly-latest.min.js"></script><script>const fig = {fig_json};const meta = {meta_json};const container = document.getElementById("{div_id}");// Render plotly figure (static positions embedded)Plotly.newPlot(container, fig.data, fig.layout, {{responsive:true}});const nodeTraceIndex = fig.data.length - 1;const edgeCount = fig.data.length - 1;// Map name -> indexconst nameToIndex = {{}};meta.node_names.forEach((n,i) => nameToIndex[n]=i);// Focus node: show only node + neighbors, hide others (including labels)function focusNode(name) {{const idx = nameToIndex[name];const keep = new Set([idx]);for (let e=0; e < meta.edge_source_index.length; e++) {{const s = meta.edge_source_index[e], t = meta.edge_target_index[e];if (s === idx) keep.add(t);1 unmodified line}}const N = meta.node_names.length;const nodeOp = Array(N).fill(0.0);const textColors = Array(N).fill("rgba(0,0,0,0)");for (let i=0;i<N;i++) {{if (keep.has(i)) {{ nodeOp[i]=1.0; textColors[i]="black"; }}}}Plotly.restyle(container, {{"marker.opacity": [nodeOp],"textfont.color": [textColors]}}, [nodeTraceIndex]);// edges: show only those connecting kept nodesfor (let e=0; e < edgeCount; e++) {{const s = meta.edge_source_index[e], t = meta.edge_target_index[e];const show = keep.has(s) && keep.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]);}}}}// Reset viewfunction resetView() {{const N = meta.node_names.length;Plotly.restyle(container, {{1 unmodified line"textfont.color": [Array(N).fill("black")]}}, [nodeTraceIndex]);for (let e=0; e < edgeCount; e++) {{Plotly.restyle(container, {{"line.color": [meta.edge_colors[e]],"line.width": [meta.edge_widths[e]]}}, [e]);}}}}// Hook clickcontainer.on('plotly_click', function(evt) {{const p = evt.points && evt.points[0];if (p && p.curveNumber === nodeTraceIndex) {{const name = meta.node_names[p.pointNumber];focusNode(name);}}}});// Hook reset buttondocument.getElementById("{div_id}-reset").addEventListener("click", resetView);</script>"""return html# ---------------------------# Company & AMC summaries (unchanged)# ---------------------------def company_trade_summary(company):buyers = [a for a,cs in BUY_MAP.items() if company in cs]sellers = [a for a,cs in SELL_MAP.items() if company in cs]fresh = [a for a,cs in FRESH_BUY.items() if company in cs]exits = [a for a,cs in COMPLETE_EXIT.items() if company in cs]df = pd.DataFrame({"Role": ["Buyer"]*len(buyers) + ["Seller"]*len(sellers) + ["Fresh buy"]*len(fresh) + ["Complete exit"]*len(exits),"AMC": buyers + sellers + fresh + exits2 unmodified linesreturn 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=f"Trade summary for {company}", margin=dict(t=30,b=10))return fig, dfdef amc_transfer_summary(amc):sold = SELL_MAP.get(amc, [])transfers = []for s in sold:buyers = [a for a,cs in BUY_MAP.items() if s in cs]for b in buyers:transfers.append({"security": s, "buyer_amc": b})df = pd.DataFrame(transfers)1 unmodified linereturn 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="gray"))fig.update_layout(title=f"Inferred transfers from {amc}", margin=dict(t=30,b=10))return fig, df# ---------------------------# Build static figure & meta# ---------------------------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.6,include_transfers=True):G = build_graph(include_transfers=include_transfers)fig, meta = build_plotly_static_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=edge_thickness)return make_static_html(fig, meta)initial_html = build_network_html()# ---------------------------# Gradio UI# ---------------------------responsive_css = """.js-plotly-plot { height:560px !important; }@media(max-width:780px){ .js-plotly-plot{ height:520px !important; } }"""with gr.Blocks(css=responsive_css, title="MF Churn Explorer — Static Bipartite") as demo:gr.Markdown("## Mutual Fund Churn Explorer — Static Bipartite Layout (mobile-friendly)")network_html = gr.HTML(value=initial_html)3 unmodified lines<div><span style="display:inline-block;width:28px;border-bottom:3px solid #2ca02c;"></span> BUY (green solid)</div><div><span style="display:inline-block;width:28px;border-bottom:3px dotted #d62728;"></span> SELL (red dotted)</div><div><span style="display:inline-block;width:28px;border-bottom:3px dashed #888;"></span> TRANSFER (grey dashed — inferred)</div><div><span style="display:inline-block;width:28px;border-bottom:5px solid #2ca02c;"></span> FRESH BUY (thick green)</div><div><span style="display:inline-block;width:28px;border-bottom:5px solid #d62728;"></span> COMPLETE EXIT (thick red)</div></div>""")with gr.Accordion("Customize Network (static)", 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.6, step=0.1, label="Edge thickness")include_transfers = gr.Checkbox(value=True, label="Show inferred AMC→AMC transfers")update_button = gr.Button("Update Graph")gr.Markdown("### Inspect Company (buyers / sellers)")select_company = gr.Dropdown(choices=COMPANIES, label="Select company")company_plot = gr.Plot()company_table = gr.DataFrame()gr.Markdown("### Inspect AMC (inferred transfers)")select_amc = gr.Dropdown(choices=AMCS, label="Select AMC")amc_plot = gr.Plot()amc_table = gr.DataFrame()9 unmodified linesedge_thickness=edge_thickness_val,include_transfers=include_transfers_val)update_button.click(update_network,inputs=[node_color_company, node_color_amc,edge_color_buy, edge_color_sell, edge_color_transfer,edge_thickness, include_transfers],outputs=[network_html])def on_company(c):fig, df = company_trade_summary(c)
app.py+190-216