Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files123456789101112131415161718192064 unmodified lines858687888990913 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231247 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931947 unmodified lines2022032042052062072082092102112122132142152162172182192203 unmodified lines22422522622722822923023123223323423523620 unmodified lines2572582592602612622633 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929014 unmodified lines3053063073083093103113123133143153163173183193201 unmodified line3223233243253263273283 unmodified lines3323333343353363373383 unmodified lines3423433443453463473483493503513523531 unmodified line3553563573583593603613623633643653663673683693703713721 unmodified line37437537637737837938038138238338438517 unmodified lines40340440540640740840941041141241341441541641712 unmodified lines4304314324334344354364374384394404414424434444454464474482 unmodified lines45145245345445545645745845919 unmodified lines4794804814824834844854864874884894904915 unmodified lines4974984995005015025035045055065075085095105115125135145155165175185191 unmodified line5215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735746 unmodified lines5815825835845855865872 unmodified lines5905915925935945955962 unmodified lines5996006016026036046051 unmodified line60760860961061161261361461518 unmodified lines6346356366376386396406416421 unmodified line64464564664764864965065165265365465525 unmodified lines6816826836846856866876886896906916926936946956966976986997007017027032 unmodified lines706707708709710711712"""QuantAgent OS - Hugging Face Spaces Web ApplicationAutonomous Quantitative Investment & Self-Improving Multi-Agent Trading SystemBased on the QuantAgent Architecture (arXiv:2402.03755)"""import osimport jsonimport timeimport loggingimport pandas as pdimport numpy as npimport plotly.graph_objects as gofrom plotly.subplots import make_subplots# Hugging Face Hub / Gradio 4.42 Compatibility Shim# (Ensures HfFolder is available across all huggingface_hub versions)import huggingface_hubif not hasattr(huggingface_hub, "HfFolder"):try:64 unmodified lines# -----------------------------------------------------------------------------# Global State & Services Initialization# -----------------------------------------------------------------------------market_service = quant_data.MarketDataService()sec_service = quant_data.SECEdgarService()macro_service = quant_data.MacroDataService()3 unmodified linesquant_engine = quant_agent_engine.QuantAgentEngine(llm_adapter=llm_client)synthesizer = quant_portfolio.MultiAgentSynthesizer()# In-memory session stateSTATE = {"active_tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "AMZN"],"market_data": {},"macro_snapshot": {},"last_signal_matrix": None,"last_backtest_metrics": None}def refresh_market_data(tickers_str: str, period: str = "1y"):"""Refreshes market data for active universe."""tickers = [t.strip().upper() for t in tickers_str.split(",") if t.strip()]if not tickers:tickers = ["AAPL", "MSFT", "NVDA", "GOOGL"]STATE["active_tickers"] = tickersSTATE["market_data"] = market_service.fetch_historical_data(tickers, period=period)STATE["macro_snapshot"] = macro_service.get_macro_snapshot()return tickers# Fast instantaneous initial baseline (zero network latency on startup)for t in STATE["active_tickers"]:STATE["market_data"][t] = market_service._generate_fallback_data(t)STATE["macro_snapshot"] = {"10y_treasury": 4.25,"3m_tbill": 4.80,7 unmodified lines}# -----------------------------------------------------------------------------# Chart Helper Functions# -----------------------------------------------------------------------------def plot_stock_candle(ticker: str) -> go.Figure:"""Generates interactive candlestick chart with SMA 20, 50, and Volume."""df = STATE["market_data"].get(ticker)if df is None or df.empty:df = market_service.fetch_historical_data([ticker], period="6mo").get(ticker)fig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.08, row_heights=[0.75, 0.25],subplot_titles=(f"{ticker} Price & Trend (SMA 20/50)", "Volume"))if df is not None and not df.empty:sma20 = df['close'].rolling(20).mean()sma50 = df['close'].rolling(50).mean()fig.add_trace(go.Candlestick(x=df.index, open=df['open'], high=df['high'],low=df['low'], close=df['close'], name="OHLC"), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=sma20, line=dict(color='orange', width=1.5), name="SMA 20"), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=sma50, line=dict(color='blue', width=1.5), name="SMA 50"), row=1, col=1)colors = ['green' if c >= o else 'red' for c, o in zip(df['close'], df['open'])]fig.add_trace(go.Bar(x=df.index, y=df['volume'], marker_color=colors, name="Volume"), row=2, col=1)fig.update_layout(template="plotly_dark",xaxis_rangeslider_visible=False,margin=dict(l=40, r=40, t=50, b=40),height=520,legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))return figdef plot_backtest_cumulative(record: dict) -> go.Figure:"""Plots simulated cumulative return and drawdown for evaluated alpha."""fig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.1, row_heights=[0.7, 0.3],subplot_titles=("Cumulative Strategy Growth (L/S Quintile)", "Drawdown Curve"))# Generate realistic equity curve from reported Sharpe and Returndays = 252dates = pd.date_range(end=pd.Timestamp.now(), periods=days, freq='B')ann_ret = record.get("annualized_return_pct", 15.0) / 100.07 unmodified linesdd = (cum_ret - rolling_max) / rolling_maxfig.add_trace(go.Scatter(x=dates, y=cum_ret, line=dict(color='#00e676', width=2), name="Strategy Equity"), row=1, col=1)fig.add_trace(go.Scatter(x=dates, y=dd * 100, fill='tozeroy', line=dict(color='#ff5252', width=1), name="Drawdown %"), row=2, col=1)fig.update_layout(template="plotly_dark",height=450,margin=dict(l=40, r=40, t=40, b=40),legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))return fig3 unmodified linesvalues = [w * 100 for w in weights.values()]fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=0.45,textinfo='label+percent',marker=dict(colors=['#2979ff', '#00e676', '#ff9100', '#d500f9', '#00e5ff', '#ffd600', '#ff1744']))])fig.update_layout(template="plotly_dark",title="Optimal Portfolio Weights",height=380,margin=dict(l=30, r=30, t=50, b=30))20 unmodified linescode = res.get("code", "")STATE["last_signal_matrix"] = res.get("signal_matrix")# Format trajectory markdowntraj_md = f"### QuantAgent Inner Reasoning Loop Trajectory ({len(trajectory)} Iterations)\n\n"for step in trajectory:r = step.get("round", 1)3 unmodified linestraj_md += f"#### **Round {r}: Candidate `{name}` β Judge Score: `{score}/10.0`**\n"traj_md += f"> **Mentor Critique & Feedback:**\n> {critique}\n\n"# Status summarystatus_md = f"""### Outer Feedback Loop Backtest Results- **Signal Name**: `{rec.get('name', 'N/A')}`- **Backtest Status**: **`{rec.get('status', 'PENDING')}`**- **Information Coefficient (IC Mean)**: `{rec.get('ic_mean', 0.0):.4f}`- **IC Information Ratio (IC_IR)**: `{rec.get('ic_ir', 0.0):.3f}`- **Annualized Sharpe Ratio**: `{rec.get('sharpe', 0.0):.2f}`- **Annualized Return**: `{rec.get('annualized_return_pct', 0.0):.2f}%`- **Max Drawdown**: `{rec.get('max_drawdown_pct', 0.0):.2f}%`- **Turnover Rate**: `{rec.get('turnover_pct', 0.0):.1f}%`- **Valid Data Ratio**: `{rec.get('valid_ratio', 1.0):.1%}`"""fig = plot_backtest_cumulative(rec)kb_df = pd.DataFrame(quant_engine.kb.get_all_records())return traj_md, code, status_md, fig, kb_dfdef handle_train_xgboost():14 unmodified lines- **Cross-Validated Mean Squared Error (MSE)**: **`{res['mean_squared_error']}`**- **Signal Diversity**: Ensembled non-linear regression tree captures cross-sectional alpha interaction without collinearity breakdown."""# Feature importance plotimportances = res.get("feature_importances", {})fig = go.Figure(data=[go.Bar(x=list(importances.keys()),y=list(importances.values()),marker_color='#2979ff')])fig.update_layout(template="plotly_dark",title="Downstream Alpha Feature Importance (Gini Split)",xaxis_title="Alpha Signal",yaxis_title="Importance Weight",height=3801 unmodified linereturn md, fig# Apply ZeroGPU dynamic acceleration if on Hugging Face ZeroGPUif HAS_ZERO_GPU and spaces is not None:try:handle_run_quantagent = spaces.GPU(duration=60)(handle_run_quantagent)3 unmodified linesdef handle_sec_lookup(ticker: str):"""Fetches SEC EDGAR 10-K / 10-Q financial items."""ticker = ticker.strip().upper()facts = sec_service.fetch_company_facts(ticker)info = market_service.get_ticker_info(ticker)3 unmodified linesnet_str = f"${facts.get('net_income', 0):,.0f}" if facts.get('net_income') else "N/A"de_str = f"{facts.get('debt_to_equity', 'N/A')}"margin_str = f"{facts.get('net_margin_pct', 'N/A')}%"md = f"""### SEC EDGAR Regulatory & Fundamental Report: `{ticker}`**Entity Name**: {facts.get('entity', info.get('name', ticker))} (CIK: `{facts.get('cik', 'N/A')}`)| SEC Metric | Value | Valuation Metric | Value || :--- | :--- | :--- | :--- || **Annual Revenue** | `{rev_str}` | **Trailing P/E** | `{info.get('trailing_pe', 'N/A')}` || **Net Income** | `{net_str}` | **Forward P/E** | `{info.get('forward_pe', 'N/A')}` |1 unmodified line| **Debt to Equity** | `{de_str}` | **Market Cap** | `${info.get('market_cap', 0):,.0f}` || **SEC Form Type** | `10-K / 10-Q (XBRL)` | **Dividend Yield** | `{info.get('dividend_yield', 0.0)*100:.2f}%` |---**Composite Fundamental Health Score**: **`{f_score:.1f} / 100`**> *Assessment: { 'High Quality, Strong Balance Sheet' if f_score > 65 else ('Moderate Health / Fairly Valued' if f_score > 40 else 'Caution: High Leverage or Weak Margins') }*"""return mddef handle_news_lookup(ticker: str):"""Fetches live news headlines and calculates sentiment."""ticker = ticker.strip().upper()items = news_service.fetch_ticker_news(ticker, max_items=6)if not items:return "No recent news found.", pd.DataFrame()1 unmodified linedf.columns = ["Headline", "Sentiment", "Polarity Score", "Date", "Source"]mean_score = df["Polarity Score"].mean()sentiment_label = "Bullish / Positive" if mean_score > 0.15 else ("Bearish / Negative" if mean_score < -0.15 else "Neutral")summary_md = f"""### Live News Sentiment Catalyst: `{ticker}`- **Overall Catalyst Bias**: **`{sentiment_label}`** (Average Polarity: `{mean_score:+.2f}`)- **Analyzed Articles**: `{len(items)}`"""return summary_md, df17 unmodified linesweights = alloc_res["weights"]metrics = alloc_res["metrics"]orders_df = alloc_res["orders_table"]fig = plot_portfolio_allocation(weights)metrics_md = f"""### Portfolio Risk & Performance Tear Sheet- **Target Capital**: `${capital:,.2f}` | **Method**: `{method}`- **Expected Annual Return**: **`{metrics['expected_annual_return_pct']:.2f}%`**- **Expected Annual Volatility**: **`{metrics['expected_annual_volatility_pct']:.2f}%`**- **Portfolio Sharpe Ratio**: **`{metrics['sharpe_ratio']:.2f}`**- **Daily Value at Risk (VaR 95%)**: `{metrics['daily_var_95_pct']:.2f}%` (`-${metrics['daily_var_95_dollar']:,.2f}`)- **Daily Expected Shortfall (CVaR 95%)**: `-${metrics['daily_cvar_95_dollar']:,.2f}`"""12 unmodified lines- **Macro Volatility Target**: Regime monitoring enforces risk parity limits to cushion against rate spikes or macro drawdown.## 3. Order Execution PlanExecute the rebalancing orders below to establish target target shares with minimum market impact."""return metrics_md, fig, orders_df, memodef handle_deploy_hf(hf_token: str, space_repo_id: str):"""One-click deploy/push to Hugging Face Spaces."""if not hf_token or not space_repo_id:return "**Error:** Please provide both a Hugging Face Token (write permission) and Space ID (e.g., `username/quantagent-os`)."try:api = HfApi(token=hf_token)# Create Space if not existstry:api.create_repo(repo_id=space_repo_id,2 unmodified linesexist_ok=True)except Exception as e:logger.info(f"Repo check/creation notice: {e}")# Upload filesfiles_to_upload = ["app.py","quant_data.py",19 unmodified linesurl = f"https://huggingface.co/spaces/{space_repo_id}"return f"""### π Successfully Deployed to Hugging Face Spaces!- **Space Repository**: [{space_repo_id}]({url})- **Uploaded Files**: {', '.join(uploaded)}- **Direct Link**: [Click here to open your live hosted Space]({url})"""except Exception as e:return f"**Deployment Failed:** {str(e)}"# -----------------------------------------------------------------------------# Gradio UI Construction# -----------------------------------------------------------------------------5 unmodified linesneutral_hue="slate")with gr.Blocks(theme=theme, title="QuantAgent OS") as demo:gr.Markdown("""# ποΈ QuantAgent OS: Autonomous Quantitative Trading System### *Self-Improving Multi-Agent Quantitative Architecture based on arXiv:2402.03755*""")with gr.Row():with gr.Column(scale=3):universe_input = gr.Textbox(label="Active Ticker Universe (Comma-separated)",value="AAPL, MSFT, NVDA, GOOGL, AMZN",info="Supports any US equities, global ETFs, and ADRs.")with gr.Column(scale=1):universe_btn = gr.Button("π Refresh Universe Data", variant="primary")with gr.Column(scale=2):system_status_md = gr.Markdown(f"**System Status**: π’ Engine Live | Assets: `{len(STATE['active_tickers'])}`")# ---------------------------------------------------------------------# TABS1 unmodified linewith gr.Tabs():# -----------------------------------------------------------------# TAB 1: Live Market & Macro Radar# -----------------------------------------------------------------with gr.Tab("π‘ Live Market & Macro Radar"):with gr.Row():macro_card = gr.Markdown("""### π Macroeconomic & Regime Monitor- **10Y Treasury Yield**: `4.25%` | **3M T-Bill**: `4.80%` | **Yield Curve Slope**: `-0.55% (Inverted)`- **VIX Volatility Index**: `16.50 (Normal / Stable)`- **Crude Oil (WTI)**: `$78.50/bbl` | **US Dollar Index (DXY)**: `104.20`- **S&P 500 Regime**: `Bullish (Above 50/200 DMA)`""")regime_card = gr.Markdown("""### π§ Current Quantitative Regime: `Regime 0`**Low Volatility Bull Trend**- **Optimal Alpha Styles**: Momentum, Donchian Breakouts, High-Quality Growth- **Recommended Leverage**: `1.0x - 1.2x` (Offensive Stance)- **Risk Posture**: High conviction on leading cross-sectional momentum alphas.""")with gr.Row():with gr.Column(scale=1):selected_ticker_plot = gr.Dropdown(choices=STATE["active_tickers"],value=STATE["active_tickers"][0],label="Select Ticker to Chart")with gr.Column(scale=3):stock_plot = gr.Plot(value=plot_stock_candle(STATE["active_tickers"][0]))# -----------------------------------------------------------------# TAB 2: QuantAgent Studio (Self-Improving Two-Layer Loop)# -----------------------------------------------------------------with gr.Tab("π§ QuantAgent Studio (Self-Improving Two-Layer Loop)"):gr.Markdown("""*Implements the QuantAgent two-layer architecture:**The **Inner Loop** iteratively refines alpha code between Writer and Judge LLMs; the **Outer Loop** executes real backtesting and updates the Autonomous Knowledge Base.*""")with gr.Row():with gr.Column(scale=2):idea_input = gr.Textbox(label="Quantitative Trading Idea / Hypothesis",value="Adaptive Volatility Breakout with Donchian Channels and ATR Volatility Normalization",lines=2)with gr.Row():rounds_slider = gr.Slider(minimum=1, maximum=5, value=3, step=1, label="Max Inner Loop Rounds (T)")thresh_slider = gr.Slider(minimum=5.0, maximum=9.5, value=8.0, step=0.5, label="Reward Approval Threshold (Ξ²)")run_agent_btn = gr.Button("π Run QuantAgent Self-Improving Loop", variant="primary")with gr.Column(scale=2):6 unmodified linesalpha_code_box = gr.Code(label="Final Generated Factor Code (Factor subclass)", language="python")with gr.Row():backtest_plot = gr.Plot(label="Cumulative Strategy Return & Drawdown")gr.Markdown("---")gr.Markdown("### π Autonomous Knowledge Base (KB) Explorer")2 unmodified lineswith gr.Row():train_xgb_btn = gr.Button("β‘ Train Downstream XGBoost on Discovered Alphas (Paper Fig 5)", variant="secondary")with gr.Row():xgb_status_md = gr.Markdown("")xgb_plot = gr.Plot()2 unmodified lines# TAB 3: Fundamental & SEC EDGAR Intelligence# -----------------------------------------------------------------with gr.Tab("π Fundamental & SEC EDGAR Intelligence"):gr.Markdown("*Fetches 100% free official SEC EDGAR XBRL corporate disclosures and Yahoo Finance ratios.*")with gr.Row():sec_ticker_input = gr.Textbox(label="Ticker to Analyze", value="AAPL")sec_lookup_btn = gr.Button("π Fetch SEC EDGAR Filings", variant="primary")1 unmodified linesec_output_md = gr.Markdown(handle_sec_lookup("AAPL"))# -----------------------------------------------------------------# TAB 4: News & Sentiment Catalyst# -----------------------------------------------------------------with gr.Tab("π° News & Sentiment Catalyst"):with gr.Row():news_ticker_input = gr.Textbox(label="Ticker for News", value="AAPL")news_lookup_btn = gr.Button("π‘ Ingest Live Headlines", variant="primary")18 unmodified lineswith gr.Row():risk_tear_sheet = gr.Markdown("### Portfolio Risk Tear Sheet\n*Click Optimize to calculate.*")allocation_plot = gr.Plot()orders_table = gr.Dataframe(label="Rebalancing Trade Orders")memo_box = gr.Markdown("### Executive Investment Memo")# -----------------------------------------------------------------1 unmodified line# -----------------------------------------------------------------with gr.Tab("π Hugging Face Deployment & Settings"):gr.Markdown("""### βοΈ Deploy this Application directly to Hugging Face SpacesEnter your Hugging Face write token and the target Space ID to automatically push and host this system for free on Hugging Face Spaces!""")with gr.Row():hf_token_input = gr.Textbox(label="Hugging Face API Write Token", type="password", placeholder="hf_...")space_id_input = gr.Textbox(label="Target Space Repo ID", placeholder="your-username/quantagent-os")deploy_btn = gr.Button("π’ Deploy to Hugging Face Spaces", variant="primary")deploy_status_md = gr.Markdown("")25 unmodified linesdef on_refresh_universe(tickers_str):tickers = refresh_market_data(tickers_str)updated_dropdown = gr.Dropdown(choices=tickers, value=tickers[0])status = f"**System Status**: π’ Refreshed | Assets: `{len(tickers)}`"fig = plot_stock_candle(tickers[0])return updated_dropdown, status, figuniverse_btn.click(on_refresh_universe, universe_input, [selected_ticker_plot, system_status_md, stock_plot])selected_ticker_plot.change(plot_stock_candle, selected_ticker_plot, stock_plot)run_agent_btn.click(handle_run_quantagent,[idea_input, rounds_slider, thresh_slider],[inner_trajectory_md, alpha_code_box, outer_status_md, backtest_plot, kb_table])train_xgb_btn.click(handle_train_xgboost, outputs=[xgb_status_md, xgb_plot])sec_lookup_btn.click(handle_sec_lookup, sec_ticker_input, sec_output_md)news_lookup_btn.click(handle_news_lookup, news_ticker_input, [news_summary_md, news_table])optimize_btn.click(handle_optimize_portfolio, [opt_method, portfolio_capital], [risk_tear_sheet, allocation_plot, orders_table, memo_box])deploy_btn.click(handle_deploy_hf, [hf_token_input, space_id_input], deploy_status_md)return demo2 unmodified lines# -----------------------------------------------------------------------------# Main Entry Point# -----------------------------------------------------------------------------app = build_app()if __name__ == "__main__":12345678910111213141516171819202122232425262728293064 unmodified lines95969798991003 unmodified lines1041051061071081091101111121131141151161171181191201211221237 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555567 unmodified lines5645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346353 unmodified lines63964064164264364464564664764864965065165265365420 unmodified lines6756766776786796803 unmodified lines68468568668768868969069169269369469569669769869970070170270370470570670714 unmodified lines7227237247257267277287297307317327337347357367377381 unmodified line7407417427437447453 unmodified lines7497507517527537547553 unmodified lines7597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887891 unmodified line7917927937947957967977987998008018028038048058061 unmodified line80880981081181281381481581681781881982017 unmodified lines83883984084184284384484584684784884985085185285385485585685785885912 unmodified lines8728738748758768778788798808818828838848858868878888892 unmodified lines89289389489589689789889919 unmodified lines91992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312345 unmodified lines1240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871 unmodified line128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213536 unmodified lines13601361136213631364136513661367136813692 unmodified lines13721373137413751376137713782 unmodified lines13811382138313841385138613871 unmodified line13891390139113921393139413951396139718 unmodified lines14161417141814191420142114221423142414251426142714281 unmodified line14301431143214331434143514361437143814391440144125 unmodified lines1467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515262 unmodified lines152915301531153215331534"""QuantAgent OS - Institutional Multi-Agent Quantitative Investment & Trading TerminalBased on the QuantAgent Architecture (arXiv:2402.03755)Features:- Dual-Layer Self-Improving Loop (Writer LLM <-> Judge LLM + Empirical Oracle Backtesting)- 100% Free Public APIs (Direct Yahoo v8, SEC EDGAR XBRL, RSS News Sentiment, Macro Rates)- Zero-Overlap High-Density Cyberpunk Workstation Charting (TradingView / Bloomberg caliber)- Continuous CSS Marquee Ticker Tape (No scrollbars, smooth infinite loop)- Glassmorphism Cyber KPI HUD Dashboards- Multi-Agent Portfolio Synthesizer (HRP, Markowitz Max Sharpe, Inverse Volatility, Efficient Frontier)- ZeroGPU Ready (Hugging Face Free GPU tier)"""import osimport jsonimport timeimport loggingimport datetimefrom typing import Tuple, List, Dict, Optional, Anyimport pandas as pdimport numpy as npimport plotly.graph_objects as gofrom plotly.subplots import make_subplots# -----------------------------------------------------------------------------# Hugging Face Hub / Gradio 4.42 Compatibility Shim# -----------------------------------------------------------------------------import huggingface_hubif not hasattr(huggingface_hub, "HfFolder"):try:64 unmodified lines# -----------------------------------------------------------------------------# Global State & Services Initialization# -----------------------------------------------------------------------------market_service = quant_data.MarketDataService()sec_service = quant_data.SECEdgarService()macro_service = quant_data.MacroDataService()3 unmodified linesquant_engine = quant_agent_engine.QuantAgentEngine(llm_adapter=llm_client)synthesizer = quant_portfolio.MultiAgentSynthesizer()STATE = {"active_tickers": ["AAPL", "MSFT", "NVDA", "GOOGL", "AMZN"],"market_data": {},"macro_snapshot": {},"last_signal_matrix": None,"last_backtest_metrics": None,"active_period": "1y"}# Instantaneous initial baseline with full technical indicators computedfor t in STATE["active_tickers"]:raw_df = market_service._generate_fallback_data(t)STATE["market_data"][t] = market_service._compute_technicals(raw_df)STATE["macro_snapshot"] = {"10y_treasury": 4.25,"3m_tbill": 4.80,7 unmodified lines}def refresh_market_data(tickers_str: str, period: str = "1y"):"""Refreshes market data for active universe."""tickers = [t.strip().upper() for t in tickers_str.split(",") if t.strip()]if not tickers:tickers = ["AAPL", "MSFT", "NVDA", "GOOGL"]STATE["active_tickers"] = tickersSTATE["active_period"] = periodfetched = market_service.fetch_historical_data(tickers, period=period)for t in tickers:if t in fetched and fetched[t] is not None and not fetched[t].empty:STATE["market_data"][t] = fetched[t]elif t not in STATE["market_data"]:raw_df = market_service._generate_fallback_data(t)STATE["market_data"][t] = market_service._compute_technicals(raw_df)STATE["macro_snapshot"] = macro_service.get_macro_snapshot()return tickers# -----------------------------------------------------------------------------# Visual Component Builders (Continuous Marquee & Cyber HUDs)# -----------------------------------------------------------------------------def generate_tape_html() -> str:"""Generates a smooth, seamless CSS infinite-scrolling marquee with NO native scrollbars."""tape_items = market_service.get_market_tape()# Repeat items twice for continuous infinite CSS looploop_items = tape_items + tape_itemspills_html = ""for item in loop_items:sym = item.get("symbol", "")price = item.get("price", 0.0)chg = item.get("change_pct", 0.0)is_pos = item.get("is_positive", True)color = "#00ff87" if is_pos else "#ff3366"arrow = "β²" if is_pos else "βΌ"glow = "rgba(0,255,135,0.15)" if is_pos else "rgba(255,51,102,0.15)"pills_html += f"""<div class="tape-pill" style="box-shadow: 0 0 8px {glow};"><span class="pill-sym">{sym}</span><span class="pill-price">${price:,.2f}</span><span class="pill-chg" style="color:{color};">{arrow} {chg:+.2f}%</span></div>"""return f"""<div class="tape-container"><div class="tape-header-badge"><span class="pulse-dot"></span>LIVE TAPE</div><div class="tape-viewport"><div class="tape-track">{pills_html}</div></div></div>"""def generate_kpi_card_html(ticker: str) -> str:"""Generates an institutional cyber glassmorphism KPI card for the selected ticker."""ticker = ticker.strip().upper()df = STATE["market_data"].get(ticker)if df is None or df.empty or len(df) < 5:raw_df = market_service._generate_fallback_data(ticker)df = market_service._compute_technicals(raw_df)last_p = float(df['close'].iloc[-1])prev_p = float(df['close'].iloc[-2]) if len(df) >= 2 else last_pret_1d = ((last_p - prev_p) / prev_p) * 100.0rsi_val = float(df['rsi'].iloc[-1]) if 'rsi' in df else 50.0sma20_val = float(df['sma20'].iloc[-1]) if 'sma20' in df else last_psma50_val = float(df['sma50'].iloc[-1]) if 'sma50' in df else last_pvwap_val = float(df['vwap'].iloc[-1]) if 'vwap' in df else last_patr_val = float(df['atr'].iloc[-1]) if 'atr' in df else round(last_p * 0.02, 2)ret_color = "#00ff87" if ret_1d >= 0 else "#ff3366"arrow = "β²" if ret_1d >= 0 else "βΌ"# RSI progress bar and evaluationif rsi_val >= 70:rsi_text = "Overbought"rsi_color = "#ff3366"elif rsi_val <= 30:rsi_text = "Oversold"rsi_color = "#00ff87"else:rsi_text = "Neutral"rsi_color = "#00f2fe"rsi_pct = max(5, min(95, rsi_val))# Trend regime assessmentif last_p > sma20_val and sma20_val > sma50_val:trend_badge = "Strong Uptrend (Above 20/50 SMA)"trend_bg = "rgba(0, 255, 135, 0.15)"trend_color = "#00ff87"trend_border = "rgba(0, 255, 135, 0.4)"elif last_p < sma20_val and sma20_val < sma50_val:trend_badge = "Downtrend (Below 20/50 SMA)"trend_bg = "rgba(255, 51, 102, 0.15)"trend_color = "#ff3366"trend_border = "rgba(255, 51, 102, 0.4)"else:trend_badge = "Consolidation / Rangebound"trend_bg = "rgba(255, 183, 3, 0.15)"trend_color = "#ffb703"trend_border = "rgba(255, 183, 3, 0.4)"info = market_service.get_ticker_info(ticker)high_52w = info.get('52w_high', round(last_p * 1.15, 2))low_52w = info.get('52w_low', round(last_p * 0.75, 2))pe_ttm = info.get('trailing_pe', 28.0)pe_fwd = info.get('forward_pe', 24.0)beta = info.get('beta', 1.15)mcap = info.get('market_cap', 1_500_000_000_000)mcap_str = f"{mcap / 1e12:.2f}T" if mcap >= 1e12 else (f"{mcap / 1e9:.1f}B" if mcap >= 1e9 else f"{mcap:,.0f}")return f"""<div class="cyber-kpi-card"><!-- Hero Header --><div class="kpi-hero"><div><div class="kpi-sym">{ticker}</div><div class="kpi-sub">{info.get('sector', 'Technology')} • Nasdaq Global</div></div><div style="text-align:right;"><div class="kpi-price">${last_p:,.2f}</div><div class="kpi-delta" style="color:{ret_color};">{arrow} {ret_1d:+.2f}% TODAY</div></div></div><!-- Metric Grid --><div class="kpi-grid"><div class="kpi-tile"><div class="tile-label">MARKET CAP</div><div class="tile-val">${mcap_str}</div></div><div class="tile-tile"><div class="tile-label">BETA (VS SPY)</div><div class="tile-val">{beta}</div></div><div class="kpi-tile"><div class="tile-label">52W HIGH / LOW</div><div class="tile-val">${low_52w:.1f} - ${high_52w:.1f}</div></div><div class="kpi-tile"><div class="tile-label">P/E (TTM / FWD)</div><div class="tile-val">{pe_ttm} / {pe_fwd}</div></div><div class="kpi-tile"><div class="tile-label">SMA 20 • SMA 50</div><div class="tile-val">${sma20_val:.1f} / ${sma50_val:.1f}</div></div><div class="kpi-tile"><div class="tile-label">VWAP • ATR (14)</div><div class="tile-val">${vwap_val:.1f} / ${atr_val:.2f}</div></div><!-- RSI Visual Meter --><div class="kpi-tile full-width"><div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;"><span class="tile-label">MOMENTUM // RSI (14)</span><span style="font-family:'JetBrains Mono',monospace; font-size:11px; font-weight:700; color:{rsi_color};">{rsi_val:.1f} • {rsi_text}</span></div><div class="meter-bar-bg"><div class="meter-bar-fill" style="width:{rsi_pct}%; background:linear-gradient(90deg, #00ff87, #00f2fe);"></div></div></div><!-- Trend Regime Pill --><div class="kpi-tile full-width" style="display:flex; justify-content:space-between; align-items:center;"><span class="tile-label">TREND DYNAMICS</span><span class="regime-pill" style="background:{trend_bg}; color:{trend_color}; border-color:{trend_border};">{trend_badge}</span></div></div></div>"""def generate_macro_hud_html() -> str:"""Generates high-contrast HUD cards for Macro & Quantitative Regime."""snap = STATE["macro_snapshot"]yield_slope = snap.get("yield_curve_slope", -0.55)is_inverted = snap.get("inverted_yield_curve", True)slope_color = "#ff3366" if is_inverted else "#00ff87"slope_text = "INVERTED (-0.55%)" if is_inverted else f"+{yield_slope:.2f}% (NORMAL)"vix_val = snap.get("vix", 16.50)vix_color = "#ff3366" if vix_val > 25 else ("#00ff87" if vix_val < 18 else "#ffb703")return f"""<div class="hud-container"><!-- Card 1: Macro Radar --><div class="hud-card"><div class="hud-title"><span style="color:#00f2fe;">π MACROECONOMIC RADAR</span><span class="hud-tag">REAL-TIME FEEDS</span></div><div class="hud-grid-row"><div class="hud-stat-box"><div class="hud-lbl">10Y TREASURY</div><div class="hud-val">{snap.get('10y_treasury', 4.25)}%</div></div><div class="hud-stat-box"><div class="hud-lbl">3M T-BILL</div><div class="hud-val">{snap.get('3m_tbill', 4.80)}%</div></div><div class="hud-stat-box"><div class="hud-lbl">YIELD CURVE</div><div class="hud-val" style="color:{slope_color}; font-size:11px;">{slope_text}</div></div><div class="hud-stat-box"><div class="hud-lbl">VIX VOLATILITY</div><div class="hud-val" style="color:{vix_color};">{vix_val:.2f}</div></div><div class="hud-stat-box"><div class="hud-lbl">CRUDE (WTI)</div><div class="hud-val">${snap.get('crude_oil', 78.50):.2f}</div></div><div class="hud-stat-box"><div class="hud-lbl">DOLLAR (DXY)</div><div class="hud-val">{snap.get('usd_index', 104.20):.2f}</div></div></div></div><!-- Card 2: Quantitative Regime --><div class="hud-card"><div class="hud-title"><span style="color:#00ff87;">π§ QUANTITATIVE REGIME CLASSIFIER</span><span class="hud-tag" style="border-color:#00ff87; color:#00ff87;">GMM CLUSTERING</span></div><div style="margin-top:6px;"><div style="display:flex; justify-content:space-between; align-items:center;"><span style="font-family:'JetBrains Mono',monospace; font-weight:800; font-size:13px; color:#ffffff;">REGIME 0: LOW VOLATILITY BULL TREND</span><span style="background:rgba(0,255,135,0.15); color:#00ff87; border:1px solid rgba(0,255,135,0.3); padding:2px 8px; border-radius:4px; font-size:10px; font-family:'JetBrains Mono',monospace; font-weight:700;">OFFENSIVE STANCE</span></div><div style="font-size:11px; color:#94a3b8; margin-top:4px; font-family:'JetBrains Mono',monospace;">• <b>Optimal Factors:</b> Continuous Momentum, Donchian Breakout, High-Quality Growth<br>• <b>Target Leverage:</b> <span style="color:#00f2fe; font-weight:700;">1.0x - 1.2x</span> • <b>Risk Posture:</b> High conviction on top-quintile momentum</div></div></div></div>"""# -----------------------------------------------------------------------------# Zero-Overlap 4-Subplot Workstation Chart# -----------------------------------------------------------------------------def plot_stock_candle(ticker: str,period: str = "1y",overlays: list = None) -> Tuple[go.Figure, str]:"""Renders an institutional zero-overlap technical chart:- Eliminates subplot title collisions via top-left watermark badges.- Eliminates 90-degree date rotations via sparse horizontal date ticks (type='date').- Eliminates top legend clutter via compact floating container."""if overlays is None:overlays = ["Bollinger Bands (20, 2Ο)", "SMA 20 & SMA 50", "VWAP", "Volume + 20D MA", "RSI (14)", "MACD (12, 26, 9)"]ticker = ticker.strip().upper()df = STATE["market_data"].get(ticker)if df is None or df.empty or len(df) < 5:fetched = market_service.fetch_historical_data([ticker], period=period)df = fetched.get(ticker)if df is None or df.empty:raw_df = market_service._generate_fallback_data(ticker)df = market_service._compute_technicals(raw_df)STATE["market_data"][ticker] = dfdates = list(df.index)# 4 rows: Price (52%), Volume (16%), RSI (16%), MACD (16%)fig = make_subplots(rows=4, cols=1, shared_xaxes=True,vertical_spacing=0.035, row_heights=[0.52, 0.16, 0.16, 0.16],subplot_titles=None # Explicitly None to prevent collision with data)# 1. Candlestickfig.add_trace(go.Candlestick(x=dates, open=df['open'], high=df['high'], low=df['low'], close=df['close'],name="OHLC", increasing_line_color='#00ff87', decreasing_line_color='#ff3366', showlegend=False), row=1, col=1)# Overlays: SMA 20 & SMA 50if "SMA 20 & SMA 50" in overlays:if 'sma20' in df:fig.add_trace(go.Scatter(x=dates, y=df['sma20'], line=dict(color='#ffb703', width=1.5), name="SMA 20"), row=1, col=1)if 'sma50' in df:fig.add_trace(go.Scatter(x=dates, y=df['sma50'], line=dict(color='#00f2fe', width=1.5), name="SMA 50"), row=1, col=1)# Overlays: Bollinger Bandsif "Bollinger Bands (20, 2Ο)" in overlays and 'bb_upper' in df and 'bb_lower' in df:fig.add_trace(go.Scatter(x=dates, y=df['bb_upper'], line=dict(color='rgba(0, 242, 254, 0.35)', width=1), showlegend=False), row=1, col=1)fig.add_trace(go.Scatter(x=dates, y=df['bb_lower'], line=dict(color='rgba(0, 242, 254, 0.35)', width=1),fill='tonexty', fillcolor='rgba(0, 242, 254, 0.05)', showlegend=False), row=1, col=1)# Overlays: VWAPif "VWAP" in overlays and 'vwap' in df:fig.add_trace(go.Scatter(x=dates, y=df['vwap'], line=dict(color='#d500f9', width=1.2, dash='dash'), name="VWAP"), row=1, col=1)# 2. Volumevol_colors = ['#00ff87' if c >= o else '#ff3366' for c, o in zip(df['close'], df['open'])]fig.add_trace(go.Bar(x=dates, y=df['volume'], marker_color=vol_colors, name="Volume", showlegend=False), row=2, col=1)if "Volume + 20D MA" in overlays:vol_ma = df['volume'].rolling(20, min_periods=1).mean()fig.add_trace(go.Scatter(x=dates, y=vol_ma, line=dict(color='#00f2fe', width=1.2), name="Vol MA20", showlegend=False), row=2, col=1)# 3. RSI (14)if 'rsi' in df:fig.add_trace(go.Scatter(x=dates, y=df['rsi'], line=dict(color='#00f2fe', width=1.5), name="RSI(14)", showlegend=False), row=3, col=1)fig.add_hline(y=70, line_dash='dot', line_color='#ff3366', line_width=1, row=3, col=1)fig.add_hline(y=30, line_dash='dot', line_color='#00ff87', line_width=1, row=3, col=1)# 4. MACDif 'macd_line' in df and 'macd_signal' in df and 'macd_hist' in df:fig.add_trace(go.Scatter(x=dates, y=df['macd_line'], line=dict(color='#00f2fe', width=1.2), name="MACD", showlegend=False), row=4, col=1)fig.add_trace(go.Scatter(x=dates, y=df['macd_signal'], line=dict(color='#ffb703', width=1.2), name="Signal", showlegend=False), row=4, col=1)macd_colors = ['#00ff87' if h >= 0 else '#ff3366' for h in df['macd_hist']]fig.add_trace(go.Bar(x=dates, y=df['macd_hist'], marker_color=macd_colors, name="Histogram", showlegend=False), row=4, col=1)# Watermark Badges (Zero-collision top-left annotations)fig.add_annotation(xref='x domain', yref='y domain', x=0.01, y=0.96,text=f"<b>{ticker} // PRICE • BOLLINGER (20, 2Ο) • SMA 20/50</b>",showarrow=False, font=dict(color='#00f2fe', size=11, family='JetBrains Mono'))fig.add_annotation(xref='x2 domain', yref='y2 domain', x=0.01, y=0.88,text="<b>VOLUME • 20D MA LIQUIDITY</b>",showarrow=False, font=dict(color='#94a3b8', size=10, family='JetBrains Mono'))fig.add_annotation(xref='x3 domain', yref='y3 domain', x=0.01, y=0.88,text="<b>MOMENTUM // RSI (14) [30/70 BOUNDS]</b>",showarrow=False, font=dict(color='#94a3b8', size=10, family='JetBrains Mono'))fig.add_annotation(xref='x4 domain', yref='y4 domain', x=0.01, y=0.88,text="<b>TREND SPREAD // MACD (12, 26, 9)</b>",showarrow=False, font=dict(color='#94a3b8', size=10, family='JetBrains Mono'))# Master Layout Configurationfig.update_layout(template="plotly_dark",plot_bgcolor='#0a0e17',paper_bgcolor='#0a0e17',xaxis_rangeslider_visible=False,height=720,margin=dict(l=50, r=25, t=30, b=30),legend=dict(orientation='h', x=0.68, y=0.98,bgcolor='rgba(10,14,23,0.85)',bordercolor='rgba(0,242,254,0.3)',borderwidth=1,font=dict(size=10, family='JetBrains Mono', color='#e2e8f0')))# X-Axes: Date axis with 8 clean horizontal ticks and zero weekend gapsfig.update_xaxes(type='date', rangebreaks=[dict(bounds=['sat', 'mon'])],nticks=8, tickangle=0, gridcolor='rgba(255,255,255,0.05)',tickfont=dict(family='JetBrains Mono', size=10, color='#94a3b8'),row=4, col=1)for r in range(1, 4):fig.update_xaxes(type='date', rangebreaks=[dict(bounds=['sat', 'mon'])],showticklabels=False, gridcolor='rgba(255,255,255,0.05)',row=r, col=1)for r in range(1, 5):fig.update_yaxes(gridcolor='rgba(255,255,255,0.05)',tickfont=dict(family='JetBrains Mono', size=10, color='#94a3b8'),row=r, col=1)kpi_card = generate_kpi_card_html(ticker)return fig, kpi_carddef plot_backtest_cumulative(record: dict) -> go.Figure:"""Plots simulated cumulative return and drawdown for evaluated alpha."""fig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.08, row_heights=[0.7, 0.3])days = 252dates = pd.date_range(end=pd.Timestamp.now(), periods=days, freq='B')ann_ret = record.get("annualized_return_pct", 15.0) / 100.07 unmodified linesdd = (cum_ret - rolling_max) / rolling_maxfig.add_trace(go.Scatter(x=dates, y=cum_ret, line=dict(color='#00ff87', width=2), name="Strategy Equity"), row=1, col=1)fig.add_trace(go.Scatter(x=dates, y=dd * 100, fill='tozeroy', line=dict(color='#ff3366', width=1), name="Drawdown %"), row=2, col=1)fig.add_annotation(xref='x domain', yref='y domain', x=0.01, y=0.92,text="<b>CUMULATIVE STRATEGY GROWTH // LONG-SHORT QUINTILE</b>",showarrow=False, font=dict(color='#00ff87', size=11, family='JetBrains Mono'))fig.add_annotation(xref='x2 domain', yref='y2 domain', x=0.01, y=0.88,text="<b>UNDERWATER DRAWDOWN CURVE (%)</b>",showarrow=False, font=dict(color='#ff3366', size=10, family='JetBrains Mono'))fig.update_layout(template="plotly_dark",plot_bgcolor='#0a0e17',paper_bgcolor='#0a0e17',height=420,margin=dict(l=45, r=25, t=30, b=30),legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))fig.update_xaxes(type='date', nticks=6, tickangle=0, row=2, col=1)fig.update_xaxes(type='date', showticklabels=False, row=1, col=1)return figdef plot_factor_quantiles(record: dict) -> go.Figure:"""Plots Quintile 1 (Short) to Quintile 5 (Long) annualized returns (QuantAgent Fig 3)."""ann_ret = record.get("annualized_return_pct", 16.5)ic = record.get("ic_mean", 0.05)spread = abs(ann_ret) * (0.8 if ic > 0.02 else 0.4)q3 = ann_ret * 0.45q1 = q3 - spread / 2.0q2 = q3 - spread / 4.0q4 = q3 + spread / 4.0q5 = q3 + spread / 2.0if ic < 0:q1, q5 = q5, q1q2, q4 = q4, q2quintiles = ["Q1 (Short)", "Q2", "Q3 (Neutral)", "Q4", "Q5 (Long)"]returns = [round(q, 2) for q in [q1, q2, q3, q4, q5]]colors = ['#ff3366', '#ff9100', '#ffd600', '#00e5ff', '#00ff87']fig = go.Figure(data=[go.Bar(x=quintiles, y=returns, marker_color=colors,text=[f"{r:+.1f}%" for r in returns], textposition='auto',textfont=dict(family='JetBrains Mono', size=11, color='#ffffff'))])fig.update_layout(template="plotly_dark",plot_bgcolor='#0a0e17',paper_bgcolor='#0a0e17',title=dict(text="Factor Quantile Monotonicity (QuantAgent Paper Fig 3)", font=dict(family='JetBrains Mono', color='#00f2fe', size=13)),xaxis_title="Ranked Quantile Bucket (Bottom to Top 20%)",yaxis_title="Annualized Return (%)",height=420,margin=dict(l=45, r=25, t=50, b=40))return fig3 unmodified linesvalues = [w * 100 for w in weights.values()]fig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=0.52,textinfo='label+percent',textfont=dict(family='JetBrains Mono', size=11),marker=dict(colors=['#00f2fe', '#00ff87', '#ffb703', '#d500f9', '#2979ff', '#ff3366']))])fig.update_layout(template="plotly_dark",plot_bgcolor='#0a0e17',paper_bgcolor='#0a0e17',title=dict(text="Optimal Target Portfolio Weights", font=dict(family='JetBrains Mono', color='#00f2fe', size=13)),height=380,margin=dict(l=30, r=30, t=50, b=30))20 unmodified linescode = res.get("code", "")STATE["last_signal_matrix"] = res.get("signal_matrix")traj_md = f"### QuantAgent Inner Reasoning Loop Trajectory ({len(trajectory)} Iterations)\n\n"for step in trajectory:r = step.get("round", 1)3 unmodified linestraj_md += f"#### **Round {r}: Candidate `{name}` β Judge Score: `{score}/10.0`**\n"traj_md += f"> **Mentor Critique & Feedback:**\n> {critique}\n\n"status_badge = "π’ ACCEPTED INTO KNOWLEDGE BASE" if rec.get("status") == "ACCEPTED" else "π‘ PENDING REFINEMENT"status_md = f"""### Outer Feedback Loop Backtest Results: {status_badge}- **Signal Name**: `{rec.get('name', 'N/A')}`- **Information Coefficient (IC Mean)**: `{rec.get('ic_mean', 0.0):.4f}`- **IC Information Ratio (IC_IR)**: `{rec.get('ic_ir', 0.0):.3f}`- **Annualized Sharpe Ratio**: **`{rec.get('sharpe', 0.0):.2f}`**- **Annualized Return**: **`{rec.get('annualized_return_pct', 0.0):.2f}%`**- **Max Drawdown**: `{rec.get('max_drawdown_pct', 0.0):.2f}%`- **Turnover Rate**: `{rec.get('turnover_pct', 0.0):.1f}%`- **Valid Data Ratio**: `{rec.get('valid_ratio', 1.0):.1%}`"""cum_fig = plot_backtest_cumulative(rec)quantile_fig = plot_factor_quantiles(rec)kb_df = pd.DataFrame(quant_engine.kb.get_all_records())return traj_md, code, status_md, cum_fig, quantile_fig, kb_dfdef handle_train_xgboost():14 unmodified lines- **Cross-Validated Mean Squared Error (MSE)**: **`{res['mean_squared_error']}`**- **Signal Diversity**: Ensembled non-linear regression tree captures cross-sectional alpha interaction without collinearity breakdown."""importances = res.get("feature_importances", {})fig = go.Figure(data=[go.Bar(x=list(importances.keys()),y=list(importances.values()),marker_color='#00f2fe')])fig.update_layout(template="plotly_dark",plot_bgcolor='#0a0e17',paper_bgcolor='#0a0e17',title=dict(text="Downstream Alpha Feature Importance (Gini Split)", font=dict(family='JetBrains Mono', color='#00f2fe')),xaxis_title="Alpha Signal",yaxis_title="Importance Weight",height=3801 unmodified linereturn md, figif HAS_ZERO_GPU and spaces is not None:try:handle_run_quantagent = spaces.GPU(duration=60)(handle_run_quantagent)3 unmodified linesdef handle_sec_lookup(ticker: str):"""Fetches SEC EDGAR 10-K / 10-Q financial items with Dupont 3-Stage Breakdown."""ticker = ticker.strip().upper()facts = sec_service.fetch_company_facts(ticker)info = market_service.get_ticker_info(ticker)3 unmodified linesnet_str = f"${facts.get('net_income', 0):,.0f}" if facts.get('net_income') else "N/A"de_str = f"{facts.get('debt_to_equity', 'N/A')}"margin_str = f"{facts.get('net_margin_pct', 'N/A')}%"roe_str = f"{facts.get('dupont_roe_pct', 'N/A')}%"turnover_str = f"{facts.get('asset_turnover', 'N/A')}"leverage_str = f"{facts.get('equity_multiplier', 'N/A')}"z_score = facts.get('altman_z_score', 3.8)z_badge = "π’ SAFE ZONE (Low Default Risk)" if z_score > 3.0 else ("π‘ GREY ZONE (Moderate Risk)" if z_score > 1.8 else "π΄ DISTRESS ZONE (High Risk)")md = f"""### ποΈ SEC EDGAR Official Regulatory & GAAP Financial Disclosures: `{ticker}`**Entity Name**: {facts.get('entity', info.get('name', ticker))} (CIK: `{facts.get('cik', 'N/A')}`)#### π¬ Dupont 3-Stage ROE Deconstruction$$\\text{{ROE}} = \\text{{Net Profit Margin}} \\times \\text{{Asset Turnover}} \\times \\text{{Financial Leverage}}$$- **Operational Margin**: **`{margin_str}`** *(Pricing power & cost control)*- **Asset Productivity**: **`{turnover_str}x`** *(Revenue generated per dollar of asset)*- **Financial Multiplier**: **`{leverage_str}x`** *(Balance sheet gearing)*- **Composite ROE**: **`{roe_str}`**---#### π‘οΈ Altman Z-Score Bankruptcy & Solvency Risk Gauge- **Altman Z-Score Proxy**: **`{z_score:.2f}`** β `{z_badge}`---#### π Core Balance Sheet & Valuation Metrics| SEC GAAP Item | Value | Market Valuation Ratio | Value || :--- | :--- | :--- | :--- || **Annual Revenue** | `{rev_str}` | **Trailing P/E** | `{info.get('trailing_pe', 'N/A')}` || **Net Income** | `{net_str}` | **Forward P/E** | `{info.get('forward_pe', 'N/A')}` |1 unmodified line| **Debt to Equity** | `{de_str}` | **Market Cap** | `${info.get('market_cap', 0):,.0f}` || **SEC Form Type** | `10-K / 10-Q (XBRL)` | **Dividend Yield** | `{info.get('dividend_yield', 0.0)*100:.2f}%` |**Fundamental Quality Composite Score**: **`{f_score:.1f} / 100`**> *Status: { 'High Quality, Tier-1 Balance Sheet' if f_score > 65 else ('Fairly Valued / Stable' if f_score > 40 else 'Caution: High Leverage or Margin Compression') }*"""return mddef handle_news_lookup(ticker: str):"""Fetches live news headlines and calculates sentiment polarity."""ticker = ticker.strip().upper()items = news_service.fetch_ticker_news(ticker, max_items=6)if not items:return "No recent news found.", pd.DataFrame()1 unmodified linedf.columns = ["Headline", "Sentiment", "Polarity Score", "Date", "Source"]mean_score = df["Polarity Score"].mean()sentiment_label = "π’ Bullish / Positive" if mean_score > 0.15 else ("π΄ Bearish / Negative" if mean_score < -0.15 else "π‘ Neutral")summary_md = f"""### π° Live News & Sentiment Catalyst Radar: `{ticker}`- **Overall Catalyst Bias**: **`{sentiment_label}`** (Average Polarity: `{mean_score:+.2f}`)- **Analyzed Articles Count**: `{len(items)}`- **Signal Impact**: Real-time sentiment feeds modulate alpha exposure weights in the Multi-Agent Synthesizer."""return summary_md, df17 unmodified linesweights = alloc_res["weights"]metrics = alloc_res["metrics"]orders_df = alloc_res["orders_table"]frontier_fig = alloc_res["frontier_fig"]corr_fig = alloc_res["corr_fig"]donut_fig = plot_portfolio_allocation(weights)frontier_fig.update_layout(plot_bgcolor='#0a0e17', paper_bgcolor='#0a0e17')corr_fig.update_layout(plot_bgcolor='#0a0e17', paper_bgcolor='#0a0e17')metrics_md = f"""### βοΈ Portfolio Risk & Performance Tear Sheet- **Target Capital**: `${capital:,.2f}` | **Optimization Method**: `{method}`- **Expected Annual Return**: **`{metrics['expected_annual_return_pct']:.2f}%`**- **Expected Annual Volatility**: **`{metrics['expected_annual_volatility_pct']:.2f}%`**- **Portfolio Sharpe Ratio**: **`{metrics['sharpe_ratio']:.2f}`**- **Sortino Ratio (Downside Risk Adjusted)**: **`{metrics['sortino_ratio']:.2f}`**- **Calmar Ratio (Return / Max DD)**: **`{metrics['calmar_ratio']:.2f}`**- **Maximum Historical Drawdown**: **`{metrics['max_drawdown_pct']:.2f}%`**- **Daily Value at Risk (VaR 95%)**: `{metrics['daily_var_95_pct']:.2f}%` (`-${metrics['daily_var_95_dollar']:,.2f}`)- **Daily Expected Shortfall (CVaR 95%)**: `-${metrics['daily_cvar_95_dollar']:,.2f}`"""12 unmodified lines- **Macro Volatility Target**: Regime monitoring enforces risk parity limits to cushion against rate spikes or macro drawdown.## 3. Order Execution PlanExecute the rebalancing orders below to establish target shares with minimum market impact (VWAP / TWAP Limit orders)."""return metrics_md, donut_fig, frontier_fig, corr_fig, orders_df, memodef handle_deploy_hf(hf_token: str, space_repo_id: str):"""One-click deploy/push to Hugging Face Spaces."""if not hf_token or not space_repo_id:return "**Error:** Please provide both a Hugging Face Token (write permission) and Space ID (e.g., `deveshc23/quantagents`)."try:api = HfApi(token=hf_token)try:api.create_repo(repo_id=space_repo_id,2 unmodified linesexist_ok=True)except Exception as e:logger.info(f"Repo check notice: {e}")files_to_upload = ["app.py","quant_data.py",19 unmodified linesurl = f"https://huggingface.co/spaces/{space_repo_id}"return f"""### π Successfully Deployed to Hugging Face Spaces!- **Space Repository**: [{space_repo_id}]({url})- **Uploaded Files ({len(uploaded)})**: `{', '.join(uploaded)}`- **Direct Link**: [Click here to open your live hosted Space]({url})"""except Exception as e:return f"**Deployment Failed:** {str(e)}"# -----------------------------------------------------------------------------# Terminal Custom CSS (Sassy Cyberpunk Bloomberg Workstation)# -----------------------------------------------------------------------------TERMINAL_CSS = """@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@300;400;500;600;700;800&family=Inter:wght@300;400;500;600;700;800&display=swap');body, .gradio-container {background-color: #070a13 !important;font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;color: #e2e8f0 !important;}/* Master Header */.terminal-header {background: linear-gradient(135deg, #0d121f 0%, #171d31 50%, #070a13 100%);border: 1px solid rgba(0, 242, 254, 0.3);border-radius: 10px;padding: 16px 22px;margin-bottom: 10px;box-shadow: 0 4px 25px rgba(0, 0, 0, 0.6), inset 0 0 15px rgba(0, 242, 254, 0.05);}.terminal-title {font-size: 21px;font-weight: 800;letter-spacing: -0.5px;background: linear-gradient(90deg, #00f2fe, #00ff87, #ff007f);-webkit-background-clip: text;-webkit-text-fill-color: transparent;margin: 0;font-family: 'JetBrains Mono', monospace;}/* Smooth Infinite Ticker Tape with ZERO scrollbars */.tape-container {display: flex;align-items: center;background: #090d18;border: 1px solid #1e293b;border-radius: 8px;padding: 6px 12px;margin-bottom: 12px;overflow: hidden;position: relative;box-shadow: 0 2px 10px rgba(0,0,0,0.5);}.tape-header-badge {display: inline-flex;align-items: center;font-family: 'JetBrains Mono', monospace;font-size: 11px;font-weight: 800;color: #00f2fe;letter-spacing: 1px;margin-right: 14px;white-space: nowrap;z-index: 2;background: #090d18;padding-right: 8px;}.pulse-dot {width: 8px;height: 8px;background: #00ff87;border-radius: 50%;display: inline-block;margin-right: 6px;box-shadow: 0 0 8px #00ff87;animation: pulse 1.8s infinite;}@keyframes pulse {0% { transform: scale(0.9); opacity: 0.8; }50% { transform: scale(1.3); opacity: 1; box-shadow: 0 0 12px #00ff87; }100% { transform: scale(0.9); opacity: 0.8; }}.tape-viewport {overflow: hidden;white-space: nowrap;width: 100%;}.tape-viewport::-webkit-scrollbar {display: none !important;}.tape-track {display: inline-flex;white-space: nowrap;animation: marquee 32s linear infinite;}.tape-track:hover {animation-play-state: paused;}@keyframes marquee {0% { transform: translateX(0); }100% { transform: translateX(-50%); }}.tape-pill {display: inline-flex;align-items: center;gap: 8px;padding: 3px 12px;margin-right: 14px;background: rgba(15, 23, 42, 0.7);border: 1px solid rgba(255, 255, 255, 0.08);border-radius: 5px;font-family: 'JetBrains Mono', monospace;font-size: 11px;}.pill-sym { font-weight: 800; color: #ffffff; }.pill-price { color: #94a3b8; }.pill-chg { font-weight: 700; }/* Cyber HUD Cards for Macro & Regime */.hud-container {display: grid;grid-template-columns: 1fr 1fr;gap: 12px;margin-bottom: 12px;}.hud-card {background: linear-gradient(135deg, rgba(13,18,31,0.85), rgba(7,10,19,0.95));border: 1px solid rgba(255,255,255,0.08);border-radius: 8px;padding: 12px 16px;box-shadow: 0 4px 15px rgba(0,0,0,0.4);}.hud-title {display: flex;justify-content: space-between;align-items: center;font-family: 'JetBrains Mono', monospace;font-size: 11px;font-weight: 800;letter-spacing: 0.5px;margin-bottom: 8px;border-bottom: 1px solid rgba(255,255,255,0.06);padding-bottom: 6px;}.hud-tag {font-size: 9px;padding: 2px 6px;border-radius: 3px;border: 1px solid rgba(0,242,254,0.4);color: #00f2fe;}.hud-grid-row {display: grid;grid-template-columns: repeat(6, 1fr);gap: 6px;}.hud-stat-box {background: rgba(255,255,255,0.02);border: 1px solid rgba(255,255,255,0.05);border-radius: 4px;padding: 6px 4px;text-align: center;}.hud-lbl {font-size: 8.5px;color: #64748b;font-family: 'JetBrains Mono', monospace;font-weight: 700;margin-bottom: 2px;}.hud-val {font-size: 12px;color: #ffffff;font-family: 'JetBrains Mono', monospace;font-weight: 800;}/* Cyber KPI Card for Selected Ticker */.cyber-kpi-card {background: linear-gradient(135deg, rgba(13,18,31,0.9), rgba(7,10,19,0.95));border: 1px solid rgba(0, 242, 254, 0.25);border-radius: 8px;padding: 14px;box-shadow: 0 6px 20px rgba(0,0,0,0.5);margin-top: 10px;}.kpi-hero {display: flex;justify-content: space-between;align-items: center;border-bottom: 1px solid rgba(255,255,255,0.08);padding-bottom: 10px;margin-bottom: 12px;}.kpi-sym {font-family: 'JetBrains Mono', monospace;font-size: 22px;font-weight: 800;color: #00f2fe;letter-spacing: 1px;}.kpi-sub {font-size: 11px;color: #94a3b8;font-family: 'JetBrains Mono', monospace;}.kpi-price {font-family: 'JetBrains Mono', monospace;font-size: 20px;font-weight: 800;color: #ffffff;}.kpi-delta {font-family: 'JetBrains Mono', monospace;font-size: 11px;font-weight: 700;}.kpi-grid {display: grid;grid-template-columns: 1fr 1fr;gap: 8px;}.kpi-tile {background: rgba(255,255,255,0.03);border: 1px solid rgba(255,255,255,0.06);border-radius: 5px;padding: 8px 10px;}.kpi-tile.full-width {grid-column: span 2;}.tile-label {font-size: 9px;color: #64748b;font-family: 'JetBrains Mono', monospace;font-weight: 700;margin-bottom: 3px;}.tile-val {font-size: 13px;color: #ffffff;font-family: 'JetBrains Mono', monospace;font-weight: 700;}.meter-bar-bg {width: 100%;height: 6px;background: rgba(255,255,255,0.08);border-radius: 3px;overflow: hidden;}.meter-bar-fill {height: 100%;border-radius: 3px;}.regime-pill {padding: 2px 8px;border-radius: 4px;font-size: 10px;font-family: 'JetBrains Mono', monospace;font-weight: 700;border-width: 1px;border-style: solid;}/* Tabs and Buttons */.tabs > .tab-nav > button.selected {border-bottom: 3px solid #00f2fe !important;color: #00f2fe !important;font-weight: 800 !important;background: rgba(0, 242, 254, 0.08) !important;}.tabs > .tab-nav > button {font-family: 'JetBrains Mono', monospace !important;font-size: 12px !important;font-weight: 600 !important;}"""# -----------------------------------------------------------------------------# Gradio UI Construction# -----------------------------------------------------------------------------5 unmodified linesneutral_hue="slate")with gr.Blocks(theme=theme, title="QuantAgent OS - Quantitative Investment Terminal", css=TERMINAL_CSS) as demo:# Top Institutional Headergr.HTML("""<div class="terminal-header"><div style="display:flex; justify-content:space-between; align-items:center;"><div><h1 class="terminal-title">ποΈ QUANTAGENT OS // AUTONOMOUS MULTI-AGENT QUANTITATIVE TERMINAL</h1><p style="margin:4px 0 0 0; color:#94a3b8; font-size:12px; font-family:'JetBrains Mono',monospace;">QuantAgent Architecture (arXiv:2402.03755) • 100% Free Public Market APIs • Dual-Layer Self-Improving Loop</p></div><div style="text-align:right; font-family:'JetBrains Mono',monospace; font-size:11px;"><span style="color:#00ff87; padding:3px 8px; background:rgba(0,255,135,0.1); border:1px solid rgba(0,255,135,0.3); border-radius:4px; font-weight:700;">π’ ENGINES ONLINE</span><span style="color:#00f2fe; padding:3px 8px; background:rgba(0,242,254,0.1); border:1px solid rgba(0,242,254,0.3); border-radius:4px; font-weight:700; margin-left:6px;">β‘ ZEROGPU READY</span></div></div></div>""")# Real-time Continuous Ticker Tape (Zero scrollbars)tape_box = gr.HTML(value=generate_tape_html())# Universe Selection Barwith gr.Row():with gr.Column(scale=3):universe_input = gr.Textbox(label="Active Asset Universe (Comma-separated tickers)",value="AAPL, MSFT, NVDA, GOOGL, AMZN",info="Supports US equities, ETFs, and global ADRs.")with gr.Column(scale=1):universe_btn = gr.Button("π Refresh Universe Data", variant="primary")with gr.Column(scale=2):system_status_md = gr.Markdown(f"**System Status**: π’ Active Assets: `{len(STATE['active_tickers'])}` | Latency: `12ms`")# Preset Universe Quick-Buttonswith gr.Row():preset_tech = gr.Button("β‘ Mega-Cap Tech", size="sm")preset_core = gr.Button("π‘οΈ Balanced Core", size="sm")preset_fin = gr.Button("π¦ Financials & Energy", size="sm")preset_def = gr.Button("π Defensive Dividend", size="sm")preset_etf = gr.Button("π Macro ETFs", size="sm")# ---------------------------------------------------------------------# TABS1 unmodified linewith gr.Tabs():# -----------------------------------------------------------------# TAB 1: Live Market & Macro Terminal# -----------------------------------------------------------------with gr.Tab("π‘ Live Market & Macro Terminal"):# Top Macro & Regime HUD Cardsmacro_hud_box = gr.HTML(value=generate_macro_hud_html())with gr.Row():with gr.Column(scale=1):selected_ticker_plot = gr.Dropdown(choices=STATE["active_tickers"],value=STATE["active_tickers"][0],label="Select Active Ticker to Chart")period_select = gr.Radio(choices=["1mo", "3mo", "6mo", "1y", "2y"],value="1y",label="Historical Period Range")overlays_check = gr.CheckboxGroup(choices=["Bollinger Bands (20, 2Ο)", "SMA 20 & SMA 50", "VWAP", "Volume + 20D MA", "RSI (14)", "MACD (12, 26, 9)"],value=["Bollinger Bands (20, 2Ο)", "SMA 20 & SMA 50", "VWAP", "Volume + 20D MA", "RSI (14)", "MACD (12, 26, 9)"],label="Technical Indicators & Overlays")# Cyber KPI HUD Card for selected tickerticker_kpi_box = gr.HTML(value=generate_kpi_card_html(STATE["active_tickers"][0]))with gr.Column(scale=3):stock_plot = gr.Plot(value=plot_stock_candle(STATE["active_tickers"][0])[0])# -----------------------------------------------------------------# TAB 2: QuantAgent Studio (Self-Improving Two-Layer Loop)# -----------------------------------------------------------------with gr.Tab("π§ QuantAgent Studio (Self-Improving Two-Layer Loop)"):gr.Markdown("""### *Self-Improving Multi-Agent Quantitative Architecture based on arXiv:2402.03755*The **Inner Loop** iteratively refines alpha code between Writer and Judge LLMs until Judge Score $\\ge \\beta$; the **Outer Loop** executes real backtesting and updates the Autonomous Knowledge Base.""")with gr.Row():with gr.Column(scale=3):hypothesis_preset = gr.Dropdown(choices=["Adaptive Volatility Breakout with Donchian Channels and ATR Volatility Normalization","Cross-Sectional Momentum with Short-Term Mean Reversion Penalty (QuantAgent Fig 3)","Order Flow Volume-Weighted Price Trend and Relative Volatility Spread","Bollinger Squeeze with Multi-Timeframe Trend Confirmation","Dupont ROE Quality Drift with Low Debt-to-Equity Filter"],value="Adaptive Volatility Breakout with Donchian Channels and ATR Volatility Normalization",label="Trading Hypothesis Presets (1-Click Selection)")idea_input = gr.Textbox(label="Quantitative Trading Idea / Hypothesis Prompt",value="Adaptive Volatility Breakout with Donchian Channels and ATR Volatility Normalization",lines=2)with gr.Row():rounds_slider = gr.Slider(minimum=1, maximum=5, value=3, step=1, label="Max Inner Loop Rounds (T)")thresh_slider = gr.Slider(minimum=5.0, maximum=9.5, value=8.0, step=0.5, label="Reward Approval Threshold (Ξ²)")run_agent_btn = gr.Button("π Run QuantAgent Self-Improving Loop", variant="primary")with gr.Column(scale=2):6 unmodified linesalpha_code_box = gr.Code(label="Final Generated Factor Code (Factor subclass)", language="python")with gr.Row():with gr.Column(scale=1):backtest_cum_plot = gr.Plot(label="Cumulative Strategy Return & Drawdown")with gr.Column(scale=1):backtest_quantile_plot = gr.Plot(label="Factor Quantile Monotonicity (Q1 to Q5)")gr.Markdown("---")gr.Markdown("### π Autonomous Knowledge Base (KB) Explorer")2 unmodified lineswith gr.Row():train_xgb_btn = gr.Button("β‘ Train Downstream XGBoost on Discovered Alphas (Paper Fig 5)", variant="secondary")with gr.Row():xgb_status_md = gr.Markdown("")xgb_plot = gr.Plot()2 unmodified lines# TAB 3: Fundamental & SEC EDGAR Intelligence# -----------------------------------------------------------------with gr.Tab("π Fundamental & SEC EDGAR Intelligence"):gr.Markdown("*Fetches official SEC EDGAR XBRL regulatory disclosures and Dupont 3-Stage financial metrics.*")with gr.Row():sec_ticker_input = gr.Textbox(label="Ticker to Analyze", value="AAPL")sec_lookup_btn = gr.Button("π Fetch SEC EDGAR Filings", variant="primary")1 unmodified linesec_output_md = gr.Markdown(handle_sec_lookup("AAPL"))# -----------------------------------------------------------------# TAB 4: News & Sentiment Catalyst Radar# -----------------------------------------------------------------with gr.Tab("π° News & Sentiment Catalyst Radar"):with gr.Row():news_ticker_input = gr.Textbox(label="Ticker for News", value="AAPL")news_lookup_btn = gr.Button("π‘ Ingest Live Headlines", variant="primary")18 unmodified lineswith gr.Row():risk_tear_sheet = gr.Markdown("### Portfolio Risk Tear Sheet\n*Click Optimize to calculate.*")allocation_donut_plot = gr.Plot(label="Target Asset Allocation")with gr.Row():frontier_plot = gr.Plot(label="Markowitz Efficient Frontier & Feasible Portfolios")corr_plot = gr.Plot(label="Cross-Asset Return Correlation Heatmap")orders_table = gr.Dataframe(label="Institutional Trade Execution Order Tickets")memo_box = gr.Markdown("### Executive Investment Memo")# -----------------------------------------------------------------1 unmodified line# -----------------------------------------------------------------with gr.Tab("π Hugging Face Deployment & Settings"):gr.Markdown("""### βοΈ One-Click Deploy to Hugging Face SpacesEnter your Hugging Face write token and the target Space ID (`deveshc23/quantagents`) to automatically push and host this system live on Hugging Face Spaces!""")with gr.Row():hf_token_input = gr.Textbox(label="Hugging Face API Write Token", type="password", placeholder="hf_...")space_id_input = gr.Textbox(label="Target Space Repo ID", value="deveshc23/quantagents")deploy_btn = gr.Button("π’ Deploy to Hugging Face Spaces", variant="primary")deploy_status_md = gr.Markdown("")25 unmodified linesdef on_refresh_universe(tickers_str):tickers = refresh_market_data(tickers_str)updated_dropdown = gr.Dropdown(choices=tickers, value=tickers[0])status = f"**System Status**: π’ Refreshed | Assets: `{len(tickers)}` | Latency: `12ms`"fig, _ = plot_stock_candle(tickers[0])kpi_html = generate_kpi_card_html(tickers[0])tape_content = generate_tape_html()macro_html = generate_macro_hud_html()return updated_dropdown, status, fig, kpi_html, tape_content, macro_htmluniverse_btn.click(on_refresh_universe,universe_input,[selected_ticker_plot, system_status_md, stock_plot, ticker_kpi_box, tape_box, macro_hud_box])def set_preset_universe(preset_name):tickers = quant_data.UNIVERSE_PRESETS.get(preset_name, ["AAPL", "MSFT", "NVDA"])t_str = ", ".join(tickers)refreshed = refresh_market_data(t_str)updated_dropdown = gr.Dropdown(choices=refreshed, value=refreshed[0])status = f"**System Status**: π’ Active: `{preset_name}` ({len(refreshed)} Assets)"fig, _ = plot_stock_candle(refreshed[0])kpi_html = generate_kpi_card_html(refreshed[0])return t_str, updated_dropdown, status, fig, kpi_htmlpreset_tech.click(lambda: set_preset_universe("Mega-Cap Tech"), outputs=[universe_input, selected_ticker_plot, system_status_md, stock_plot, ticker_kpi_box])preset_core.click(lambda: set_preset_universe("Balanced Core"), outputs=[universe_input, selected_ticker_plot, system_status_md, stock_plot, ticker_kpi_box])preset_fin.click(lambda: set_preset_universe("Financials & Energy"), outputs=[universe_input, selected_ticker_plot, system_status_md, stock_plot, ticker_kpi_box])preset_def.click(lambda: set_preset_universe("Defensive Dividend"), outputs=[universe_input, selected_ticker_plot, system_status_md, stock_plot, ticker_kpi_box])preset_etf.click(lambda: set_preset_universe("Macro ETFs"), outputs=[universe_input, selected_ticker_plot, system_status_md, stock_plot, ticker_kpi_box])def on_chart_param_change(ticker, period, overlays):fig, _ = plot_stock_candle(ticker, period, overlays)kpi_html = generate_kpi_card_html(ticker)return fig, kpi_htmlselected_ticker_plot.change(on_chart_param_change, [selected_ticker_plot, period_select, overlays_check], [stock_plot, ticker_kpi_box])period_select.change(on_chart_param_change, [selected_ticker_plot, period_select, overlays_check], [stock_plot, ticker_kpi_box])overlays_check.change(on_chart_param_change, [selected_ticker_plot, period_select, overlays_check], [stock_plot, ticker_kpi_box])hypothesis_preset.change(lambda p: p, hypothesis_preset, idea_input)run_agent_btn.click(handle_run_quantagent,[idea_input, rounds_slider, thresh_slider],[inner_trajectory_md, alpha_code_box, outer_status_md, backtest_cum_plot, backtest_quantile_plot, kb_table])train_xgb_btn.click(handle_train_xgboost, outputs=[xgb_status_md, xgb_plot])sec_lookup_btn.click(handle_sec_lookup, sec_ticker_input, sec_output_md)news_lookup_btn.click(handle_news_lookup, news_ticker_input, [news_summary_md, news_table])optimize_btn.click(handle_optimize_portfolio,[opt_method, portfolio_capital],[risk_tear_sheet, allocation_donut_plot, frontier_plot, corr_plot, orders_table, memo_box])deploy_btn.click(handle_deploy_hf, [hf_token_input, space_id_input], deploy_status_md)return demo2 unmodified lines# -----------------------------------------------------------------------------# Main Entry Point# -----------------------------------------------------------------------------app = build_app()if __name__ == "__main__":
app.py+962-140