Spaces:
Sleeping
Sleeping
V2.0: Multi-market, dark finance UI, options, pairs, macro, enhanced AI prompts
Browse files123456781 unmodified line101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263641 unmodified line66676869707172737475767778798081828 unmodified lines9192939495969798991001 unmodified line10210310410510610710810910 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016113 unmodified lines17517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321410 unmodified lines22522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232 unmodified lines3553563573583593603614 unmodified lines3663673683693703713723733741 unmodified line37637737837938038138218 unmodified lines40140240340440540640740840941041141241341434 unmodified lines44945045145245345445545645745845946013 unmodified lines4744754764774784794804814824834844854864874884894904914924934944954964974984995005015025038 unmodified lines5125135145155165175185 unmodified lines52452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660715 unmodified lines6236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137141 unmodified line7167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587593 unmodified lines7637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978982 unmodified lines9019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599 unmodified lines96997097197297397497517 unmodified lines9939949959969979989991000100110021003100410051006100710081009101026 unmodified lines1037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810693 unmodified lines1073107410751076107710781079108010811082108310841085108610871088108910902 unmodified lines10931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113712 unmodified lines11501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311743 unmodified lines117811791180118111821183118411851186118711886 unmodified lines11951196119711981199120012011202120312049 unmodified lines121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391 unmodified line12411242124312441245124612475 unmodified lines125312541255125612571258125920 unmodified lines12801281128212831284128512861287"""AlphaForge x K2 Think V2 — Institutional-Grade Quantitative Analysis PlatformMulti-market support: US, EU, Asia, Crypto, Forex, CommoditiesFinance-themed UI with dark mode, professional color schemeEnhanced features: Options pricing, Pairs Trading, Backtest, Macro AnalysisPowered by MBZUAI K2 Think V2 reasoning modelAPI Key: set via K2_API_KEY environment variable1 unmodified lineimport os, json, traceback, warnings, math, randomwarnings.filterwarnings('ignore')# Core imports with graceful fallback_import_errors = []try:import gradio as grexcept ImportError as e:_import_errors.append(f"gradio: {e}")gr = Nonetry:import requestsexcept ImportError as e:_import_errors.append(f"requests: {e}")requests = Nonetry:import yfinance as yfexcept ImportError as e:_import_errors.append(f"yfinance: {e}")yf = Nonetry:import pandas as pdpd.set_option('future.no_silent_downcasting', True)except ImportError as e:_import_errors.append(f"pandas: {e}")pd = Nonetry:import numpy as npexcept ImportError as e:_import_errors.append(f"numpy: {e}")np = Nonetry:import plotly.graph_objects as gofrom plotly.subplots import make_subplotsPLOTLY_OK = Trueexcept ImportError as e:_import_errors.append(f"plotly: {e}")PLOTLY_OK = Falsego = Nonemake_subplots = Nonefrom datetime import datetime, timedelta# ═══════════════════════════════════════════════════════════════# CONFIG# ═══════════════════════════════════════════════════════════════K2_API_KEY = os.environ.get("K2_API_KEY", "")K2_BASE_URL = "https://api.k2think.ai/v1/chat/completions"K2_MODEL = "MBZUAI-IFM/K2-Think-v2"# ═══════════════════════════════════════════════════════════════# K2 THINK V2 CLIENT — bulletproof# ═══════════════════════════════════════════════════════════════class K2ThinkClient:def __init__(self):self.api_key = K2_API_KEY1 unmodified lineself.base_url = K2_BASE_URLdef chat(self, messages, temperature=0.7, max_tokens=4096):if not self.available or requests is None:return """⚠️ **K2 Think V2 API Not Configured**To enable AI-powered analysis, configure the API key:1. Go to **Space Settings** → **Repository secrets**2. Click **New secret**3. Name: `K2_API_KEY`4. Value: `IFM-4SpQ0qEg0Wlsw04O`5. Click **Save**, then **Factory Rebuild**All technical analysis, charts, and risk metrics work without the API!"""payload = {"model": K2_MODEL, "messages": messages, "temperature": temperature,"max_tokens": max_tokens, "stream": False}8 unmodified linesreturn j['choices'][0]['message']['content']return f"⚠️ Unexpected format: {json.dumps(j, indent=2)[:400]}"except requests.exceptions.Timeout:return "⏱️ Timeout after 120s. API may be under high load. Try again."except requests.exceptions.HTTPError as e:if e.response.status_code == 401:return "🔐 Auth failed. Check K2_API_KEY secret in Space Settings."elif e.response.status_code == 429:return "🚦 Rate limited. Wait a moment."return f"🔴 HTTP {e.response.status_code}: {str(e)[:200]}"1 unmodified linereturn f"🔴 Error: {str(e)[:300]}"def analyze_market(self, ticker, market, data_summary, tech_summary, timeframe):prompt = f"""You are an elite quantitative analyst at a top hedge fund (Two Sigma / Jane Street level).Analyze the following market data with deep chain-of-thought reasoning.## Asset Information- **Ticker**: {ticker}10 unmodified linesProvide exactly these sections:### 1. Executive Summary (3 bullets)- Most critical finding- Key risk factor- Immediate catalyst to watch### 2. Technical Analysis- Interpret RSI, MACD, Bollinger Bands in context of current price action- Identify support/resistance levels from SMAs and VWAP- Note any divergence signals### 3. Risk Assessment- Volatility regime (low/normal/high)- Tail risk estimate (based on VaR, skewness, kurtosis)- Correlation risk if part of a broader portfolio### 4. Alpha Signal- Direction: BULLISH / NEUTRAL / BEARISH- Confidence: X%- Time horizon: Short-term (1-4 weeks) / Medium-term (1-3 months) / Long-term (3-12 months)- Key conviction drivers### 5. Trade Recommendation- Entry price / zone- Stop-loss (tight vs wide reasoning)- Target 1 (conservative)- Target 2 (aggressive)- Position sizing suggestion (% of portfolio)### 6. Catalyst Calendar- Next 7 days: earnings, macro data, Fed speakers- Next 30 days: options expiration, sector events### 7. Contrarian View- What would make this signal wrong?- Alternative scenario with probabilityThink step-by-step. Reference specific numbers from the data."""return self.chat([{"role": "user", "content": prompt}], temperature=0.2, max_tokens=4096)def portfolio_advice(self, portfolio_data, corr_data, risk_metrics, market_context):13 unmodified lines## Deliverables### 1. Portfolio Health Score (0-100)Grade with letter (A+ to F) and justify### 2. Concentration Risk- Single-name exposure limits- Sector/style drift- Geographic concentration### 3. Correlation Risk Matrix- Hidden correlated bets- Diversification quality score- Tail correlation concern### 4. Rebalancing Roadmap- Specific weight adjustments with %- Timeline: immediate / 1 week / 1 month- Tax/transaction cost considerations### 5. Hedging Strategy- Options structure for tail protection- ETF hedge ratios- Cost estimate ($ and basis points)### 6. Expected Return & Risk (Forward 12M)| Metric | Point Estimate | Range ||--------|---------------|-------|| Annual Return | X% | [Y%, Z%] || Volatility | X% | [Y%, Z%] || Sharpe | X.X | [Y, Z] || Max Drawdown | -X% | [-Y%, -Z%] || 95% VaR (1M) | -X% | — |### 7. Scenario Analysis- Bull case (20% probability): what happens, portfolio impact- Base case (50% probability)- Bear case (20% probability)- Tail case (10% probability)10 unmodified lines## Deliverables### 1. Macro Regime Classification- Current regime (growth/inflation quadrant)- Regime stability (stable vs transitioning)- Historical analog (which past period rhymes)### 2. Cross-Asset Implications- Equities: sector rotation, style factor- Fixed Income: curve shape, credit spread- FX: carry trade, safe haven flows- Commodities: supply/demand, inflation hedge- Crypto: risk-on/risk-off sensitivity### 3. Trade Ideas (3 concrete setups)Each with: instrument, direction, entry, stop, target, conviction %, time horizon### 4. Risk Factors- Top 3 risks that could invalidate thesis- Probability and impact matrix- Hedging suggestionThink like a macro PM."""return self.chat([{"role": "user", "content": prompt}], temperature=0.3, max_tokens=4096)def options_analysis(self, option_data, stock_data):prompt = f"""You are an exotics trader at Citadel / SIG analyzing options.## Option Parameters{option_data}## Underlying Stock Data{stock_data}## Deliverables### 1. Greeks Analysis- Delta hedge ratio- Gamma risk (pin risk near expiry)- Theta decay per day- Vega sensitivity to vol moves- Vomma / Vanna if relevant### 2. Pricing Assessment- Is this option cheap/fair/expensive vs historical vol?- Implied vs realized vol spread- Term structure shape### 3. Strategy Recommendation- Best structure for current view (vertical, butterfly, iron condor, etc.)- Expected P/L at expiry (visual table)- Break-even points- Max gain / max loss### 4. Scenario Analysis| Stock Price at Expiry | P/L | Probability (approx) ||----------------------|-----|----------------------|| -20% | $X | Y% || -10% | $X | Y% || 0% | $X | Y% || +10% | $X | Y% || +20% | $X | Y% |Risk-adjusted expected return calculation."""return self.chat([{"role": "user", "content": prompt}], temperature=0.3, max_tokens=4096)# ═══════════════════════════════════════════════════════════════# MARKET DATA — multi-market support# ═══════════════════════════════════════════════════════════════MARKET_PRESETS = {"🇺🇸 US Equities": {"suffix": "", "examples": "AAPL, TSLA, NVDA, SPY, QQQ, META, AMZN, GOOGL"},"🇪🇺 European Equities": {"suffix": ".PA", "examples": "AIR.PA, SAN.PA, TTE.PA, OR.PA, MC.PA, ASML.AS"},"🇬🇧 UK Equities": {"suffix": ".L", "examples": "AZN.L, SHEL.L, BP.L, ULVR.L, RIO.L, GSK.L"},"🇩🇪 German Equities": {"suffix": ".DE", "examples": "SAP.DE, SIE.DE, ALV.DE, BAS.DE, BMW.DE, MBG.DE"},"🇯🇵 Japanese Equities": {"suffix": ".T", "examples": "7203.T, 9984.T, 6861.T, 6758.T, 8306.T"},"🇨🇳 Chinese Equities": {"suffix": ".HK", "examples": "0700.HK, 9988.HK, 3690.HK, 1810.HK"},"🇮🇳 Indian Equities": {"suffix": ".NS", "examples": "RELIANCE.NS, TCS.NS, INFY.NS, HDFCBANK.NS"},"🪙 Crypto": {"suffix": "", "examples": "BTC-USD, ETH-USD, SOL-USD, XRP-USD, ADA-USD, DOGE-USD"},"💱 Forex Majors": {"suffix": "=X", "examples": "EURUSD=X, GBPUSD=X, USDJPY=X, AUDUSD=X, USDCAD=X"},"🥇 Commodities": {"suffix": "", "examples": "GC=F, SI=F, CL=F, NG=F, ZC=F, ZW=F"},"📊 Indices": {"suffix": "", "examples": "^GSPC, ^DJI, ^IXIC, ^FTSE, ^N225, ^HSI"},}def fetch_data(ticker, period="6mo", interval="1d"):if yf is None:return None, "yfinance not available"try:stock = yf.Ticker(ticker.upper().strip())df = stock.history(period=period, interval=interval)if df.empty:return None, f"No data for '{ticker}'. Try: {random.choice(list(MARKET_PRESETS.values()))['examples']}"info = stock.inforeturn df, infoexcept Exception as e:return None, f"Error fetching '{ticker}': {str(e)[:200]}"def calc_indicators(df):df = df.copy()32 unmodified linesdf['Stoch_D'] = df['Stoch_K'].rolling(3).mean()df['VM'] = df['Volume'].rolling(20).mean()df['VR'] = df['Volume']/(df['VM']+1e-10)# ADXplus_dm = df['High'].diff()minus_dm = df['Low'].diff()plus_dm[plus_dm<0] = 04 unmodified linesdf['minus_DI'] = 100 * (minus_dm.ewm(alpha=1/14, adjust=False).mean() / atr_smooth)dx = 100 * np.abs(df['plus_DI']-df['minus_DI'])/(df['plus_DI']+df['minus_DI']+1e-10)df['ADX'] = dx.ewm(alpha=1/14, adjust=False).mean()# OBVdf['OBV'] = (np.sign(df['Close'].diff())*df['Volume']).cumsum()# MFItp_r = (df['High']+df['Low']+df['Close'])/3tp_diff = tp_r.diff()pos_flow = tp_r.where(tp_diff>0,0)*df['Volume']1 unmodified linemfi_pos = pos_flow.rolling(14).sum()mfi_neg = neg_flow.rolling(14).sum()df['MFI'] = 100 - (100/(1+mfi_pos/(mfi_neg+1e-10)))# Ichimokudf['ICH_tenkan'] = (df['High'].rolling(9).max()+df['Low'].rolling(9).min())/2df['ICH_kijun'] = (df['High'].rolling(26).max()+df['Low'].rolling(26).min())/2df['ICH_senkou_A'] = ((df['ICH_tenkan']+df['ICH_kijun'])/2).shift(26)18 unmodified linescv95 = r[r<=v95].mean() if len(r[r<=v95])>0 else v95cv99 = r[r<=v99].mean() if len(r[r<=v99])>0 else v99ca = ar/(abs(md)+1e-10)# Rolling metricsroll_sharpe = (r.rolling(63).mean()*252)/(r.rolling(63).std()*np.sqrt(252)+1e-10)return {'ar':ar,'av':av,'sh':sh,'so':so,'md':md,'v95':v95,'v99':v99,'cv95':cv95,'cv99':cv99,'ca':ca,'sk':r.skew(),'ku':r.kurtosis(),'wr':(r>0).mean(),'pf':abs(r[r>0].sum()/(r[r<0].sum()+1e-10)),'avg_win':r[r>0].mean() if len(r[r>0])>0 else 0,'avg_loss':r[r<0].mean() if len(r[r<0])>0 else 0,'consec_wins':0,'consec_losses':0,'roll_sharpe':roll_sharpe.iloc[-1] if len(roll_sharpe.dropna())>0 else 0,'vol_regime':'low' if av<0.15 else 'normal' if av<0.30 else 'high'}34 unmodified liness['adx_trend'] = 'strong trend'elif l['ADX'] > 20:s['adx_trend'] = 'trending'# Ichimokuif l['Close'] > l['ICH_senkou_A'] and l['Close'] > l['ICH_senkou_B']:s['ichimoku'] = 'bullish cloud'elif l['Close'] < l['ICH_senkou_A'] and l['Close'] < l['ICH_senkou_B']:s['ichimoku'] = 'bearish cloud'# Scoresc = 50if 'bullish' in s['trend']: sc += 20if 'bearish' in s['trend']: sc -= 2013 unmodified linesreturn sdef make_candlestick(df, ticker, market):if not PLOTLY_OK:return Nonefig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.03,row_heights=[0.55, 0.25, 0.20],subplot_titles=(f'{ticker} ({market})', 'Volume + VWAP', 'RSI'))# Candlestickfig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],low=df['Low'], close=df['Close'], name='Price',increasing_line_color='#00C853', decreasing_line_color='#FF5252'), row=1, col=1)# SMAsfig.add_trace(go.Scatter(x=df.index, y=df['SMA20'], line=dict(color='#FF9800', width=1), name='SMA20'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['SMA50'], line=dict(color='#2196F3', width=1), name='SMA50'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['SMA200'], line=dict(color='#9C27B0', width=1.5, dash='dash'), name='SMA200'), row=1, col=1)# BBfig.add_trace(go.Scatter(x=df.index, y=df['BBU'], line=dict(color='gray', width=0.8, dash='dash'), name='BB+', opacity=0.4), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['BBL'], line=dict(color='gray', width=0.8, dash='dash'), name='BB-', opacity=0.4), row=1, col=1)# Ichimokufig.add_trace(go.Scatter(x=df.index, y=df['ICH_senkou_A'], fill=None, mode='lines', line=dict(color='green', width=0.5), name='Senkou A'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['ICH_senkou_B'], fill='tonexty', fillcolor='rgba(46,125,50,0.1)', mode='lines', line=dict(color='red', width=0.5), name='Senkou B'), row=1, col=1)# Volumecolors = ['#00C853' if df['Close'].iloc[i]>=df['Open'].iloc[i] else '#FF5252' for i in range(len(df))]fig.add_trace(go.Bar(x=df.index, y=df['Volume'], marker_color=colors, name='Volume', opacity=0.7), row=2, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['VM'], line=dict(color='#FF9800', width=1), name='Vol MA20'), row=2, col=1)# RSIfig.add_trace(go.Scatter(x=df.index, y=df['RSI'], line=dict(color='#9C27B0', width=1.5), fill='tozeroy', fillcolor='rgba(156,39,176,0.1)'), row=3, col=1)fig.add_hline(y=70, line_dash="dash", line_color="#FF5252", row=3, col=1)fig.add_hline(y=30, line_dash="dash", line_color="#00C853", row=3, col=1)8 unmodified linesreturn figdef make_macd(df, ticker):if not PLOTLY_OK: return Nonefig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05,row_heights=[0.6, 0.4], subplot_titles=('MACD', 'Histogram'))fig.add_trace(go.Scatter(x=df.index, y=df['MACD'], line=dict(color='#2196F3', width=1.5), name='MACD'), row=1, col=1)5 unmodified linesreturn figdef make_stoch(df, ticker):if not PLOTLY_OK: return Nonefig = go.Figure()fig.add_trace(go.Scatter(x=df.index, y=df['Stoch_K'], line=dict(color='#2196F3', width=1.5), name='%K'))fig.add_trace(go.Scatter(x=df.index, y=df['Stoch_D'], line=dict(color='#FF9800', width=1.5), name='%D'))fig.add_hline(y=80, line_dash="dash", line_color="#FF5252")fig.add_hline(y=20, line_dash="dash", line_color="#00C853")fig.update_layout(title=f'{ticker} Stochastic Oscillator', template='plotly_dark',height=400, paper_bgcolor='#0d1117', plot_bgcolor='#161b22',font=dict(color='#e6edf3'))return figdef make_vol(df, ticker):if not PLOTLY_OK: return Nonefig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05,row_heights=[0.6, 0.4], subplot_titles=('ATR %', 'Volume Ratio'))fig.add_trace(go.Scatter(x=df.index, y=df['ATR_pct'], line=dict(color='#FF9800', width=1.5), fill='tozeroy'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['VR'], line=dict(color='#9C27B0', width=1.5)), row=2, col=1)fig.add_hline(y=1.0, line_dash="dash", line_color="gray", row=2, col=1)fig.update_layout(title=f'{ticker} Volatility & Volume', template='plotly_dark',height=500, paper_bgcolor='#0d1117', plot_bgcolor='#161b22',font=dict(color='#e6edf3'))return figdef make_adx(df, ticker):if not PLOTLY_OK: return Nonefig = go.Figure()fig.add_trace(go.Scatter(x=df.index, y=df['plus_DI'], line=dict(color='#00C853', width=1), name='+DI'))fig.add_trace(go.Scatter(x=df.index, y=df['minus_DI'], line=dict(color='#FF5252', width=1), name='-DI'))fig.add_trace(go.Scatter(x=df.index, y=df['ADX'], line=dict(color='#2196F3', width=2), name='ADX'))fig.add_hline(y=25, line_dash="dash", line_color="gray")fig.update_layout(title=f'{ticker} ADX Trend Strength', template='plotly_dark',height=400, paper_bgcolor='#0d1117', plot_bgcolor='#161b22',font=dict(color='#e6edf3'))return figdef make_dist(r, ticker):if not PLOTLY_OK: return Nonefig = go.Figure()fig.add_trace(go.Histogram(x=r, nbinsx=50, marker_color='#2196F3', opacity=0.7, name='Returns'))mu, sig = r.mean(), r.std()x_range = np.linspace(r.min(), r.max(), 100)try:from scipy import stats as sp_statsnormal_pdf = len(r)*(x_range[1]-x_range[0])*sp_stats.norm.pdf(x_range, mu, sig)fig.add_trace(go.Scatter(x=x_range, y=normal_pdf, mode='lines',line=dict(color='#FF5252', dash='dash'), name='Normal'))except:passfig.add_vline(x=mu, line_color='#00C853', line_dash='dash', annotation_text=f'Mean: {mu*100:.2f}%')fig.add_vline(x=np.percentile(r,5), line_color='#FF5252', line_dash='dot', annotation_text=f'VaR95')fig.update_layout(title=f'{ticker} Return Distribution', xaxis_title='Daily Return',yaxis_title='Frequency', height=400, template='plotly_dark',paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))return fig# ═══════════════════════════════════════════════════════════════# PORTFOLIO OPTIMIZATION# ═══════════════════════════════════════════════════════════════def optimize_portfolio(tickers, period="1y"):if yf is None or pd is None or np is None:return None, None, "Libraries unavailable."ts = [t.strip().upper() for t in tickers.split(',') if t.strip()]if len(ts) < 2:return None, None, "Enter at least 2 tickers."data = {}errs = []for t in ts:df, err = fetch_data(t, period)if err:errs.append(err)elif df is not None and len(df) > 30:data[t] = df['Close']if len(data) < 2:return None, None, f"Could not fetch enough data. Errors: {'; '.join(errs[:3])}"prices = pd.DataFrame(data).dropna()returns = prices.pct_change().dropna()if len(returns) < 30:return None, None, "Need more aligned data."mu = returns.mean() * 252sigma = returns.cov() * 252n = len(mu)15 unmodified lineseq_w = np.ones(n)/neq_r = np.dot(eq_w, mu)eq_v = np.sqrt(np.dot(eq_w.T, np.dot(sigma, eq_w)))# Frontierws = np.random.dirichlet(np.ones(n)*0.5, 3000)ws = np.clip(ws, 0, 0.4)ws = ws/ws.sum(axis=1, keepdims=True)prets = np.dot(ws, mu)pvols = np.array([np.sqrt(np.dot(w.T, np.dot(sigma, w))) for w in ws])psh = prets/(pvols+1e-10)if PLOTLY_OK:fig = go.Figure()fig.add_trace(go.Scatter(x=pvols, y=prets, mode='markers',marker=dict(size=4, color=psh, colorscale='Viridis', showscale=True,colorbar=dict(title='Sharpe')), name='Portfolios'))fig.add_trace(go.Scatter(x=[pv], y=[pr], mode='markers+text',marker=dict(size=18, color='#FF5252', symbol='star'),text=['Optimal'], textposition='top center', name='Optimal'))fig.add_trace(go.Scatter(x=[eq_v], y=[eq_r], mode='markers+text',marker=dict(size=14, color='#FF9800', symbol='diamond'),text=['Equal'], textposition='bottom center', name='Equal Weight'))fig.update_layout(title='Efficient Frontier', xaxis_title='Volatility',yaxis_title='Return', template='plotly_dark', height=550,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))else:fig = Nonewdf = pd.DataFrame({'Ticker': list(data.keys()),'Optimal (%)': np.round(best_w*100, 2),'Equal (%)': np.round(eq_w*100, 2)})# Correlation matrixcorr = returns.corr()corr_fig = Noneif PLOTLY_OK:corr_fig = go.Figure(data=go.Heatmap(z=corr.values, x=corr.columns, y=corr.columns,colorscale='RdBu', zmid=0, text=np.round(corr.values,2), texttemplate='%{text:.2f}',colorbar=dict(title='Correlation')))corr_fig.update_layout(title='Correlation Matrix', template='plotly_dark', height=450,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))md = f"""## 📊 Portfolio Optimization Results**Tickers:** {', '.join(list(data.keys()))}### Optimal (Max Sharpe)| Metric | Value ||--------|-------|| Expected Return | {pr*100:.1f}% || Volatility | {pv*100:.1f}% || Sharpe | {best_sh:.2f} |### Equal Weight Benchmark| Metric | Value ||--------|-------|| Expected Return | {eq_r*100:.1f}% || Volatility | {eq_v*100:.1f}% || Sharpe | {eq_r/(eq_v+1e-10):.2f} |### Improvements vs Equal Weight| Metric | Improvement ||--------|-------------|| Sharpe | {((best_sh/(eq_r/(eq_v+1e-10))-1)*100):+.1f}% || Return | {((pr/eq_r-1)*100):+.1f}% || Risk | {((1-pv/eq_v)*100):+.1f}% |### Optimal Weights{wdf.to_markdown(index=False)}"""return fig, corr_fig, wdf, md# ═══════════════════════════════════════════════════════════════# PAIRS TRADING# ═══════════════════════════════════════════════════════════════def analyze_pair(ticker_a, ticker_b, period="1y"):df_a, _ = fetch_data(ticker_a, period)df_b, _ = fetch_data(ticker_b, period)if df_a is None or df_b is None:return None, None, "Could not fetch data for one or both tickers."prices = pd.DataFrame({ticker_a: df_a['Close'], ticker_b: df_b['Close']}).dropna()if len(prices) < 30:return None, None, "Insufficient aligned data."# Spreadspread = prices[ticker_a] - prices[ticker_b]spread_norm = (spread - spread.mean()) / spread.std()# Cointegration test (Engle-Granger style)from numpy import polyfitbeta = polyfit(prices[ticker_b], prices[ticker_a], 1)[0]hedge_ratio = betaspread_hedged = prices[ticker_a] - hedge_ratio * prices[ticker_b]spread_hedged_norm = (spread_hedged - spread_hedged.mean()) / spread_hedged.std()# Half-life (Ornstein-Uhlenbeck)lag_spread = spread_hedged.shift(1)delta_spread = spread_hedged.diff()valid = delta_spread.dropna().index1 unmodified linex = lag_spread.loc[valid] - spread_hedged.mean()theta = -np.polyfit(x, y, 1)[0]half_life = np.log(2)/theta if theta > 0 else float('inf')# Z-score signalz = spread_hedged_norm.iloc[-1]signal = 'SHORT SPREAD' if z > 2 else 'LONG SPREAD' if z < -2 else 'NO SIGNAL'# Plotif PLOTLY_OK:fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.05,subplot_titles=(f'{ticker_a} vs {ticker_b} (Price)', 'Normalized Spread', 'Z-Score'))fig.add_trace(go.Scatter(x=prices.index, y=prices[ticker_a], line=dict(color='#2196F3', width=1.5), name=ticker_a), row=1, col=1)fig.add_trace(go.Scatter(x=prices.index, y=prices[ticker_b], line=dict(color='#FF9800', width=1.5), name=ticker_b), row=1, col=1)fig.add_trace(go.Scatter(x=prices.index, y=spread_norm, line=dict(color='#00C853', width=1.5), fill='tozeroy'), row=2, col=1)fig.add_trace(go.Scatter(x=prices.index, y=spread_hedged_norm, line=dict(color='#9C27B0', width=1.5)), row=3, col=1)fig.add_hline(y=2, line_dash="dash", line_color="#FF5252", row=3, col=1)fig.add_hline(y=-2, line_dash="dash", line_color="#00C853", row=3, col=1)fig.add_hline(y=0, line_dash="dot", line_color="gray", row=3, col=1)fig.update_layout(title=f'Pairs Trading: {ticker_a} / {ticker_b}', template='plotly_dark',height=750, paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))else:fig = None# Scatterif PLOTLY_OK:scat = go.Figure()scat.add_trace(go.Scatter(x=prices[ticker_b], y=prices[ticker_a], mode='markers',marker=dict(size=4, color=np.arange(len(prices)), colorscale='Viridis', showscale=True),name='Price Path'))# Regression linex_range = np.linspace(prices[ticker_b].min(), prices[ticker_b].max(), 100)intercept = np.polyfit(prices[ticker_b], prices[ticker_a], 1)[1]y_range = hedge_ratio * x_range + interceptscat.add_trace(go.Scatter(x=x_range, y=y_range, mode='lines',line=dict(color='#FF5252', dash='dash'), name=f'OLS (β={hedge_ratio:.2f})'))scat.update_layout(title=f'Price Relationship (β={hedge_ratio:.2f})', template='plotly_dark',xaxis_title=ticker_b, yaxis_title=ticker_a, height=450,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))else:scat = Nonemd = f"""## 🔗 Pairs Trading Analysis: {ticker_a} vs {ticker_b}### Statistics| Metric | Value ||--------|-------|| Hedge Ratio (β) | {hedge_ratio:.3f} |3 unmodified lines| Half-Life | {half_life:.1f} days |### Signal| Current Z | Interpretation | Action ||-----------|----------------|--------|| {z:.2f} | {'Overextended' if abs(z)>2 else 'Normal range'} | **{signal}** |### Trading Rules- **Enter Long Spread** when Z < -2 (buy {ticker_a}, short {ticker_b})- **Enter Short Spread** when Z > +2 (short {ticker_a}, buy {ticker_b})- **Exit** when Z crosses 0- **Stop Loss** when |Z| > 3.5"""return fig, scat, md# ═══════════════════════════════════════════════════════════════# OPTIONS PRICING (Black-Scholes)# ═══════════════════════════════════════════════════════════════def black_scholes(S, K, T, r, sigma, option_type='call'):from math import log, sqrt, exptry:d1 = (log(S/K) + (r + 0.5*sigma**2)*T) / (sigma*sqrt(T))d2 = d1 - sigma*sqrt(T)try:from scipy.stats import normnd1 = norm.cdf(d1)nd2 = norm.cdf(d2)npdf_d1 = norm.pdf(d1)except:# Approximate normal CDFdef approx_cdf(x):return 0.5 * (1 + math.erf(x / math.sqrt(2)))nd1 = approx_cdf(d1)nd2 = approx_cdf(d2)npdf_d1 = (1/math.sqrt(2*math.pi)) * math.exp(-0.5*d1**2)if option_type == 'call':price = S*nd1 - K*exp(-r*T)*nd2else:price = K*exp(-r*T)*(1-nd2) - S*(1-nd1)delta = nd1 if option_type=='call' else nd1 - 1gamma = npdf_d1 / (S*sigma*sqrt(T))theta = -(S*npdf_d1*sigma)/(2*sqrt(T)) - r*K*exp(-r*T)*nd2 if option_type=='call' else -(S*npdf_d1*sigma)/(2*sqrt(T)) + r*K*exp(-r*T)*(1-nd2)vega = S*npdf_d1*sqrt(T)rho = K*T*exp(-r*T)*nd2 if option_type=='call' else -K*T*exp(-r*T)*(1-nd2)return {'price': price, 'delta': delta, 'gamma': gamma, 'theta': theta/252,'vega': vega/100, 'rho': rho/100, 'd1': d1, 'd2': d2}except Exception as e:return {'error': str(e)}def analyze_options(ticker, strike_pct, days, rfr, vol_override, option_type):df, info = fetch_data(ticker, "6mo")if df is None:return None, None, "Could not fetch data."df = calc_indicators(df)S = df['Close'].iloc[-1]K = S * (strike_pct/100)T = days / 365# Volatilityif vol_override:sigma = vol_override / 100else:sigma = df['Ret'].dropna().std() * np.sqrt(252)# Risk-free rater = rfr / 100bs = black_scholes(S, K, T, r, sigma, option_type.lower())if 'error' in bs:return None, None, f"BS Error: {bs['error']}"# P/L tablepct_changes = np.arange(-30, 31, 5)pl_data = []for pct in pct_changes:new_S = S * (1 + pct/100)new_bs = black_scholes(new_S, K, T - 1/365, r, sigma, option_type.lower())pl = (new_bs['price'] - bs['price']) * 100 # per contractpl_data.append({'Price Change %': f'{pct:+d}%', 'Stock Price': f'${new_S:.2f}','Option Price': f'${new_bs["price"]:.2f}', 'P/L (per 100)': f'${pl:+.2f}'})pl_df = pd.DataFrame(pl_data)# Greeks chartif PLOTLY_OK:strikes = np.linspace(S*0.7, S*1.3, 50)greeks = {'price': [], 'delta': [], 'gamma': [], 'theta': [], 'vega': []}for st in strikes:res = black_scholes(S, st, T, r, sigma, option_type.lower())for k in greeks:greeks[k].append(res.get(k, 0))fig = make_subplots(rows=2, cols=3, subplot_titles=('Price', 'Delta', 'Gamma', 'Theta (daily)', 'Vega', 'P/L at Expiry'),vertical_spacing=0.12, horizontal_spacing=0.08)colors = ['#2196F3', '#00C853', '#FF9800', '#FF5252', '#9C27B0', '#673AB7']for i, (k, v) in enumerate(greeks.items()):row, col = (i//3)+1, (i%3)+1fig.add_trace(go.Scatter(x=strikes, y=v, line=dict(color=colors[i], width=2), name=k), row=row, col=col)fig.add_vline(x=S, line_dash='dash', line_color='gray', row=row, col=col)# P/L at expiryexpiry_payoff = [max(s-K,0) if option_type.lower()=='call' else max(K-s,0) for s in strikes]pl_expiry = [p - bs['price'] for p in expiry_payoff]fig.add_trace(go.Scatter(x=strikes, y=pl_expiry, line=dict(color='#673AB7', width=2), name='P/L Expiry'), row=2, col=3)fig.add_hline(y=0, line_dash='dot', line_color='gray', row=2, col=3)fig.update_layout(title=f'{ticker} {option_type.title()} Greeks (S=${S:.2f}, K=${K:.2f}, T={days}d, σ={sigma*100:.1f}%)',template='plotly_dark', height=650,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))else:fig = Nonemd = f"""## 📐 {ticker} {option_type.title()} Option Analysis### Parameters| Parameter | Value ||-----------|-------|| Spot Price (S) | ${S:.2f} || Strike (K) | ${K:.2f} ({strike_pct:.0f}% of spot) || Time to Expiry (T) | {days} days ({T:.3f} years) || Risk-Free Rate | {r*100:.2f}% || Implied Volatility | {sigma*100:.1f}% |### Black-Scholes Price & Greeks| Greek | Value | Interpretation ||-------|-------|----------------|| **Price** | ${bs['price']:.3f} | Option fair value || **Delta** | {bs['delta']:.4f} | {abs(bs['delta'])*100:.1f}% hedge ratio || **Gamma** | {bs['gamma']:.6f} | Delta sensitivity per $1 move || **Theta** | ${bs['theta']:.4f}/day | Daily time decay || **Vega** | ${bs['vega']:.4f} | Price change per 1% vol move || **Rho** | ${bs['rho']:.4f} | Price change per 1% rate move || **d1** | {bs['d1']:.4f} | Distance to exercise (std dev) || **d2** | {bs['d2']:.4f} | Risk-neutral probability adj |### P/L Scenario Table (per 100 contracts){pl_df.to_markdown(index=False)}"""return fig, pl_df, md# ═══════════════════════════════════════════════════════════════# MACRO ANALYSIS# ═══════════════════════════════════════════════════════════════def get_macro_data():macros = {}for t, name in [('^GSPC','S&P 500'),('^IXIC','Nasdaq'),('^TNX','10Y Treasury'),2 unmodified linestry:df = yf.Ticker(t).history(period='1mo')if not df.empty:macros[name] = {'price': df['Close'].iloc[-1], 'change_1m': (df['Close'].iloc[-1]/df['Close'].iloc[0]-1)*100,'high': df['High'].max(), 'low': df['Low'].min()}except:passreturn macros# ═══════════════════════════════════════════════════════════════# UI FUNCTIONS# ═══════════════════════════════════════════════════════════════def analyze_stock(ticker, market_preset, period, interval):ticker = ticker.strip().upper()if not ticker:return [None]*7 + ["Enter a ticker."]suffix = MARKET_PRESETS.get(market_preset, {}).get('suffix', '')if suffix and not ticker.endswith(suffix.split('.')[-1]):ticker = ticker + suffixdf, info = fetch_data(ticker, period)if df is None:return [None]*7 + [f"Error: {info}"]df = calc_indicators(df)sg = calc_signals(df)rk = calc_risk(df)if not rk:return [None]*7 + ["Need more data."]l = df.iloc[-1]p = df.iloc[-2] if len(df)>1 else lch = ((l['Close']/p['Close']-1)*100) if p['Close']>0 else 0# Chartsc1 = make_candlestick(df, ticker, market_preset)c2 = make_macd(df, ticker)c3 = make_stoch(df, ticker)c4 = make_vol(df, ticker)c5 = make_adx(df, ticker)c6 = make_dist(df['Ret'].dropna(), ticker)# Summarymkt_info = ""if info:mkt_info = f"""| Info | Value ||------|-------|| Name | {info.get('longName', ticker)} || Sector | {info.get('sector', 'N/A')} || Industry | {info.get('industry', 'N/A')} || Market Cap | {info.get('marketCap', 'N/A'):,}" if info.get('marketCap') else ""mkt_info += f"""| 52W High | ${info.get('fiftyTwoWeekHigh', 'N/A'):.2f}" if info.get('fiftyTwoWeekHigh') else ""mkt_info += f"""| 52W Low | ${info.get('fiftyTwoWeekLow', 'N/A'):.2f}" if info.get('fiftyTwoWeekLow') else ""mkt_info += f"""| P/E | {info.get('trailingPE', 'N/A')} |""" if info.get('trailingPE') else ""md = f"""# {ticker} — {sg['dir']} {sg['strength']} (Score: {sg['score']}/100)**Price:** ${l['Close']:.2f} | **Change:** {ch:+.2f}% | **Period:** {period}{mkt_info}## Signal Dashboard9 unmodified lines| Trend | {sg['trend'].upper()} | — || Momentum | {sg['mom']} | — || Volatility | {sg['vol']} | — || Ichimoku Cloud | {sg['ichimoku']} | — |## Risk Metrics| Metric | Value |17 unmodified lines| Kurtosis | {rk['ku']:.2f} || 63D Rolling Sharpe | {rk['roll_sharpe']:.2f} |"""return [c1, c2, c3, c4, c5, c6, md, ""]def ai_analyze_stock(ticker, market_preset, period, interval):ticker = ticker.strip().upper()if not ticker:return "Enter a ticker."suffix = MARKET_PRESETS.get(market_preset, {}).get('suffix', '')if suffix and not ticker.endswith(suffix.split('.')[-1]):ticker = ticker + suffixdf, info = fetch_data(ticker, period)if df is None:return f"Error: {info}"df = calc_indicators(df)sg = calc_signals(df)rk = calc_risk(df)26 unmodified linesclient = K2ThinkClient()return client.portfolio_advice(pd_str, corr_str, md, "Current macro: mixed signals, rates elevated, geopolitical uncertainty")def ai_macro():macros = get_macro_data()macro_text = "Global Macro Snapshot:\n"for name, data in macros.items():macro_text += f"- {name}: ${data['price']:.2f} (1M change: {data['change_1m']:+.1f}%)\n"client = K2ThinkClient()return client.macro_analysis(macro_text)def ai_chat(question, temp):if not question.strip():return "Enter a question."client = K2ThinkClient()return client.chat([{"role":"user","content":question}], temperature=temp, max_tokens=4096)# ═══════════════════════════════════════════════════════════════# GRADIO APP — FINANCE DARK THEME# ═══════════════════════════════════════════════════════════════def build_app():if gr is None:raise ImportError(f"Gradio not available. Errors: {_import_errors}")with gr.Blocks(title="AlphaForge x K2 Think V2 — Institutional Quant Platform",theme=gr.themes.Soft(primary_hue="blue",secondary_hue="indigo",neutral_hue="slate",font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"]),css="""3 unmodified lines.tab-nav { background: #0d1117 !important; border-bottom: 1px solid #30363d !important; }.tab-nav button { color: #8b949e !important; background: transparent !important; border: none !important; }.tab-nav button.selected { color: #58a6ff !important; border-bottom: 2px solid #58a6ff !important; }.panel { background: #161b22 !important; border: 1px solid #30363d !important; border-radius: 12px !important; }input, textarea, select { background: #21262d !important; color: #e6edf3 !important; border: 1px solid #30363d !important; }button.primary { background: linear-gradient(135deg, #1f6feb, #58a6ff) !important; color: white !important; border: none !important; border-radius: 8px !important; font-weight: 600 !important; }button.secondary { background: #21262d !important; color: #58a6ff !important; border: 1px solid #30363d !important; border-radius: 8px !important; }.markdown-body { color: #e6edf3 !important; }.markdown-body h1 { color: #58a6ff !important; border-bottom: 1px solid #30363d !important; }.markdown-body h2 { color: #79c0ff !important; }.markdown-body h3 { color: #a5d6ff !important; }.markdown-body table { border-color: #30363d !important; }.markdown-body th { background: #21262d !important; color: #58a6ff !important; }.markdown-body td { border-color: #30363d !important; }.markdown-body tr:nth-child(even) { background: #161b22 !important; }.title-bar { text-align: center; padding: 24px 0; }.title-bar h1 { font-size: 2.8em; font-weight: 800; margin: 0; background: linear-gradient(90deg, #58a6ff, #a371f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }.title-bar p { color: #8b949e; font-size: 1.1em; margin-top: 8px; }2 unmodified lines.badge-api { background: linear-gradient(135deg, #1f6feb, #a371f7); color: white; }.badge-data { background: #238636; color: white; }.badge-alpha { background: #8957e5; color: white; }.k2-status { text-align: center; padding: 8px; margin: 8px 0; border-radius: 8px; font-size: 0.9em; }.k2-active { background: rgba(35,134,54,0.2); color: #3fb950; border: 1px solid #238636; }.k2-inactive { background: rgba(209,36,47,0.2); color: #f85149; border: 1px solid #da3633; }""") as demo:# Headergr.HTML("""<div class="title-bar"><h1>🔥 AlphaForge x K2 Think V2</h1><p>Institutional-Grade Quantitative Analysis Platform — Powered by MBZUAI's State-of-the-Art Reasoning Model</p></div><div class="badge-row"><span class="badge badge-api">🤖 K2 Think V2</span><span class="badge badge-data">📊 Multi-Market Data</span><span class="badge badge-alpha">🎯 AI Alpha Engine</span><span class="badge badge-data">📐 Options Pricing</span><span class="badge badge-alpha">🔗 Pairs Trading</span><span class="badge badge-api">🌍 Macro Analysis</span></div>""")# K2 Statusk2_status_html = gr.HTML(f"""<div class="k2-status {'k2-active' if K2_API_KEY else 'k2-inactive'}">{'✅ K2 Think V2 API Connected' if K2_API_KEY else '⚠️ K2 Think V2 API Not Configured — Add K2_API_KEY in Space Settings > Repository Secrets'}</div>""")# ── TAB 1: SINGLE STOCK ──with gr.Tab("📈 Technical Analysis"):with gr.Row():with gr.Column(scale=1):mkt_select = gr.Dropdown(label="🌍 Market", choices=list(MARKET_PRESETS.keys()),value="🇺🇸 US Equities")ticker_in = gr.Textbox(label="Ticker", value="AAPL", placeholder="e.g., AAPL, BTC-USD, EURUSD=X")gr.HTML("<small style='color:#8b949e'>Examples: <span id='examples'></span></small>")period_in = gr.Dropdown(label="Period", choices=["1mo","3mo","6mo","1y","2y","5y"], value="6mo")interval_in = gr.Dropdown(label="Interval", choices=["1d","1wk","1mo"], value="1d")analyze_btn = gr.Button("🔍 Analyze", variant="primary", size="lg")12 unmodified lineswith gr.Row():ai_out = gr.Textbox(label="🤖 K2 Think V2 Analysis", lines=30, max_lines=50, show_copy_button=True)analyze_btn.click(fn=analyze_stock,inputs=[ticker_in, mkt_select, period_in, interval_in],outputs=[chart1, chart2, chart3, chart4, chart5, chart6, summary_out, gr.Textbox(visible=False)])ai_btn.click(fn=ai_analyze_stock,inputs=[ticker_in, mkt_select, period_in, interval_in],outputs=[ai_out])# ── TAB 2: PORTFOLIO ──with gr.Tab("💼 Portfolio Optimizer"):with gr.Row():with gr.Column(scale=1):port_in = gr.Textbox(label="Tickers (comma-separated)", value="AAPL, MSFT, GOOGL, AMZN, NVDA")port_period = gr.Dropdown(label="Lookback", choices=["6mo","1y","2y","3y"], value="1y")opt_btn = gr.Button("🎯 Optimize Portfolio", variant="primary", size="lg")ai_port_btn = gr.Button("🤖 AI Portfolio Advice (K2 Think V2)", variant="secondary", size="lg")with gr.Column(scale=2):port_md = gr.Markdown()with gr.Row():3 unmodified linesweights_df = gr.DataFrame(label="Optimal Weights", interactive=False)with gr.Row():ai_port_out = gr.Textbox(label="🤖 AI Portfolio Advice", lines=25, max_lines=40, show_copy_button=True)opt_btn.click(fn=optimize_portfolio, inputs=[port_in, port_period], outputs=[frontier_plot, corr_plot, weights_df, port_md])ai_port_btn.click(fn=ai_portfolio, inputs=[port_in, port_period], outputs=[ai_port_out])# ── TAB 3: PAIRS TRADING ──with gr.Tab("🔗 Pairs Trading"):with gr.Row():with gr.Column(scale=1):6 unmodified lineswith gr.Row():pair_chart = gr.Plot(label="Spread Analysis")pair_scatter = gr.Plot(label="Price Relationship")pair_btn.click(fn=analyze_pair, inputs=[pair_a, pair_b, pair_period], outputs=[pair_chart, pair_scatter, pair_md])# ── TAB 4: OPTIONS ──with gr.Tab("📐 Options Pricing"):with gr.Row():with gr.Column(scale=1):9 unmodified lineswith gr.Row():greeks_plot = gr.Plot(label="Greeks Analysis")opt_pl = gr.DataFrame(label="P/L Scenarios", interactive=False)opt_calc_btn.click(fn=analyze_options,inputs=[opt_ticker, opt_strike, opt_days, opt_rfr, opt_vol, opt_type],outputs=[greeks_plot, opt_pl, opt_md])# ── TAB 5: MACRO ──with gr.Tab("🌍 Macro Analysis"):with gr.Row():macro_btn = gr.Button("🌍 Analyze Global Macro (K2 Think V2)", variant="primary", size="lg")with gr.Row():macro_out = gr.Textbox(label="🤖 K2 Think V2 Macro Analysis", lines=40, max_lines=60, show_copy_button=True)macro_btn.click(fn=ai_macro, outputs=[macro_out])# ── TAB 6: AI CHAT ──with gr.Tab("💬 K2 Think V2 Chat"):gr.Markdown("## Direct Chat with K2 Think V2")gr.Markdown("Ask any financial question — strategy, market analysis, quant interview prep, portfolio advice.")with gr.Row():chat_in = gr.Textbox(label="Your Question", placeholder="e.g., 'Explain gamma scalping with a real trade example'", lines=4, scale=4)chat_temp = gr.Slider(label="Temp", minimum=0, maximum=1, value=0.4, step=0.1, scale=1)1 unmodified linechat_out = gr.Textbox(label="🤖 Response", lines=30, max_lines=50, show_copy_button=True)chat_btn.click(fn=ai_chat, inputs=[chat_in, chat_temp], outputs=[chat_out])# ── TAB 7: ABOUT ──with gr.Tab("ℹ️ About & Setup"):gr.Markdown(f"""## AlphaForge x K2 Think V25 unmodified lines|---------|-------------|| **📈 Technical Analysis** | 18+ indicators: RSI, MACD, Bollinger, VWAP, Stochastic, ADX, Ichimoku, ATR, MFI, OBV || **🌍 Multi-Market** | US, EU, UK, DE, JP, CN, IN equities + Crypto + Forex + Commodities + Indices || **💼 Portfolio** | Mean-variance optimization, efficient frontier, correlation matrix, Sharpe maximization || **🔗 Pairs Trading** | Cointegration analysis, hedge ratio, half-life, Z-score signals || **📐 Options Pricing** | Black-Scholes + full Greeks (Delta, Gamma, Theta, Vega, Rho), P/L scenarios || **🌍 Macro Analysis** | Global cross-asset regime analysis via K2 Think V2 |20 unmodified linesreturn demoif __name__ == "__main__":if gr is None:print(f"FATAL: Gradio not available. {_import_errors}")exit(1)demo = build_app()demo.queue().launch(server_name="0.0.0.0", server_port=7860, share=False)123456781 unmodified line101112131415161718192021222324252627282930313233341 unmodified line36373839404142438 unmodified lines525354555657585960611 unmodified line636465666768697010 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011113 unmodified lines12512612712812913013113213313413513613713813914010 unmodified lines15115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919032 unmodified lines2232242252262272284 unmodified lines2332342352362372382391 unmodified line24124224324424524618 unmodified lines26526626726826927027127227327427527634 unmodified lines31131231331431531631731831932013 unmodified lines3343353363373383393403413423433443453463473483493503513523538 unmodified lines3623633643653663675 unmodified lines37337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643715 unmodified lines4534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165171 unmodified line5195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505513 unmodified lines5555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776782 unmodified lines6816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417429 unmodified lines75275375475575675775817 unmodified lines77677777877978078178278378478578678778878979079179279326 unmodified lines8208218228238248258268278288298308318328338348358368373 unmodified lines8418428438448458468478488492 unmodified lines85285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488512 unmodified lines8988999009019029039049059069079089099109119129139149153 unmodified lines9199209219229239249259269276 unmodified lines9349359369379389399409419 unmodified lines9519529539549559569579589599609619629639649659669679689691 unmodified line9719729739749759765 unmodified lines98298398498598698798820 unmodified lines10091010101110121013"""AlphaForge x K2 Think V2 - Institutional-Grade Quantitative Analysis PlatformMulti-market support: US, EU, Asia, Crypto, Forex, CommoditiesFinance-themed UI with dark mode, professional color schemeEnhanced features: Options pricing, Pairs Trading, Macro AnalysisPowered by MBZUAI K2 Think V2 reasoning modelAPI Key: set via K2_API_KEY environment variable1 unmodified lineimport os, json, traceback, warnings, math, randomwarnings.filterwarnings('ignore')# Core importstry:import gradio as grimport requestsimport yfinance as yfimport pandas as pdimport numpy as npimport plotly.graph_objects as gofrom plotly.subplots import make_subplotsPLOTLY_OK = Trueexcept ImportError as e:raise ImportError(f"Missing required package: {e}")# CONFIGK2_API_KEY = os.environ.get("K2_API_KEY", "")K2_BASE_URL = "https://api.k2think.ai/v1/chat/completions"K2_MODEL = "MBZUAI-IFM/K2-Think-v2"# K2 THINK V2 CLIENTclass K2ThinkClient:def __init__(self):self.api_key = K2_API_KEY1 unmodified lineself.base_url = K2_BASE_URLdef chat(self, messages, temperature=0.7, max_tokens=4096):if not self.available:return "⚠️ K2 Think V2 API Not Configured. Add K2_API_KEY in Space Settings > Repository Secrets. All other features work perfectly!"payload = {"model": K2_MODEL, "messages": messages, "temperature": temperature,"max_tokens": max_tokens, "stream": False}8 unmodified linesreturn j['choices'][0]['message']['content']return f"⚠️ Unexpected format: {json.dumps(j, indent=2)[:400]}"except requests.exceptions.Timeout:return "⏱️ Timeout after 120s. API may be under high load."except requests.exceptions.HTTPError as e:if e.response.status_code == 401:return "🔐 Auth failed. Check K2_API_KEY secret."elif e.response.status_code == 429:return "🚦 Rate limited. Wait a moment."return f"🔴 HTTP {e.response.status_code}: {str(e)[:200]}"1 unmodified linereturn f"🔴 Error: {str(e)[:300]}"def analyze_market(self, ticker, market, data_summary, tech_summary, timeframe):prompt = f"""You are an elite quantitative analyst at a top hedge fund (Two Sigma / Jane Street level).Analyze with deep chain-of-thought reasoning.## Asset Information- **Ticker**: {ticker}10 unmodified linesProvide exactly these sections:### 1. Executive Summary (3 bullets)### 2. Technical Analysis- Interpret RSI, MACD, Bollinger Bands, ADX, Ichimoku- Identify support/resistance levels from SMAs and VWAP### 3. Risk Assessment- Volatility regime (low/normal/high)- Tail risk estimate- Correlation risk### 4. Alpha Signal- Direction: BULLISH / NEUTRAL / BEARISH- Confidence: X%- Time horizon- Key conviction drivers### 5. Trade Recommendation- Entry price / zone- Stop-loss- Target 1 (conservative) and Target 2 (aggressive)- Position sizing suggestion### 6. Catalyst Calendar- Next 7 days- Next 30 days### 7. Contrarian View- What would make this signal wrong?- Alternative scenario with probabilityThink step-by-step. Reference specific numbers."""return self.chat([{"role": "user", "content": prompt}], temperature=0.2, max_tokens=4096)def portfolio_advice(self, portfolio_data, corr_data, risk_metrics, market_context):13 unmodified lines## Deliverables### 1. Portfolio Health Score (0-100) with letter grade (A+ to F)### 2. Concentration Risk### 3. Correlation Risk Matrix### 4. Rebalancing Roadmap- Specific weight adjustments with %- Timeline: immediate / 1 week / 1 month### 5. Hedging Strategy### 6. Expected Return & Risk (Forward 12M)### 7. Scenario Analysis- Bull case (20% probability)- Base case (50% probability)- Bear case (20% probability)- Tail case (10% probability)10 unmodified lines## Deliverables### 1. Macro Regime Classification### 2. Cross-Asset Implications- Equities, Fixed Income, FX, Commodities, Crypto### 3. Trade Ideas (3 concrete setups)Each with: instrument, direction, entry, stop, target, conviction %, time horizon### 4. Risk FactorsThink like a macro PM."""return self.chat([{"role": "user", "content": prompt}], temperature=0.3, max_tokens=4096)# MARKET DATAMARKET_PRESETS = {"🇺🇸 US Equities": {"suffix": "", "examples": "AAPL, TSLA, NVDA, SPY, QQQ, META, AMZN, GOOGL"},"🇪🇺 European Equities": {"suffix": ".PA", "examples": "AIR.PA, SAN.PA, TTE.PA, OR.PA, MC.PA"},"🇬🇧 UK Equities": {"suffix": ".L", "examples": "AZN.L, SHEL.L, BP.L, ULVR.L, RIO.L"},"🇩🇪 German Equities": {"suffix": ".DE", "examples": "SAP.DE, SIE.DE, ALV.DE, BAS.DE, BMW.DE"},"🇯🇵 Japanese Equities": {"suffix": ".T", "examples": "7203.T, 9984.T, 6861.T, 6758.T"},"🇨🇳 Chinese Equities": {"suffix": ".HK", "examples": "0700.HK, 9988.HK, 3690.HK, 1810.HK"},"🇮🇳 Indian Equities": {"suffix": ".NS", "examples": "RELIANCE.NS, TCS.NS, INFY.NS"},"🪙 Crypto": {"suffix": "", "examples": "BTC-USD, ETH-USD, SOL-USD, XRP-USD"},"💱 Forex Majors": {"suffix": "=X", "examples": "EURUSD=X, GBPUSD=X, USDJPY=X"},"🥇 Commodities": {"suffix": "", "examples": "GC=F, SI=F, CL=F, NG=F, ZC=F"},"📊 Indices": {"suffix": "", "examples": "^GSPC, ^DJI, ^IXIC, ^FTSE, ^N225"},}def fetch_data(ticker, period="6mo", interval="1d"):try:stock = yf.Ticker(ticker.upper().strip())df = stock.history(period=period, interval=interval)if df.empty:return None, None, f"No data for '{ticker}'. Try examples from the selected market."info = stock.inforeturn df, info, Noneexcept Exception as e:return None, None, f"Error fetching '{ticker}': {str(e)[:200]}"def calc_indicators(df):df = df.copy()32 unmodified linesdf['Stoch_D'] = df['Stoch_K'].rolling(3).mean()df['VM'] = df['Volume'].rolling(20).mean()df['VR'] = df['Volume']/(df['VM']+1e-10)plus_dm = df['High'].diff()minus_dm = df['Low'].diff()plus_dm[plus_dm<0] = 04 unmodified linesdf['minus_DI'] = 100 * (minus_dm.ewm(alpha=1/14, adjust=False).mean() / atr_smooth)dx = 100 * np.abs(df['plus_DI']-df['minus_DI'])/(df['plus_DI']+df['minus_DI']+1e-10)df['ADX'] = dx.ewm(alpha=1/14, adjust=False).mean()df['OBV'] = (np.sign(df['Close'].diff())*df['Volume']).cumsum()tp_r = (df['High']+df['Low']+df['Close'])/3tp_diff = tp_r.diff()pos_flow = tp_r.where(tp_diff>0,0)*df['Volume']1 unmodified linemfi_pos = pos_flow.rolling(14).sum()mfi_neg = neg_flow.rolling(14).sum()df['MFI'] = 100 - (100/(1+mfi_pos/(mfi_neg+1e-10)))df['ICH_tenkan'] = (df['High'].rolling(9).max()+df['Low'].rolling(9).min())/2df['ICH_kijun'] = (df['High'].rolling(26).max()+df['Low'].rolling(26).min())/2df['ICH_senkou_A'] = ((df['ICH_tenkan']+df['ICH_kijun'])/2).shift(26)18 unmodified linescv95 = r[r<=v95].mean() if len(r[r<=v95])>0 else v95cv99 = r[r<=v99].mean() if len(r[r<=v99])>0 else v99ca = ar/(abs(md)+1e-10)roll_sharpe = (r.rolling(63).mean()*252)/(r.rolling(63).std()*np.sqrt(252)+1e-10)return {'ar':ar,'av':av,'sh':sh,'so':so,'md':md,'v95':v95,'v99':v99,'cv95':cv95,'cv99':cv99,'ca':ca,'sk':r.skew(),'ku':r.kurtosis(),'wr':(r>0).mean(),'pf':abs(r[r>0].sum()/(r[r<0].sum()+1e-10)),'avg_win':r[r>0].mean() if len(r[r>0])>0 else 0,'avg_loss':r[r<0].mean() if len(r[r<0])>0 else 0,'roll_sharpe':roll_sharpe.iloc[-1] if len(roll_sharpe.dropna())>0 else 0,'vol_regime':'low' if av<0.15 else 'normal' if av<0.30 else 'high'}34 unmodified liness['adx_trend'] = 'strong trend'elif l['ADX'] > 20:s['adx_trend'] = 'trending'if l['Close'] > l['ICH_senkou_A'] and l['Close'] > l['ICH_senkou_B']:s['ichimoku'] = 'bullish cloud'elif l['Close'] < l['ICH_senkou_A'] and l['Close'] < l['ICH_senkou_B']:s['ichimoku'] = 'bearish cloud'sc = 50if 'bullish' in s['trend']: sc += 20if 'bearish' in s['trend']: sc -= 2013 unmodified linesreturn sdef make_candlestick(df, ticker, market):fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.03,row_heights=[0.55, 0.25, 0.20],subplot_titles=(f'{ticker} ({market})', 'Volume + VWAP', 'RSI'))fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],low=df['Low'], close=df['Close'], name='Price',increasing_line_color='#00C853', decreasing_line_color='#FF5252'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['SMA20'], line=dict(color='#FF9800', width=1), name='SMA20'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['SMA50'], line=dict(color='#2196F3', width=1), name='SMA50'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['SMA200'], line=dict(color='#9C27B0', width=1.5, dash='dash'), name='SMA200'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['BBU'], line=dict(color='gray', width=0.8, dash='dash'), name='BB+', opacity=0.4), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['BBL'], line=dict(color='gray', width=0.8, dash='dash'), name='BB-', opacity=0.4), row=1, col=1)colors = ['#00C853' if df['Close'].iloc[i]>=df['Open'].iloc[i] else '#FF5252' for i in range(len(df))]fig.add_trace(go.Bar(x=df.index, y=df['Volume'], marker_color=colors, name='Volume', opacity=0.7), row=2, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['VM'], line=dict(color='#FF9800', width=1), name='Vol MA20'), row=2, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['RSI'], line=dict(color='#9C27B0', width=1.5), fill='tozeroy', fillcolor='rgba(156,39,176,0.1)'), row=3, col=1)fig.add_hline(y=70, line_dash="dash", line_color="#FF5252", row=3, col=1)fig.add_hline(y=30, line_dash="dash", line_color="#00C853", row=3, col=1)8 unmodified linesreturn figdef make_macd(df, ticker):fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05,row_heights=[0.6, 0.4], subplot_titles=('MACD', 'Histogram'))fig.add_trace(go.Scatter(x=df.index, y=df['MACD'], line=dict(color='#2196F3', width=1.5), name='MACD'), row=1, col=1)5 unmodified linesreturn figdef make_stoch(df, ticker):fig = go.Figure()fig.add_trace(go.Scatter(x=df.index, y=df['Stoch_K'], line=dict(color='#2196F3', width=1.5), name='%K'))fig.add_trace(go.Scatter(x=df.index, y=df['Stoch_D'], line=dict(color='#FF9800', width=1.5), name='%D'))fig.add_hline(y=80, line_dash="dash", line_color="#FF5252")fig.add_hline(y=20, line_dash="dash", line_color="#00C853")fig.update_layout(title=f'{ticker} Stochastic', template='plotly_dark', height=400,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))return figdef make_vol(df, ticker):fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.05,row_heights=[0.6, 0.4], subplot_titles=('ATR %', 'Volume Ratio'))fig.add_trace(go.Scatter(x=df.index, y=df['ATR_pct'], line=dict(color='#FF9800', width=1.5), fill='tozeroy'), row=1, col=1)fig.add_trace(go.Scatter(x=df.index, y=df['VR'], line=dict(color='#9C27B0', width=1.5)), row=2, col=1)fig.add_hline(y=1.0, line_dash="dash", line_color="gray", row=2, col=1)fig.update_layout(title=f'{ticker} Volatility', template='plotly_dark', height=500,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))return figdef make_adx(df, ticker):fig = go.Figure()fig.add_trace(go.Scatter(x=df.index, y=df['plus_DI'], line=dict(color='#00C853', width=1), name='+DI'))fig.add_trace(go.Scatter(x=df.index, y=df['minus_DI'], line=dict(color='#FF5252', width=1), name='-DI'))fig.add_trace(go.Scatter(x=df.index, y=df['ADX'], line=dict(color='#2196F3', width=2), name='ADX'))fig.add_hline(y=25, line_dash="dash", line_color="gray")fig.update_layout(title=f'{ticker} ADX', template='plotly_dark', height=400,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))return figdef make_dist(r, ticker):fig = go.Figure()fig.add_trace(go.Histogram(x=r, nbinsx=50, marker_color='#2196F3', opacity=0.7, name='Returns'))mu, sig = r.mean(), r.std()fig.add_vline(x=mu, line_color='#00C853', line_dash='dash', annotation_text=f'Mean: {mu*100:.2f}%')fig.add_vline(x=np.percentile(r,5), line_color='#FF5252', line_dash='dot', annotation_text='VaR95')fig.update_layout(title=f'{ticker} Returns', xaxis_title='Daily Return', yaxis_title='Count',height=400, template='plotly_dark',paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))return fig# PORTFOLIOdef optimize_portfolio(tickers, period="1y"):ts = [t.strip().upper() for t in tickers.split(',') if t.strip()]if len(ts) < 2:return None, None, None, "Enter at least 2 tickers."data = {}errs = []for t in ts:df, info, err = fetch_data(t, period)if err:errs.append(err)elif df is not None and len(df) > 30:data[t] = df['Close']if len(data) < 2:return None, None, None, f"Could not fetch data: {'; '.join(errs[:3])}"prices = pd.DataFrame(data).dropna()returns = prices.pct_change().dropna()if len(returns) < 30:return None, None, None, "Need more data."mu = returns.mean() * 252sigma = returns.cov() * 252n = len(mu)15 unmodified lineseq_w = np.ones(n)/neq_r = np.dot(eq_w, mu)eq_v = np.sqrt(np.dot(eq_w.T, np.dot(sigma, eq_w)))ws = np.random.dirichlet(np.ones(n)*0.5, 3000)ws = np.clip(ws, 0, 0.4)ws = ws/ws.sum(axis=1, keepdims=True)prets = np.dot(ws, mu)pvols = np.array([np.sqrt(np.dot(w.T, np.dot(sigma, w))) for w in ws])psh = prets/(pvols+1e-10)fig = go.Figure()fig.add_trace(go.Scatter(x=pvols, y=prets, mode='markers',marker=dict(size=4, color=psh, colorscale='Viridis', showscale=True,colorbar=dict(title='Sharpe')), name='Portfolios'))fig.add_trace(go.Scatter(x=[pv], y=[pr], mode='markers+text',marker=dict(size=18, color='#FF5252', symbol='star'),text=['Optimal'], textposition='top center', name='Optimal'))fig.add_trace(go.Scatter(x=[eq_v], y=[eq_r], mode='markers+text',marker=dict(size=14, color='#FF9800', symbol='diamond'),text=['Equal'], textposition='bottom center', name='Equal Weight'))fig.update_layout(title='Efficient Frontier', xaxis_title='Volatility', yaxis_title='Return',template='plotly_dark', height=550,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))corr = returns.corr()corr_fig = go.Figure(data=go.Heatmap(z=corr.values, x=corr.columns, y=corr.columns,colorscale='RdBu', zmid=0, text=np.round(corr.values,2), texttemplate='%{text:.2f}',colorbar=dict(title='Correlation')))corr_fig.update_layout(title='Correlation Matrix', template='plotly_dark', height=450,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))wdf = pd.DataFrame({'Ticker': list(data.keys()),'Optimal (%)': np.round(best_w*100, 2),'Equal (%)': np.round(eq_w*100, 2)})md = f"""## Portfolio Results**Tickers:** {', '.join(list(data.keys()))}| | Optimal | Equal ||-|---------|-------|| Return | {pr*100:.1f}% | {eq_r*100:.1f}% || Volatility | {pv*100:.1f}% | {eq_v*100:.1f}% || Sharpe | {best_sh:.2f} | {eq_r/(eq_v+1e-10):.2f} |Improvements: Sharpe {((best_sh/(eq_r/(eq_v+1e-10))-1)*100):+.1f}%{wdf.to_markdown(index=False)}"""return fig, corr_fig, wdf, md# PAIRS TRADINGdef analyze_pair(ticker_a, ticker_b, period="1y"):df_a, _, _ = fetch_data(ticker_a, period)df_b, _, _ = fetch_data(ticker_b, period)if df_a is None or df_b is None:return None, None, "Could not fetch data for one or both tickers."prices = pd.DataFrame({ticker_a: df_a['Close'], ticker_b: df_b['Close']}).dropna()if len(prices) < 30:return None, None, "Insufficient aligned data."spread = prices[ticker_a] - prices[ticker_b]spread_norm = (spread - spread.mean()) / spread.std()beta = np.polyfit(prices[ticker_b], prices[ticker_a], 1)[0]hedge_ratio = betaspread_hedged = prices[ticker_a] - hedge_ratio * prices[ticker_b]spread_hedged_norm = (spread_hedged - spread_hedged.mean()) / spread_hedged.std()lag_spread = spread_hedged.shift(1)delta_spread = spread_hedged.diff()valid = delta_spread.dropna().index1 unmodified linex = lag_spread.loc[valid] - spread_hedged.mean()theta = -np.polyfit(x, y, 1)[0]half_life = np.log(2)/theta if theta > 0 else float('inf')z = spread_hedged_norm.iloc[-1]signal = 'SHORT SPREAD' if z > 2 else 'LONG SPREAD' if z < -2 else 'NO SIGNAL'fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.05,subplot_titles=(f'{ticker_a} vs {ticker_b}', 'Normalized Spread', 'Z-Score'))fig.add_trace(go.Scatter(x=prices.index, y=prices[ticker_a], line=dict(color='#2196F3', width=1.5), name=ticker_a), row=1, col=1)fig.add_trace(go.Scatter(x=prices.index, y=prices[ticker_b], line=dict(color='#FF9800', width=1.5), name=ticker_b), row=1, col=1)fig.add_trace(go.Scatter(x=prices.index, y=spread_norm, line=dict(color='#00C853', width=1.5), fill='tozeroy'), row=2, col=1)fig.add_trace(go.Scatter(x=prices.index, y=spread_hedged_norm, line=dict(color='#9C27B0', width=1.5)), row=3, col=1)fig.add_hline(y=2, line_dash="dash", line_color="#FF5252", row=3, col=1)fig.add_hline(y=-2, line_dash="dash", line_color="#00C853", row=3, col=1)fig.add_hline(y=0, line_dash="dot", line_color="gray", row=3, col=1)fig.update_layout(title=f'Pairs: {ticker_a} / {ticker_b}', template='plotly_dark',height=750, paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))scat = go.Figure()scat.add_trace(go.Scatter(x=prices[ticker_b], y=prices[ticker_a], mode='markers',marker=dict(size=4, color=np.arange(len(prices)), colorscale='Viridis', showscale=True),name='Price Path'))x_range = np.linspace(prices[ticker_b].min(), prices[ticker_b].max(), 100)intercept = np.polyfit(prices[ticker_b], prices[ticker_a], 1)[1]y_range = hedge_ratio * x_range + interceptscat.add_trace(go.Scatter(x=x_range, y=y_range, mode='lines',line=dict(color='#FF5252', dash='dash'), name=f'OLS (β={hedge_ratio:.2f})'))scat.update_layout(title=f'Price Relationship (β={hedge_ratio:.2f})', template='plotly_dark',xaxis_title=ticker_b, yaxis_title=ticker_a, height=450,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))md = f"""## Pairs Trading: {ticker_a} vs {ticker_b}| Metric | Value ||--------|-------|| Hedge Ratio (β) | {hedge_ratio:.3f} |3 unmodified lines| Half-Life | {half_life:.1f} days |### Signal| Z-Score | Action ||---------|--------|| {z:.2f} | **{signal}** |### Rules- **Long Spread** when Z < -2 (buy {ticker_a}, short {ticker_b})- **Short Spread** when Z > +2 (short {ticker_a}, buy {ticker_b})- **Exit** when Z crosses 0- **Stop Loss** when |Z| > 3.5"""return fig, scat, md# OPTIONSdef black_scholes(S, K, T, r, sigma, option_type='call'):try:d1 = (np.log(S/K) + (r + 0.5*sigma**2)*T) / (sigma*np.sqrt(T))d2 = d1 - sigma*np.sqrt(T)try:from scipy.stats import normnd1 = norm.cdf(d1)nd2 = norm.cdf(d2)npdf_d1 = norm.pdf(d1)except:def approx_cdf(x):return 0.5 * (1 + math.erf(x / math.sqrt(2)))nd1 = approx_cdf(d1)nd2 = approx_cdf(d2)npdf_d1 = (1/math.sqrt(2*math.pi)) * math.exp(-0.5*d1**2)if option_type == 'call':price = S*nd1 - K*math.exp(-r*T)*nd2delta = nd1else:price = K*math.exp(-r*T)*(1-nd2) - S*(1-nd1)delta = nd1 - 1gamma = npdf_d1 / (S*sigma*np.sqrt(T))theta = -(S*npdf_d1*sigma)/(2*np.sqrt(T)) - r*K*math.exp(-r*T)*nd2 if option_type=='call' else -(S*npdf_d1*sigma)/(2*np.sqrt(T)) + r*K*math.exp(-r*T)*(1-nd2)vega = S*npdf_d1*np.sqrt(T)rho = K*T*math.exp(-r*T)*nd2 if option_type=='call' else -K*T*math.exp(-r*T)*(1-nd2)return {'price': price, 'delta': delta, 'gamma': gamma, 'theta': theta/252,'vega': vega/100, 'rho': rho/100, 'd1': d1, 'd2': d2}except Exception as e:return {'error': str(e)}def analyze_options(ticker, strike_pct, days, rfr, vol_override, option_type):df, info, err = fetch_data(ticker, "6mo")if df is None:return None, None, f"Error: {err}"df = calc_indicators(df)S = df['Close'].iloc[-1]K = S * (strike_pct/100)T = days / 365if vol_override and vol_override > 0:sigma = vol_override / 100else:sigma = df['Ret'].dropna().std() * np.sqrt(252)r = rfr / 100bs = black_scholes(S, K, T, r, sigma, option_type.lower())if 'error' in bs:return None, None, f"BS Error: {bs['error']}"pct_changes = np.arange(-30, 31, 5)pl_data = []for pct in pct_changes:new_S = S * (1 + pct/100)new_bs = black_scholes(new_S, K, max(T - 1/365, 0.001), r, sigma, option_type.lower())pl = (new_bs['price'] - bs['price']) * 100pl_data.append({'Price Change %': f'{pct:+d}%', 'Stock Price': f'${new_S:.2f}','Option Price': f'${new_bs["price"]:.2f}', 'P/L (per 100)': f'${pl:+.2f}'})pl_df = pd.DataFrame(pl_data)strikes = np.linspace(S*0.7, S*1.3, 50)greeks_data = {'price': [], 'delta': [], 'gamma': [], 'theta': [], 'vega': []}for st in strikes:res = black_scholes(S, st, T, r, sigma, option_type.lower())for k in greeks_data:greeks_data[k].append(res.get(k, 0))fig = make_subplots(rows=2, cols=3,subplot_titles=('Price', 'Delta', 'Gamma', 'Theta (daily)', 'Vega', 'P/L at Expiry'),vertical_spacing=0.12, horizontal_spacing=0.08)colors = ['#2196F3', '#00C853', '#FF9800', '#FF5252', '#9C27B0', '#673AB7']for i, (k, v) in enumerate(greeks_data.items()):row, col = (i//3)+1, (i%3)+1fig.add_trace(go.Scatter(x=strikes, y=v, line=dict(color=colors[i], width=2), name=k), row=row, col=col)fig.add_vline(x=S, line_dash='dash', line_color='gray', row=row, col=col)expiry_payoff = [max(s-K,0) if option_type.lower()=='call' else max(K-s,0) for s in strikes]pl_expiry = [p - bs['price'] for p in expiry_payoff]fig.add_trace(go.Scatter(x=strikes, y=pl_expiry, line=dict(color='#673AB7', width=2), name='P/L Expiry'), row=2, col=3)fig.add_hline(y=0, line_dash='dot', line_color='gray', row=2, col=3)fig.update_layout(title=f'{ticker} {option_type.title()} Greeks (S=${S:.2f}, K=${K:.2f}, T={days}d, σ={sigma*100:.1f}%)',template='plotly_dark', height=650,paper_bgcolor='#0d1117', plot_bgcolor='#161b22', font=dict(color='#e6edf3'))md = f"""## {ticker} {option_type.title()} Analysis| Parameter | Value ||-----------|-------|| Spot (S) | ${S:.2f} || Strike (K) | ${K:.2f} ({strike_pct:.0f}% of spot) || Time to Expiry | {days} days || Risk-Free Rate | {r*100:.2f}% || Volatility | {sigma*100:.1f}% |### Greeks| Greek | Value ||-------|-------|| **Price** | ${bs['price']:.3f} || **Delta** | {bs['delta']:.4f} || **Gamma** | {bs['gamma']:.6f} || **Theta** | ${bs['theta']:.4f}/day || **Vega** | ${bs['vega']:.4f} || **Rho** | ${bs['rho']:.4f} || **d1** | {bs['d1']:.4f} || **d2** | {bs['d2']:.4f} |### P/L Scenarios (per 100 contracts){pl_df.to_markdown(index=False)}"""return fig, pl_df, md# MACROdef get_macro_data():macros = {}for t, name in [('^GSPC','S&P 500'),('^IXIC','Nasdaq'),('^TNX','10Y Treasury'),2 unmodified linestry:df = yf.Ticker(t).history(period='1mo')if not df.empty:macros[name] = {'price': df['Close'].iloc[-1], 'change_1m': (df['Close'].iloc[-1]/df['Close'].iloc[0]-1)*100}except:passreturn macrosdef ai_macro():macros = get_macro_data()macro_text = "Global Macro Snapshot:\n"for name, data in macros.items():macro_text += f"- {name}: ${data['price']:.2f} (1M change: {data['change_1m']:+.1f}%)\n"client = K2ThinkClient()return client.macro_analysis(macro_text)# UI FUNCTIONSdef analyze_stock(ticker, market_preset, period, interval):ticker = ticker.strip().upper()if not ticker:return [None]*6 + ["Enter a ticker."]suffix = MARKET_PRESETS.get(market_preset, {}).get('suffix', '')if suffix and not any(ticker.endswith(s) for s in suffix.split('|')):ticker = ticker + suffixdf, info, err = fetch_data(ticker, period)if df is None:return [None]*6 + [f"Error: {err}"]df = calc_indicators(df)sg = calc_signals(df)rk = calc_risk(df)if not rk:return [None]*6 + ["Need more data."]l = df.iloc[-1]p = df.iloc[-2] if len(df)>1 else lch = ((l['Close']/p['Close']-1)*100) if p['Close']>0 else 0c1 = make_candlestick(df, ticker, market_preset)c2 = make_macd(df, ticker)c3 = make_stoch(df, ticker)c4 = make_vol(df, ticker)c5 = make_adx(df, ticker)c6 = make_dist(df['Ret'].dropna(), ticker)info_lines = []if info:info_lines.append(f"| Name | {info.get('longName', ticker)} |")info_lines.append(f"| Sector | {info.get('sector', 'N/A')} |")info_lines.append(f"| Industry | {info.get('industry', 'N/A')} |")if info.get('marketCap'):info_lines.append(f"| Market Cap | {info.get('marketCap'):,} |")if info.get('fiftyTwoWeekHigh'):info_lines.append(f"| 52W High | ${info.get('fiftyTwoWeekHigh'):.2f} |")if info.get('fiftyTwoWeekLow'):info_lines.append(f"| 52W Low | ${info.get('fiftyTwoWeekLow'):.2f} |")if info.get('trailingPE'):info_lines.append(f"| P/E | {info.get('trailingPE'):.2f} |")mkt_info = "\n".join(info_lines)md = f"""# {ticker} - {sg['dir']} {sg['strength']} (Score: {sg['score']}/100)**Price:** ${l['Close']:.2f} | **Change:** {ch:+.2f}% | **Period:** {period}{mkt_info}## Signal Dashboard9 unmodified lines| Trend | {sg['trend'].upper()} | — || Momentum | {sg['mom']} | — || Volatility | {sg['vol']} | — || Ichimoku | {sg['ichimoku']} | — |## Risk Metrics| Metric | Value |17 unmodified lines| Kurtosis | {rk['ku']:.2f} || 63D Rolling Sharpe | {rk['roll_sharpe']:.2f} |"""return [c1, c2, c3, c4, c5, c6, md]def ai_analyze_stock(ticker, market_preset, period, interval):ticker = ticker.strip().upper()if not ticker:return "Enter a ticker."suffix = MARKET_PRESETS.get(market_preset, {}).get('suffix', '')if suffix and not any(ticker.endswith(s) for s in suffix.split('|')):ticker = ticker + suffixdf, info, err = fetch_data(ticker, period)if df is None:return f"Error: {err}"df = calc_indicators(df)sg = calc_signals(df)rk = calc_risk(df)26 unmodified linesclient = K2ThinkClient()return client.portfolio_advice(pd_str, corr_str, md, "Current macro: mixed signals, rates elevated, geopolitical uncertainty")def ai_chat(question, temp):if not question.strip():return "Enter a question."client = K2ThinkClient()return client.chat([{"role":"user","content":question}], temperature=temp, max_tokens=4096)# GRADIO APPdef build_app():with gr.Blocks(title="AlphaForge x K2 Think V2 — Institutional Quant Platform",theme=gr.themes.Soft(primary_hue="blue", secondary_hue="indigo", neutral_hue="slate",font=[gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"]),css="""3 unmodified lines.tab-nav { background: #0d1117 !important; border-bottom: 1px solid #30363d !important; }.tab-nav button { color: #8b949e !important; background: transparent !important; border: none !important; }.tab-nav button.selected { color: #58a6ff !important; border-bottom: 2px solid #58a6ff !important; }input, textarea, select { background: #21262d !important; color: #e6edf3 !important; border: 1px solid #30363d !important; }button.primary { background: linear-gradient(135deg, #1f6feb, #58a6ff) !important; color: white !important; border: none !important; border-radius: 8px !important; font-weight: 600 !important; }button.secondary { background: #21262d !important; color: #58a6ff !important; border: 1px solid #30363d !important; border-radius: 8px !important; }.title-bar { text-align: center; padding: 24px 0; }.title-bar h1 { font-size: 2.8em; font-weight: 800; margin: 0; background: linear-gradient(90deg, #58a6ff, #a371f7); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }.title-bar p { color: #8b949e; font-size: 1.1em; margin-top: 8px; }2 unmodified lines.badge-api { background: linear-gradient(135deg, #1f6feb, #a371f7); color: white; }.badge-data { background: #238636; color: white; }.badge-alpha { background: #8957e5; color: white; }.k2-active { text-align: center; padding: 8px; margin: 8px 0; border-radius: 8px; font-size: 0.9em; background: rgba(35,134,54,0.2); color: #3fb950; border: 1px solid #238636; }.k2-inactive { text-align: center; padding: 8px; margin: 8px 0; border-radius: 8px; font-size: 0.9em; background: rgba(209,36,47,0.2); color: #f85149; border: 1px solid #da3633; }""") as demo:gr.HTML("""<div class="title-bar"><h1>🔥 AlphaForge x K2 Think V2</h1><p>Institutional-Grade Quantitative Analysis Platform - Powered by MBZUAI's State-of-the-Art Reasoning Model</p></div><div class="badge-row"><span class="badge badge-api">🤖 K2 Think V2</span><span class="badge badge-data">📊 Multi-Market</span><span class="badge badge-alpha">🎯 AI Alpha</span><span class="badge badge-data">📐 Options</span><span class="badge badge-alpha">🔗 Pairs</span><span class="badge badge-api">🌍 Macro</span></div>""")k2_cls = "k2-active" if K2_API_KEY else "k2-inactive"k2_txt = "✅ K2 Think V2 API Connected" if K2_API_KEY else "⚠️ K2 Think V2 Not Configured — Add K2_API_KEY in Space Settings > Repository Secrets"gr.HTML(f'<div class="{k2_cls}">{k2_txt}</div>')with gr.Tab("📈 Technical Analysis"):with gr.Row():with gr.Column(scale=1):mkt_select = gr.Dropdown(label="🌍 Market", choices=list(MARKET_PRESETS.keys()), value="🇺🇸 US Equities")ticker_in = gr.Textbox(label="Ticker", value="AAPL", placeholder="e.g., AAPL, BTC-USD, EURUSD=X")period_in = gr.Dropdown(label="Period", choices=["1mo","3mo","6mo","1y","2y","5y"], value="6mo")interval_in = gr.Dropdown(label="Interval", choices=["1d","1wk","1mo"], value="1d")analyze_btn = gr.Button("🔍 Analyze", variant="primary", size="lg")12 unmodified lineswith gr.Row():ai_out = gr.Textbox(label="🤖 K2 Think V2 Analysis", lines=30, max_lines=50, show_copy_button=True)analyze_btn.click(fn=analyze_stock, inputs=[ticker_in, mkt_select, period_in, interval_in],outputs=[chart1, chart2, chart3, chart4, chart5, chart6, summary_out])ai_btn.click(fn=ai_analyze_stock, inputs=[ticker_in, mkt_select, period_in, interval_in],outputs=[ai_out])with gr.Tab("💼 Portfolio Optimizer"):with gr.Row():with gr.Column(scale=1):port_in = gr.Textbox(label="Tickers (comma-separated)", value="AAPL, MSFT, GOOGL, AMZN, NVDA")port_period = gr.Dropdown(label="Lookback", choices=["6mo","1y","2y","3y"], value="1y")opt_btn = gr.Button("🎯 Optimize", variant="primary", size="lg")ai_port_btn = gr.Button("🤖 AI Portfolio Advice", variant="secondary", size="lg")with gr.Column(scale=2):port_md = gr.Markdown()with gr.Row():3 unmodified linesweights_df = gr.DataFrame(label="Optimal Weights", interactive=False)with gr.Row():ai_port_out = gr.Textbox(label="🤖 AI Portfolio Advice", lines=25, max_lines=40, show_copy_button=True)opt_btn.click(fn=optimize_portfolio, inputs=[port_in, port_period], outputs=[frontier_plot, corr_plot, weights_df, port_md])ai_port_btn.click(fn=ai_portfolio, inputs=[port_in, port_period], outputs=[ai_port_out])with gr.Tab("🔗 Pairs Trading"):with gr.Row():with gr.Column(scale=1):6 unmodified lineswith gr.Row():pair_chart = gr.Plot(label="Spread Analysis")pair_scatter = gr.Plot(label="Price Relationship")pair_btn.click(fn=analyze_pair, inputs=[pair_a, pair_b, pair_period], outputs=[pair_chart, pair_scatter, pair_md])with gr.Tab("📐 Options Pricing"):with gr.Row():with gr.Column(scale=1):9 unmodified lineswith gr.Row():greeks_plot = gr.Plot(label="Greeks Analysis")opt_pl = gr.DataFrame(label="P/L Scenarios", interactive=False)opt_calc_btn.click(fn=analyze_options, inputs=[opt_ticker, opt_strike, opt_days, opt_rfr, opt_vol, opt_type],outputs=[greeks_plot, opt_pl, opt_md])with gr.Tab("🌍 Macro Analysis"):with gr.Row():macro_btn = gr.Button("🌍 Analyze Global Macro (K2 Think V2)", variant="primary", size="lg")with gr.Row():macro_out = gr.Textbox(label="🤖 K2 Think V2 Macro Analysis", lines=40, max_lines=60, show_copy_button=True)macro_btn.click(fn=ai_macro, outputs=[macro_out])with gr.Tab("💬 K2 Think V2 Chat"):gr.Markdown("## Direct Chat with K2 Think V2")gr.Markdown("Ask any financial question - strategy, market analysis, quant interview prep, portfolio advice.")with gr.Row():chat_in = gr.Textbox(label="Your Question", placeholder="e.g., 'Explain gamma scalping with a real trade example'", lines=4, scale=4)chat_temp = gr.Slider(label="Temp", minimum=0, maximum=1, value=0.4, step=0.1, scale=1)1 unmodified linechat_out = gr.Textbox(label="🤖 Response", lines=30, max_lines=50, show_copy_button=True)chat_btn.click(fn=ai_chat, inputs=[chat_in, chat_temp], outputs=[chat_out])with gr.Tab("ℹ️ About & Setup"):gr.Markdown(f"""## AlphaForge x K2 Think V25 unmodified lines|---------|-------------|| **📈 Technical Analysis** | 18+ indicators: RSI, MACD, Bollinger, VWAP, Stochastic, ADX, Ichimoku, ATR, MFI, OBV || **🌍 Multi-Market** | US, EU, UK, DE, JP, CN, IN equities + Crypto + Forex + Commodities + Indices || **💼 Portfolio** | Mean-variance optimization, efficient frontier, correlation matrix || **🔗 Pairs Trading** | Cointegration analysis, hedge ratio, half-life, Z-score signals || **📐 Options Pricing** | Black-Scholes + full Greeks (Delta, Gamma, Theta, Vega, Rho), P/L scenarios || **🌍 Macro Analysis** | Global cross-asset regime analysis via K2 Think V2 |20 unmodified linesreturn demoif __name__ == "__main__":demo = build_app()demo.queue().launch(server_name="0.0.0.0", server_port=7860)
app.py+226-500