Commit ·
75d9b3c
0
Parent(s):
Initial commit for HF Space
Browse filesFiles changed (40)
- .gitignoreAdded+3
- DockerfileAdded+31
- README.mdAdded+12
- backend/.DS_StoreAdded
- backend/__init__.pyAdded+1
- backend/agents/__init__.pyAdded+1
- backend/agents/alpha_scorer.pyAdded+90
- backend/agents/execution_agent.pyAdded+196
- backend/agents/news_agent.pyAdded+186
- backend/agents/portfolio_agent.pyAdded+104
- backend/agents/regime_agent.pyAdded+190
- backend/agents/risk_agent.pyAdded+150
- backend/agents/scan_pipeline.pyAdded+491
- backend/agents/signal_agent.pyAdded+250
- backend/agents/supervisor_agent.pyAdded+89
- backend/backtesting/backtester.pyAdded+181
- backend/backtesting/monte_carlo.pyAdded+72
- backend/backtesting/run_sample_test.pyAdded+49
- backend/data/__init__.pyAdded+1
- backend/data/fundamentals.pyAdded+124
- backend/data/market_data.pyAdded+152
- backend/data/store.pyAdded+252
- backend/features/__init__.pyAdded+1
- backend/features/feature_store.pyAdded+125
- backend/features/fundamental.pyAdded+40
- backend/features/momentum.pyAdded+74
- backend/features/technical.pyAdded+118
- backend/features/volatility.pyAdded+70
- backend/intelligence/__init__.pyAdded+1
- backend/intelligence/alert_classifier.pyAdded+96
- backend/intelligence/cache.pyAdded+127
- backend/intelligence/news_fetcher.pyAdded+250
- backend/intelligence/perplexity_client.pyAdded+72
- backend/intelligence/sentiment_analyzer.pyAdded+124
- backend/server.pyAdded+127
- config.pyAdded+145
- frontend/css/styles.cssAdded+354
- frontend/index.htmlAdded+129
- frontend/js/app.jsAdded+331
- requirements.txtAdded+17
123*.db*.parquet__pycache__/12345678910111213141516171819202122232425262728293031FROM python:3.11-slim
WORKDIR /app
# Install system dependencies if anyRUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ && rm -rf /var/lib/apt/lists/*
# Install python requirementsCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# Create necessary directoriesRUN mkdir -p /app/data /app/frontend
# Copy the rest of the applicationCOPY backend/ /app/backend/COPY frontend/ /app/frontend/COPY config.py /app/config.py
# Create a non-root user for Hugging Face space compatibilityRUN useradd -m -u 1000 userRUN chown -R user:user /appUSER user
# Expose the standard port for Hugging Face spacesEXPOSE 7860
# Run the applicationCMD ["uvicorn", "backend.server:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112---title: Swing Quant Engineemoji: 📈colorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860---
# Swing Quant Engine
An advanced multi-agent quantitative analysis and trading platform.1# Swing Quant Engine — Backend1# Agents layer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Alpha Scorer — Composite ranking for signals.Consolidates Technical, Volume, Sentiment, Regime, and Fundamental scores."""import loggingimport pandas as pdfrom config import ALPHA_WEIGHTS as AW
logger = logging.getLogger(__name__)
def compute_alpha_score(signal: dict, features: dict) -> float: """ Compute a composite alpha score (0-100) for a trade signal. Args: signal: The detected signal dictionary. features: The latest feature dictionary for the ticker. Returns: float: Alpha score from 0-100. """ score = 0.0 # 1. Momentum Component (0-100) # Using momentum_score from feature_store (which should be 0-100) momentum = features.get("momentum_score", 50) if momentum is not None: score += AW["momentum"] * float(momentum) # 2. Volume Breakout Component (0-100) # Scale vol_ratio: 1.2 -> 0, 2.0 -> 100 vol_ratio = features.get("vol_ratio", 1.0) if vol_ratio is not None and vol_ratio > 1.2: vol_score = min(100, (float(vol_ratio) - 1.2) * 125) score += AW["volume_breakout"] * vol_score else: vol_score = 0 # 3. Sentiment Component (0-100) # If news_agent found sentiment, use it. Otherwise use signal confidence as proxy. sentiment_val = signal.get("sentiment_score") if sentiment_val is None: sentiment_val = signal.get("confidence", 0.5) * 100 else: # Scale -1 to 1 into 0 to 100 sentiment_val = (sentiment_val + 1) * 50 score += AW["sentiment"] * sentiment_val # 4. Regime Fit (0-100) # Signals already filtered by regime, so if it made it here, it fits. # Higher confidence regime gives higher score. regime_conf = signal.get("regime_confidence", 0.5) * 100 score += AW["regime_fit"] * regime_conf # 5. Fundamental Component (0-100) # Using fundamental_score from features fund_score = features.get("fundamental_score", 50) if fund_score is not None: score += AW["fundamental"] * float(fund_score) final_score = round(min(100, max(0, score)), 1) # Save the component metrics to the signal dictionary for narrative generation signal["metrics_momentum"] = round(momentum, 1) if momentum else 0 signal["metrics_volume"] = round(vol_ratio, 2) if vol_ratio else 1.0 signal["metrics_sentiment"] = round(sentiment_val, 1) signal["metrics_fundamental"] = round(fund_score, 1) if fund_score else 0
# Log details if it's a high score if final_score > 75: logger.info(f"High Alpha [{signal.get('ticker')}]: {final_score} (M:{momentum:.0f} V:{vol_ratio:.1f} S:{sentiment_val:.0f})") return final_score
def rank_signals(signals: list[dict], feature_results: list[dict], top_n: int = 10) -> list[dict]: """ Score and rank a list of signals. """ # Map features by ticker for lookup f_map = {r["ticker"]: r.get("latest", {}) for r in feature_results} for s in signals: ticker = s.get("ticker", "") features = f_map.get(ticker, {}) s["alpha_score"] = compute_alpha_score(s, features) # Sort by score descending signals.sort(key=lambda x: x.get("alpha_score", 0), reverse=True) return signals[:top_n]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196"""Execution Agent — Trade plan construction.100% rule-based (zero LLM tokens).Builds complete trade plans with entry, targets, and scaling logic."""import loggingimport time
logger = logging.getLogger(__name__)
def _build_summary_html(signal: dict, news_items: list, sentiment_label: str) -> str: s_icon = "🟢" if sentiment_label == "Bullish" else ("🔴" if sentiment_label == "Bearish" else "⚪") top_news = news_items[0].get("title", "") if news_items else signal.get("reason", "No recent news") if len(top_news) > 65: top_news = top_news[:62] + "..." return f"<strong>{s_icon} {sentiment_label}</strong><br><span style='font-size:0.75rem;'>{top_news}</span>"
def construct_trade_plan(signal: dict) -> dict: """ Build a complete, actionable trade plan from a signal.
Returns a trade plan with: - Entry strategy (limit/market, scaling) - Stop loss (strict) - Multiple targets (T1/T2/T3) with scaling out logic - Time-based exit rules """ entry = signal.get("entry_price", 0) sl = signal.get("stop_loss", 0) t1 = signal.get("target_1", 0) t2 = signal.get("target_2", 0) t3 = signal.get("target_3", 0) quantity = signal.get("quantity", 0) signal_type = signal.get("signal_type", "") horizon = signal.get("horizon_days", 10)
# ── Entry Strategy ── if signal_type in ("volume_breakout", "bb_squeeze_breakout"): entry_type = "market" entry_note = "Enter at market — breakout requires immediate execution" else: entry_type = "limit" entry_note = f"Place limit order at {entry:.2f} or better"
# ── Scaling Strategy ── # Tranche 1: 60% at entry, Tranche 2: 40% on pullback confirmation tranche_1_qty = int(quantity * 0.6) or 1 tranche_2_qty = quantity - tranche_1_qty pullback_entry = round(entry * 0.985, 2) # 1.5% pullback
# ── Exit Strategy ── # Scale out at targets: 40% at T1, 30% at T2, 30% at T3 exit_plan = [] remaining = quantity if t1 and remaining > 0: t1_qty = int(quantity * 0.4) or 1 exit_plan.append({"target": "T1", "price": t1, "quantity": t1_qty, "action": "Sell 40%"}) remaining -= t1_qty if t2 and remaining > 0: t2_qty = int(quantity * 0.3) or 1 exit_plan.append({"target": "T2", "price": t2, "quantity": min(t2_qty, remaining), "action": "Sell 30%"}) remaining -= t2_qty if t3 and remaining > 0: exit_plan.append({"target": "T3", "price": t3, "quantity": remaining, "action": "Sell remaining"})
# ── Risk Management Rules ── risk_rules = [ f"Hard stop loss at {sl:.2f} — NO exceptions", f"Trail stop to breakeven after T1 is hit", f"Time exit: Close position after {horizon} trading days if no target hit", "If market regime changes to high_volatility, tighten stop by 50%", ]
# ── Build Detailed Narrative ── fund_data = signal.get("fundamental_data", {}) news_items = signal.get("news_items", []) risk_decision = signal.get("risk_decision", "approved")
# Technical section tech_narrative = ( f"<div class='narrative-section'>" f"<div class='narrative-heading'><i class='fa-solid fa-chart-line'></i> Technical Analysis</div>" f"<div class='narrative-body'>" f"Pattern: <strong>{signal_type.replace('_', ' ').title()}</strong> detected.<br>" f"Momentum Score: <span class='narrative-metric'>{signal.get('metrics_momentum', 0):.0f}/100</span> | " f"Volume: <span class='narrative-metric'>{signal.get('metrics_volume', 1):.1f}x</span> avg | " f"Confidence: <span class='narrative-metric'>{signal.get('confidence', 0)*100:.0f}%</span><br>" f"Horizon: {horizon} trading days | Regime: {signal.get('regime', 'N/A')}" f"</div></div>" )
# Fundamental section pe_str = f"{fund_data.get('pe_ratio', 0):.1f}" if fund_data.get('pe_ratio') else "N/A" roe_str = f"{fund_data.get('roe', 0)*100:.1f}%" if fund_data.get('roe') else "N/A" rev_growth_str = f"{fund_data.get('revenue_growth', 0)*100:.1f}%" if fund_data.get('revenue_growth') else "N/A" margin_str = f"{fund_data.get('profit_margin', 0)*100:.1f}%" if fund_data.get('profit_margin') else "N/A" rec_str = fund_data.get('recommendation', 'N/A') sector_str = fund_data.get('sector', 'Unknown') fund_score = signal.get('fundamental_score', signal.get('metrics_fundamental', 50))
fund_narrative = ( f"<div class='narrative-section'>" f"<div class='narrative-heading'><i class='fa-solid fa-building-columns'></i> Fundamental Quality</div>" f"<div class='narrative-body'>" f"Sector: <strong>{sector_str}</strong> | Score: <span class='narrative-metric'>{fund_score:.0f}/100</span><br>" f"P/E: {pe_str} | ROE: {roe_str} | Rev Growth: {rev_growth_str} | Margin: {margin_str}<br>" f"Analyst: <span class='narrative-tag'>{rec_str}</span>" f"</div></div>" )
# News/Sentiment section sentiment_score = signal.get('sentiment_score', 0) sentiment_label = "Bullish" if sentiment_score > 0.2 else ("Bearish" if sentiment_score < -0.2 else "Neutral") sentiment_class = "positive" if sentiment_score > 0.2 else ("negative" if sentiment_score < -0.2 else "neutral")
news_lines = "" if news_items: for n in news_items[:3]: s_icon = "🟢" if n.get("sentiment") == "positive" else ("🔴" if n.get("sentiment") == "negative" else "⚪") news_lines += f"{s_icon} {n.get('title', '')[:70]} <span class='narrative-source'>({n.get('source', '')})</span><br>" else: news_lines = "No ticker-specific news found in recent feeds.<br>"
news_narrative = ( f"<div class='narrative-section'>" f"<div class='narrative-heading'><i class='fa-solid fa-newspaper'></i> News & Sentiment</div>" f"<div class='narrative-body'>" f"Overall: <span class='narrative-sentiment {sentiment_class}'>{sentiment_label}</span> " f"(score: {sentiment_score:+.2f}) | {signal.get('news_count', 0)} articles matched<br>" f"{news_lines}" f"</div></div>" )
# Risk & Trade section sl_pct = round(abs(entry - sl) / entry * 100, 2) if entry else 0 risk_emoji = "✅" if risk_decision == "approved" else "⚠️" risk_label = "Approved" if risk_decision == "approved" else "Reduced Size"
trade_narrative = ( f"<div class='narrative-section'>" f"<div class='narrative-heading'><i class='fa-solid fa-shield-halved'></i> Risk & Trade Plan</div>" f"<div class='narrative-body'>" f"Risk Status: {risk_emoji} <strong>{risk_label}</strong> | " f"Alpha Score: <span class='narrative-metric gold'>{signal.get('alpha_score', 0):.1f}</span><br>" f"Entry: {entry_type.upper()} @ <span class='mono'>{entry:.2f}</span> | " f"SL: <span class='mono negative'>{sl:.2f}</span> (-{sl_pct:.1f}%) | " f"T1: <span class='mono positive'>{t1:.2f}</span> | " f"T2: <span class='mono positive'>{t2:.2f}</span> | " f"T3: <span class='mono positive'>{t3:.2f}</span><br>" f"R:R = <strong>{signal.get('risk_reward', 0):.1f}</strong> | " f"Qty: {quantity} shares | " f"Position: ₹{signal.get('position_value', 0):,.0f} ({signal.get('position_pct', 0):.1f}% portfolio)" f"</div></div>" )
full_narrative = tech_narrative + fund_narrative + news_narrative + trade_narrative
trade_plan = { **signal, "trade_plan": { "entry": { "type": entry_type, "price": entry, "note": entry_note, "tranche_1": {"qty": tranche_1_qty, "price": entry, "note": "Initial entry"}, "tranche_2": {"qty": tranche_2_qty, "price": pullback_entry, "note": "Add on pullback"}, }, "stop_loss": { "price": sl, "type": "hard", "pct_from_entry": round(abs(entry - sl) / entry * 100, 2), }, "targets": exit_plan, "risk_rules": risk_rules, "horizon_days": horizon, "max_hold_date": f"{horizon} trading days from entry", }, "status": "pending", "created_at": time.time(), "agent_name": "execution_agent", "narrative": full_narrative, "reason_summary": _build_summary_html(signal, news_items, sentiment_label), }
logger.info( f"Trade plan [{signal['ticker']}]: {entry_type} entry @ {entry:.2f}, " f"SL={sl:.2f}, T1={t1:.2f}, T2={t2:.2f}, qty={quantity}" ) return trade_plan
def construct_all_plans(signals: list[dict]) -> list[dict]: """Build trade plans for all sized signals.""" plans = [construct_trade_plan(s) for s in signals] logger.info(f"Constructed {len(plans)} trade plans") return plans123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import loggingimport osimport timefrom datetime import datetime, timedeltafrom dataclasses import dataclass
import requestsimport feedparser
from backend.intelligence.sentiment_analyzer import analyze_sentiment_batch
logger = logging.getLogger(__name__)
# RSS feeds focused on markets (reuse from portfolio_website)MARKET_RSS_FEEDS = [ ("https://feeds.finance.yahoo.com/rss/2.0/headline?s=^NSEI®ion=IN", "Yahoo Finance India"), ("https://feeds.finance.yahoo.com/rss/2.0/headline?s=^GSPC®ion=US", "Yahoo Finance US"), ("https://economictimes.indiatimes.com/markets/rssfeeds/1977021501.cms", "ET Markets"), ("https://www.cnbc.com/id/10001147/device/rss/rss.html", "CNBC"), ("https://www.moneycontrol.com/rss/marketreports.xml", "MoneyControl"),]
def fetch_market_news() -> list[dict]: """Fetch latest market news from RSS feeds.""" items = [] seen_urls = set()
for url, source in MARKET_RSS_FEEDS: try: feed = feedparser.parse(url) for entry in feed.entries[:15]: link = entry.get("link", "") if link in seen_urls: continue seen_urls.add(link) items.append({ "title": entry.get("title", ""), "summary": entry.get("summary", "")[:200], "url": link, "source": source, "published": entry.get("published", ""), }) except Exception as e: logger.warning(f"RSS fetch failed for {source}: {e}")
logger.info(f"Fetched {len(items)} news items from {len(MARKET_RSS_FEEDS)} sources") return items
def fetch_company_news(tickers: list[str]) -> list[dict]: """Fetch company-specific news from Finnhub if API key is present.""" api_key = os.getenv("FINNHUB_API_KEY", "").strip() if not api_key: return []
items = [] today = datetime.now().strftime("%Y-%m-%d") week_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
# Limit to top 15 tickers to avoid rate limits on free tier for ticker in tickers[:15]: try: # Clean ticker for Finnhub (remove .NS, etc for US-style) # Actually Finnhub supports some international, but primarily US clean_ticker = ticker.split('.')[0] if '.' in ticker else ticker resp = requests.get( "https://finnhub.io/api/v1/company-news", params={"symbol": clean_ticker, "from": week_ago, "to": today, "token": api_key}, timeout=10, ) if resp.status_code != 200: continue
for article in resp.json()[:3]: # Max 3 per ticker items.append({ "title": article.get("headline", ""), "summary": article.get("summary", "")[:200], "url": article.get("url", ""), "source": f"Finnhub ({article.get('source', 'unknown')})", "published": datetime.fromtimestamp(article.get("datetime", 0)).isoformat() if article.get("datetime") else "", "ticker": ticker }) time.sleep(0.1) # Be nice to rate limits except Exception as e: logger.warning(f"Finnhub fetch failed for {ticker}: {e}")
logger.info(f"Fetched {len(items)} company-specific items from Finnhub") return items
def analyze_news_for_tickers(news_items: list[dict], tickers: list[str]) -> list[dict]: """ Analyze news sentiment and match to specific tickers. Returns news items with sentiment + ticker matches. """ if not news_items: return []
# Build a ticker name map for matching ticker_names = {} for t in tickers: # Extract clean name from ticker: "TCS.NS" -> "TCS", "AAPL" -> "AAPL" clean = t.replace(".NS", "").replace(".BO", "").replace("-", "") ticker_names[clean.upper()] = t
# Run batched sentiment analysis sentiments = analyze_sentiment_batch(news_items)
results = [] for item, sentiment in zip(news_items, sentiments): title_upper = item["title"].upper() summary_upper = (item.get("summary") or "").upper() text = title_upper + " " + summary_upper
# Match tickers mentioned in headline matched_tickers = [] for name, full_ticker in ticker_names.items(): if len(name) >= 3 and name in text: matched_tickers.append(full_ticker)
# Also check sentiment targets for target in sentiment.get("targets", []): target_name = target.get("name", "").upper() if target_name in ticker_names: t = ticker_names[target_name] if t not in matched_tickers: matched_tickers.append(t)
# Generate event signal if strong sentiment + ticker match event_signal = None overall = sentiment.get("overall_sentiment", "neutral") confidence = sentiment.get("confidence", 0.5)
if matched_tickers and overall != "neutral" and confidence > 0.6: event_signal = { "type": "news_event", "direction": "bullish" if overall == "positive" else "bearish", "strength": confidence, "tickers": matched_tickers, }
results.append({ **item, "sentiment": overall, "sentiment_confidence": confidence, "impact_summary": sentiment.get("impact_summary", ""), "targets": sentiment.get("targets", []), "matched_tickers": matched_tickers, "event_signal": event_signal, })
# Filter to only ticker-relevant news relevant = [r for r in results if r["matched_tickers"]] logger.info(f"News analysis: {len(relevant)}/{len(results)} items matched to portfolio tickers") return relevant
def generate_news_signals(news_results: list[dict]) -> list[dict]: """ Convert strong news events into trade signals. Only generates signals for high-confidence sentiment with ticker matches. """ signals = [] for item in news_results: event = item.get("event_signal") if not event: continue
for ticker in event["tickers"]: signals.append({ "ticker": ticker, "signal_type": "news_event", "strength": round(event["strength"], 3), "confidence": round(event["strength"], 2), "horizon_days": 5, "reason": f"{event['direction'].title()} news: {item['title'][:80]}", "news_source": item.get("source"), "agent_name": "news_agent", "detected_at": time.time(), })
logger.info(f"News signals generated: {len(signals)}") return signals123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Portfolio Agent — Position sizing and risk budgeting.100% rule-based (zero LLM tokens).Uses Fractional Kelly Criterion + ATR-based sizing."""import logging
from config import RISK_PARAMS as RP
logger = logging.getLogger(__name__)
DEFAULT_PORTFOLIO_VALUE = 10_00_000 # ₹10L default
def size_position(signal: dict, portfolio_value: float = DEFAULT_PORTFOLIO_VALUE, existing_positions: list[dict] | None = None) -> dict: """ Calculate position size for a trade signal.
Uses the conservative approach: 1. Risk-based sizing: position_size = risk_budget / stop_distance 2. Fractional Kelly: reduce to 25% of optimal 3. Cap at max_position_pct of portfolio
Args: signal: Trade signal with entry_price, stop_loss portfolio_value: Total portfolio value existing_positions: Currently open positions
Returns: signal dict augmented with position sizing info """ entry = signal.get("entry_price", 0) stop_loss = signal.get("stop_loss", 0) confidence = signal.get("confidence", 0.5) risk_decision = signal.get("risk_decision", "approved")
if not entry or not stop_loss or entry <= 0: signal["position_size"] = 0 signal["position_reason"] = "Invalid entry/stop loss" return signal
# Stop loss distance sl_distance = abs(entry - stop_loss) sl_pct = sl_distance / entry
# ── Method 1: Risk-based sizing ── # Risk 1-2% of portfolio per trade risk_pct = 0.02 if confidence > 0.7 else 0.01 risk_amount = portfolio_value * risk_pct risk_based_qty = int(risk_amount / sl_distance) if sl_distance > 0 else 0
# ── Method 2: Kelly Criterion ── # Kelly% = (win_prob * avg_win / avg_loss) - (1 - win_prob) / 1 # Simplified using confidence as win probability rr = signal.get("risk_reward", 2.0) win_prob = min(confidence, 0.75) # Cap at 75% kelly_pct = (win_prob * rr - (1 - win_prob)) / rr if rr > 0 else 0 kelly_pct = max(0, kelly_pct) * RP["kelly_fraction"] # Fractional Kelly (25%) kelly_amount = portfolio_value * kelly_pct kelly_qty = int(kelly_amount / entry) if entry > 0 else 0
# ── Take the more conservative of the two ── quantity = min(risk_based_qty, kelly_qty) if kelly_qty > 0 else risk_based_qty
# ── Max position cap ── max_position = portfolio_value * (RP["max_position_pct"] / 100) max_qty = int(max_position / entry) if entry > 0 else 0 quantity = min(quantity, max_qty)
# ── Reduce if risk agent flagged ── if risk_decision == "reduce_size": quantity = int(quantity * 0.5)
# Ensure at least 1 share if signal is valid quantity = max(1, quantity) if quantity > 0 else 0
position_value = quantity * entry
signal["quantity"] = quantity signal["position_value"] = round(position_value, 2) signal["position_pct"] = round(position_value / portfolio_value * 100, 2) if portfolio_value else 0 signal["risk_amount"] = round(quantity * sl_distance, 2) signal["risk_pct_portfolio"] = round(quantity * sl_distance / portfolio_value * 100, 3) if portfolio_value else 0 signal["kelly_pct"] = round(kelly_pct * 100, 2) signal["sizing_method"] = "fractional_kelly + risk_based" signal["agent_name"] = "portfolio_agent"
logger.info( f"Position [{signal['ticker']}]: {quantity} shares @ {entry} = ₹{position_value:,.0f} " f"({signal['position_pct']:.1f}% of portfolio, risk={signal['risk_pct_portfolio']:.2f}%)" ) return signal
def size_all_positions(signals: list[dict], portfolio_value: float = DEFAULT_PORTFOLIO_VALUE) -> list[dict]: """Size positions for all approved signals.""" sized = [] for signal in signals: result = size_position(signal, portfolio_value) if result.get("quantity", 0) > 0: sized.append(result) logger.info(f"Sized {len(sized)}/{len(signals)} positions") return sized123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""Regime Agent — Market context detection.100% rule-based (zero LLM tokens).Detects bull/bear/range/volatile regimes using market-wide indicators."""import logging
import numpy as npimport pandas as pd
from backend.data.market_data import fetch_ohlcvfrom backend.features.technical import compute_technical_featuresfrom backend.features.volatility import compute_volatility_features
logger = logging.getLogger(__name__)
# Market indices for regime detectionREGIME_INDICES = { "india": "^NSEI", # Nifty 50 "us": "^GSPC", # S&P 500}VIX_INDICES = { "india": "^INDIAVIX", "us": "^VIX",}
def detect_regime(market: str = "india") -> dict: """ Detect current market regime for a given market.
Returns: { "market": "india"|"us", "regime": "trend_up"|"trend_down"|"range_bound"|"high_volatility", "trend": "bullish"|"bearish"|"neutral", "volatility_state": "low"|"medium"|"high"|"extreme", "vix": float, "breadth": float, # % above SMA50 (proxy) "confidence": float, "valid_signals": ["momentum_breakout", ...], # which signal types are valid "description": str, } """ index_ticker = REGIME_INDICES.get(market, "^GSPC") vix_ticker = VIX_INDICES.get(market, "^VIX")
# Fetch index data index_df = fetch_ohlcv(index_ticker, period="1y") if index_df.empty or len(index_df) < 200: logger.warning(f"Insufficient index data for {market} regime detection") return _default_regime(market)
# Compute features on the index features = compute_technical_features(index_df, index_ticker) features = compute_volatility_features(features, index_ticker) latest = features.iloc[-1]
# ── Trend Detection ── close = float(latest["Close"]) sma50 = latest.get("sma_50") sma200 = latest.get("sma_200") rsi = latest.get("rsi_14") adx = latest.get("ADX_14")
trend = "neutral" if sma50 and sma200: if close > float(sma50) > float(sma200): trend = "bullish" elif close < float(sma50) < float(sma200): trend = "bearish" elif close > float(sma200): trend = "neutral" # Above 200 but choppy else: trend = "bearish"
# ── Volatility State ── vol_regime = str(latest.get("vol_regime", "medium"))
# Try to get VIX vix_value = None try: vix_df = fetch_ohlcv(vix_ticker, period="5d") if not vix_df.empty: vix_value = float(vix_df.iloc[-1]["Close"]) if vix_value > 30: vol_regime = "high" elif vix_value > 40: vol_regime = "extreme" except Exception: pass
# ── Regime Classification ── if vol_regime in ("high", "extreme"): regime = "high_volatility" elif trend == "bullish" and adx and float(adx) > 25: regime = "trend_up" elif trend == "bearish" and adx and float(adx) > 25: regime = "trend_down" else: regime = "range_bound"
# ── Valid Signal Types Per Regime ── valid_signals_map = { "trend_up": ["momentum_breakout", "golden_cross", "macd_bullish_cross", "volume_breakout"], "trend_down": ["rsi_oversold_bounce", "support_bounce"], "range_bound": ["rsi_oversold_bounce", "bb_squeeze_breakout", "support_bounce", "macd_bullish_cross"], "high_volatility": ["rsi_oversold_bounce", "support_bounce"], # Only mean reversion in high vol }
# ── Breadth Proxy ── # Use index RSI and price position as breadth proxy breadth = 50.0 if rsi: breadth = float(rsi)
# ── Confidence ── confidence = 0.70 if adx and float(adx) > 30: confidence += 0.10 if vix_value and vix_value < 20: confidence += 0.05
description = _regime_description(regime, trend, vol_regime, vix_value, close, sma200)
result = { "market": market, "regime": regime, "trend": trend, "volatility_state": vol_regime, "vix": round(vix_value, 2) if vix_value else None, "breadth": round(breadth, 1), "index_close": round(close, 2), "index_sma200": round(float(sma200), 2) if sma200 else None, "adx": round(float(adx), 1) if adx else None, "confidence": round(confidence, 2), "valid_signals": valid_signals_map.get(regime, []), "description": description, }
logger.info(f"Regime [{market}]: {regime} | trend={trend} | vol={vol_regime} | VIX={vix_value}") return result
def filter_signals_by_regime(signals: list[dict], regime: dict) -> list[dict]: """ Filter signals to only those valid for the current regime. """ valid_types = set(regime.get("valid_signals", [])) if not valid_types: return signals # If no regime info, pass all through
filtered = [] for signal in signals: if signal.get("signal_type") in valid_types: signal["regime"] = regime["regime"] signal["regime_confidence"] = regime["confidence"] filtered.append(signal) else: logger.debug( f"{signal['ticker']}: {signal['signal_type']} rejected — invalid for {regime['regime']} regime" )
logger.info(f"Regime filter: {len(filtered)}/{len(signals)} signals passed ({regime['regime']})") return filtered
def _regime_description(regime, trend, vol, vix, close, sma200): parts = [f"Market is in {regime.replace('_', ' ')} mode."] if trend == "bullish": parts.append("Trend is bullish — price above key moving averages.") elif trend == "bearish": parts.append("Trend is bearish — caution advised.") if vix: parts.append(f"VIX at {vix:.1f}.") if sma200: pct = ((close / float(sma200)) - 1) * 100 parts.append(f"Index is {pct:+.1f}% from 200-day SMA.") return " ".join(parts)
def _default_regime(market): return { "market": market, "regime": "range_bound", "trend": "neutral", "volatility_state": "medium", "vix": None, "breadth": 50.0, "confidence": 0.5, "valid_signals": [ "rsi_oversold_bounce", "bb_squeeze_breakout", "support_bounce", "macd_bullish_cross" ], "description": "Unable to determine regime — defaulting to range-bound.", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150"""Risk Agent — Trade gatekeeper.100% rule-based (zero LLM tokens).Filters out bad trades based on liquidity, volatility, concentration, and drawdown."""import logging
from backend.data.market_data import is_indian_tickerfrom config import RISK_PARAMS as RP
logger = logging.getLogger(__name__)
def evaluate_risk(signal: dict, latest_features: dict, existing_positions: list[dict] | None = None) -> dict: """ Evaluate risk for a trade signal. Returns approval/rejection decision.
Args: signal: The trade signal dict latest_features: Latest feature row for the ticker existing_positions: Currently open positions (for concentration check)
Returns: { "decision": "approve"|"reject"|"reduce", "original_signal": signal, "risk_checks": {...}, "reason": str, } """ checks = {} reasons = [] decision = "approve" ticker = signal.get("ticker", "")
# ── 1. Liquidity Check ── avg_volume = float(latest_features.get("Volume") or 0) close = float(latest_features.get("Close") or 0) if avg_volume and close: daily_value = avg_volume * close threshold = RP["min_liquidity_inr"] if is_indian_ticker(ticker) else RP["min_liquidity_usd"] checks["liquidity"] = { "daily_value": round(daily_value), "threshold": threshold, "pass": daily_value >= threshold, } if not checks["liquidity"]["pass"]: decision = "reject" reasons.append(f"Illiquid: daily volume value {daily_value:,.0f} < {threshold:,.0f}")
# ── 2. Volatility Check ── atr_pct = latest_features.get("atr_pct") if atr_pct: checks["volatility"] = { "atr_pct": round(atr_pct, 2), "threshold": RP["max_atr_pct"], "pass": atr_pct <= RP["max_atr_pct"], } if not checks["volatility"]["pass"]: if decision != "reject": decision = "reduce" reasons.append(f"High volatility: ATR%={atr_pct:.1f}% > {RP['max_atr_pct']}%")
# ── 3. Risk:Reward Check ── rr = signal.get("risk_reward", 0) checks["risk_reward"] = { "value": rr, "threshold": 1.5, "pass": rr >= 1.5, } if not checks["risk_reward"]["pass"]: if decision == "approve": decision = "reduce" reasons.append(f"Poor R:R = {rr:.1f} (min 1.5)")
# ── 4. Sector Concentration ── if existing_positions: sector = latest_features.get("sector", "Unknown") sector_count = sum(1 for p in existing_positions if p.get("sector") == sector) sector_pct = (sector_count + 1) / max(len(existing_positions), 1) * 100 checks["sector_concentration"] = { "sector": sector, "current_pct": round(sector_pct, 1), "threshold": RP["max_sector_pct"], "pass": sector_pct <= RP["max_sector_pct"], } if not checks["sector_concentration"]["pass"]: if decision == "approve": decision = "reduce" reasons.append(f"Sector concentration: {sector} at {sector_pct:.0f}% > {RP['max_sector_pct']}%")
# ── 5. Stop Loss Distance ── entry = signal.get("entry_price", 0) sl = signal.get("stop_loss", 0) if entry and sl: sl_pct = abs(entry - sl) / entry * 100 checks["stop_loss_distance"] = { "pct": round(sl_pct, 2), "max_acceptable": 8.0, "pass": sl_pct <= 8.0, } if not checks["stop_loss_distance"]["pass"]: if decision == "approve": decision = "reduce" reasons.append(f"Wide stop loss: {sl_pct:.1f}% from entry")
reason = "; ".join(reasons) if reasons else "All risk checks passed"
result = { "decision": decision, "ticker": ticker, "signal_type": signal.get("signal_type"), "risk_checks": checks, "reason": reason, "agent_name": "risk_agent", }
emoji = {"approve": "✅", "reject": "❌", "reduce": "⚠️"} logger.info(f"{emoji.get(decision, '?')} Risk [{ticker}]: {decision} — {reason}") return result
def filter_signals_by_risk(signals: list[dict], feature_results: list[dict], existing_positions: list[dict] | None = None) -> list[dict]: """ Filter a list of signals through the risk agent. Returns only approved/reduced signals (rejects are dropped). """ # Build a lookup of features by ticker features_map = {} for result in feature_results: features_map[result["ticker"]] = result.get("latest", {})
approved = [] for signal in signals: ticker = signal.get("ticker", "") latest = features_map.get(ticker, {}) risk = evaluate_risk(signal, latest, existing_positions)
if risk["decision"] == "approve": signal["risk_decision"] = "approved" approved.append(signal) elif risk["decision"] == "reduce": signal["risk_decision"] = "reduce_size" signal["risk_reason"] = risk["reason"] approved.append(signal) # Rejected signals are dropped
logger.info(f"Risk filter: {len(approved)}/{len(signals)} signals passed") return approved123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491"""Scan Pipeline — Orchestrates the full signal detection flow WITHOUT LangGraph.This is the batch/scheduled scan mode: Features → Signals → Regime Filter → Fundamental Filter → News/Sentiment → Risk Filter → Sizing → Trade Plans
The LangGraph supervisor (supervisor.py) is used for HITL chat mode.This pipeline is the workhorse for daily/scheduled scans.
Now returns step-by-step pipeline stages for visual funnel display."""import loggingimport time
from backend.agents.alpha_scorer import rank_signalsfrom backend.agents.execution_agent import construct_all_plansfrom backend.agents.news_agent import fetch_market_news, fetch_company_news, analyze_news_for_tickersfrom backend.agents.portfolio_agent import size_all_positionsfrom backend.agents.regime_agent import detect_regime, filter_signals_by_regimefrom backend.agents.risk_agent import filter_signals_by_riskfrom backend.agents.signal_agent import scan_universefrom backend.data.fundamentals import fetch_fundamentals, compute_fundamental_scorefrom backend.data.store import get_storefrom backend.features.feature_store import compute_universe_featuresfrom config import INDIA_UNIVERSE, US_UNIVERSE
logger = logging.getLogger(__name__)
def _make_stage( stage_id: str, label: str, icon: str, count_in: int, count_out: int, tickers: list[str], duration_ms: float, details: str = "", rejected: list[dict] | None = None,) -> dict: """Create a pipeline stage record for the frontend funnel display.""" return { "id": stage_id, "label": label, "icon": icon, "count_in": count_in, "count_out": count_out, "tickers": tickers, "duration_ms": round(duration_ms, 1), "details": details, "rejected": rejected or [], }
def run_full_scan( tickers: list[str] | None = None, market: str = "both", portfolio_value: float = 10_00_000, top_n: int = 10,) -> dict: """ Run the complete swing trading scan pipeline.
Steps: 1. Compute features for universe 2. Detect raw signals (Signal Agent) 3. Detect market regime & filter (Regime Agent) 4. Fundamental quality filter 5. News & Sentiment filter 6. Risk filter (Risk Agent) 7. Size positions (Portfolio Agent) 8. Compute alpha score + rank (Alpha Scorer) 9. Construct trade plans (Execution Agent) 10. Store results
Args: tickers: Custom ticker list (None = use configured universe) market: "india", "us", or "both" portfolio_value: Total portfolio value for position sizing top_n: Number of top opportunities to return
Returns: Scan results dict with signals, regime, stats, and pipeline_stages """ start_time = time.time() store = get_store() pipeline_stages = []
# ── Step 0: Determine universe ── if tickers is None: if market == "india": tickers = INDIA_UNIVERSE elif market == "us": tickers = US_UNIVERSE else: tickers = INDIA_UNIVERSE + US_UNIVERSE
logger.info(f"═══ SCAN STARTED: {len(tickers)} tickers, market={market} ═══")
# ── STAGE 1: Universe ── stage_start = time.time() pipeline_stages.append(_make_stage( "universe", "Universe Scanned", "fa-globe", count_in=len(tickers), count_out=len(tickers), tickers=tickers[:], duration_ms=0, details=f"Scanning {len(tickers)} tickers across {'India + US' if market == 'both' else market.upper()} markets", ))
# ── STAGE 2: Compute features ── logger.info("Step 1/9: Computing features...") stage_start = time.time() feature_results = compute_universe_features(tickers, period="1y") stage_duration = (time.time() - stage_start) * 1000 logger.info(f"Features computed for {len(feature_results)}/{len(tickers)} tickers")
feature_tickers = [r["ticker"] for r in feature_results] failed_tickers = [t for t in tickers if t not in feature_tickers]
pipeline_stages.append(_make_stage( "features", "Features Computed", "fa-chart-line", count_in=len(tickers), count_out=len(feature_results), tickers=feature_tickers, duration_ms=stage_duration, details=f"Technical, momentum, volatility indicators computed. {len(failed_tickers)} tickers had insufficient data.", rejected=[{"ticker": t, "reason": "Insufficient OHLCV data"} for t in failed_tickers], ))
if not feature_results: return {"error": "No feature data available", "stats": {"duration": time.time() - start_time}, "pipeline_stages": pipeline_stages}
# ── STAGE 3: Detect signals ── logger.info("Step 2/9: Scanning for signals...") stage_start = time.time() raw_signals = scan_universe(feature_results) stage_duration = (time.time() - stage_start) * 1000 logger.info(f"Raw signals: {len(raw_signals)}")
signal_tickers = list(set(s["ticker"] for s in raw_signals)) no_signal_tickers = [t for t in feature_tickers if t not in signal_tickers]
pipeline_stages.append(_make_stage( "signals", "Signals Detected", "fa-bolt", count_in=len(feature_results), count_out=len(raw_signals), tickers=signal_tickers, duration_ms=stage_duration, details=f"Detected {len(raw_signals)} raw signals from {len(signal_tickers)} tickers using 7 pattern detectors (momentum breakout, RSI oversold, BB squeeze, MACD cross, golden cross, support bounce, volume breakout).", rejected=[{"ticker": t, "reason": "No signal patterns matched"} for t in no_signal_tickers], ))
if not raw_signals: duration = time.time() - start_time store.log_scan("full_scan", len(tickers), 0, duration) return { "signals": [], "regime": {}, "stats": { "universe_size": len(tickers), "features_computed": len(feature_results), "raw_signals": 0, "final_signals": 0, "duration_seconds": round(duration, 1), }, "pipeline_stages": pipeline_stages, }
# ── STAGE 4: Detect regime & filter ── logger.info("Step 3/9: Detecting market regime...") stage_start = time.time() regimes = {} if market in ("india", "both"): regimes["india"] = detect_regime("india") if market in ("us", "both"): regimes["us"] = detect_regime("us")
regime_filtered = [] regime_rejected = [] for signal in raw_signals: ticker = signal.get("ticker", "") mkt = "india" if ticker.endswith(".NS") or ticker.endswith(".BO") else "us" regime = regimes.get(mkt, regimes.get("india", regimes.get("us", {}))) filtered = filter_signals_by_regime([signal], regime) if filtered: regime_filtered.extend(filtered) else: regime_rejected.append({ "ticker": ticker, "signal_type": signal.get("signal_type", ""), "reason": f"Signal type '{signal.get('signal_type')}' invalid for '{regime.get('regime', 'unknown')}' regime ({regime.get('trend', '')} trend)", })
stage_duration = (time.time() - stage_start) * 1000 regime_tickers = list(set(s["ticker"] for s in regime_filtered))
# Build regime summary regime_desc_parts = [] for mkt_key, r in regimes.items(): regime_desc_parts.append(f"{mkt_key.upper()}: {r.get('regime', '?').replace('_', ' ')} ({r.get('trend', '?')} trend, VIX={r.get('vix', '?')})") regime_summary = " | ".join(regime_desc_parts)
pipeline_stages.append(_make_stage( "regime", "Regime Filtered", "fa-wind", count_in=len(raw_signals), count_out=len(regime_filtered), tickers=regime_tickers, duration_ms=stage_duration, details=f"Market regime: {regime_summary}. Only signal types compatible with current regime are kept.", rejected=regime_rejected, ))
logger.info(f"After regime filter: {len(regime_filtered)} signals")
if not regime_filtered: duration = time.time() - start_time store.log_scan("full_scan", len(tickers), 0, duration) return { "signals": [], "regimes": regimes, "stats": { "universe_size": len(tickers), "features_computed": len(feature_results), "raw_signals": len(raw_signals), "regime_filtered": 0, "final_signals": 0, "duration_seconds": round(duration, 1), }, "pipeline_stages": pipeline_stages, }
# ── STAGE 5: Fundamental filter ── logger.info("Step 4/9: Applying fundamental quality filter...") stage_start = time.time() fundamental_filtered = [] fundamental_rejected = [] fundamental_data_cache = {}
for signal in regime_filtered: ticker = signal.get("ticker", "") # Fetch fundamentals (with caching within this scan) if ticker not in fundamental_data_cache: try: fund_data = fetch_fundamentals(ticker) fund_score = compute_fundamental_score(fund_data) fundamental_data_cache[ticker] = {"data": fund_data, "score": fund_score} except Exception as e: logger.warning(f"Failed to fetch fundamentals for {ticker}: {e}") fundamental_data_cache[ticker] = {"data": {}, "score": 50.0}
cached = fundamental_data_cache[ticker] fund_score = cached["score"] fund_data = cached["data"] signal["fundamental_score"] = fund_score signal["fundamental_data"] = { "pe_ratio": fund_data.get("pe_ratio"), "roe": fund_data.get("roe"), "revenue_growth": fund_data.get("revenue_growth"), "earnings_growth": fund_data.get("earnings_growth"), "profit_margin": fund_data.get("profit_margin"), "sector": fund_data.get("sector", "Unknown"), "industry": fund_data.get("industry", "Unknown"), "name": fund_data.get("name", ticker), "recommendation": fund_data.get("recommendation"), "market_cap": fund_data.get("market_cap"), }
# Filter: reject signals with very poor fundamentals (score < 25) if fund_score < 25: fundamental_rejected.append({ "ticker": ticker, "signal_type": signal.get("signal_type", ""), "reason": f"Poor fundamental quality (score={fund_score:.0f}/100). PE={fund_data.get('pe_ratio', '?')}, ROE={fund_data.get('roe', '?')}", }) else: fundamental_filtered.append(signal)
stage_duration = (time.time() - stage_start) * 1000 fund_tickers = list(set(s["ticker"] for s in fundamental_filtered))
pipeline_stages.append(_make_stage( "fundamentals", "Fundamental Filtered", "fa-building-columns", count_in=len(regime_filtered), count_out=len(fundamental_filtered), tickers=fund_tickers, duration_ms=stage_duration, details=f"Stocks with fundamental quality score < 25/100 rejected. Checks PE ratio, ROE, revenue growth, margins, and analyst recommendations.", rejected=fundamental_rejected, ))
logger.info(f"After fundamental filter: {len(fundamental_filtered)} signals")
# ── STAGE 6: News & Sentiment filter ── logger.info("Step 5/9: News & sentiment analysis...") stage_start = time.time()
news_filtered = [] news_rejected = [] news_enrichment = {}
try: # Fetch latest market news (RSS) all_news = fetch_market_news() signal_tickers_list = list(set(s["ticker"] for s in fundamental_filtered)) # Fetch company-specific news (Finnhub) company_news = fetch_company_news(signal_tickers_list) if company_news: all_news.extend(company_news)
if all_news: # Analyze news for our signal tickers analyzed_news = analyze_news_for_tickers(all_news, signal_tickers_list) # Build a map of ticker -> news sentiment for item in analyzed_news: for t in item.get("matched_tickers", []): if t not in news_enrichment: news_enrichment[t] = [] news_enrichment[t].append({ "title": item.get("title", ""), "sentiment": item.get("sentiment", "neutral"), "confidence": item.get("sentiment_confidence", 0.5), "source": item.get("source", ""), "impact": item.get("impact_summary", ""), }) except Exception as e: logger.warning(f"News analysis failed, skipping filter: {e}")
for signal in fundamental_filtered: ticker = signal.get("ticker", "") ticker_news = news_enrichment.get(ticker, [])
# Check for strongly negative news has_bearish_news = False bearish_reasons = [] for news_item in ticker_news: if news_item["sentiment"] == "negative" and news_item["confidence"] > 0.7: has_bearish_news = True bearish_reasons.append(f"{news_item['source']}: {news_item['title'][:60]}")
# Enrich signal with news data signal["news_items"] = ticker_news if ticker_news: # Compute average sentiment score sentiments = [] for n in ticker_news: if n["sentiment"] == "positive": sentiments.append(n["confidence"]) elif n["sentiment"] == "negative": sentiments.append(-n["confidence"]) else: sentiments.append(0) signal["sentiment_score"] = sum(sentiments) / len(sentiments) if sentiments else 0 signal["news_count"] = len(ticker_news) else: signal["sentiment_score"] = 0 signal["news_count"] = 0
# Only reject if strongly bearish news with high confidence if has_bearish_news and len(bearish_reasons) >= 2: news_rejected.append({ "ticker": ticker, "signal_type": signal.get("signal_type", ""), "reason": f"Multiple bearish news signals: {'; '.join(bearish_reasons[:3])}", }) else: news_filtered.append(signal)
stage_duration = (time.time() - stage_start) * 1000 news_tickers = list(set(s["ticker"] for s in news_filtered))
pipeline_stages.append(_make_stage( "news_sentiment", "News & Sentiment Filtered", "fa-newspaper", count_in=len(fundamental_filtered), count_out=len(news_filtered), tickers=news_tickers, duration_ms=stage_duration, details=f"Analyzed {len(news_enrichment)} ticker-specific news items. Signals with multiple strongly bearish news events are rejected.", rejected=news_rejected, ))
logger.info(f"After news/sentiment filter: {len(news_filtered)} signals")
# ── STAGE 7: Risk filter ── logger.info("Step 6/9: Risk filtering...") stage_start = time.time()
# Track rejections by intercepting risk agent results pre_risk_tickers = set(s["ticker"] for s in news_filtered) risk_filtered = filter_signals_by_risk(news_filtered, feature_results) post_risk_tickers = set(s["ticker"] for s in risk_filtered)
risk_rejected = [] for signal in news_filtered: t = signal["ticker"] if t not in post_risk_tickers or signal not in risk_filtered: # Check if this specific signal was rejected if not any(rf["ticker"] == t and rf.get("signal_type") == signal.get("signal_type") for rf in risk_filtered): risk_rejected.append({ "ticker": t, "signal_type": signal.get("signal_type", ""), "reason": signal.get("risk_reason", "Failed risk checks (liquidity, volatility, R:R ratio, or stop-loss distance)"), })
stage_duration = (time.time() - stage_start) * 1000 risk_tickers = list(set(s["ticker"] for s in risk_filtered))
pipeline_stages.append(_make_stage( "risk", "Risk Filtered", "fa-shield-halved", count_in=len(news_filtered), count_out=len(risk_filtered), tickers=risk_tickers, duration_ms=stage_duration, details=f"Applied 5-point risk evaluation: liquidity check, volatility (ATR%), risk:reward ratio, sector concentration, and stop-loss distance.", rejected=risk_rejected, ))
logger.info(f"After risk filter: {len(risk_filtered)} signals")
# ── STAGE 8: Position sizing ── logger.info("Step 7/9: Sizing positions...") stage_start = time.time() sized = size_all_positions(risk_filtered, portfolio_value) stage_duration = (time.time() - stage_start) * 1000
sized_tickers = list(set(s["ticker"] for s in sized)) pipeline_stages.append(_make_stage( "sizing", "Position Sized", "fa-scale-balanced", count_in=len(risk_filtered), count_out=len(sized), tickers=sized_tickers, duration_ms=stage_duration, details=f"Fractional Kelly Criterion + risk-based sizing applied. Portfolio value: ₹{portfolio_value:,.0f}. Max position: 5% of portfolio.", ))
# ── STAGE 9: Alpha scoring + ranking ── logger.info("Step 8/9: Ranking and scoring...") stage_start = time.time() top_signals = rank_signals(sized, feature_results, top_n=top_n) stage_duration = (time.time() - stage_start) * 1000
scored_tickers = list(set(s["ticker"] for s in top_signals)) pipeline_stages.append(_make_stage( "scoring", "Alpha Scored & Ranked", "fa-ranking-star", count_in=len(sized), count_out=len(top_signals), tickers=scored_tickers, duration_ms=stage_duration, details=f"Composite alpha score (0-100) computed using: Momentum 35%, Volume 20%, Sentiment 20%, Regime Fit 15%, Fundamental 10%. Top {top_n} selected.", ))
# ── STAGE 10: Construct trade plans ── logger.info("Step 9/9: Constructing trade plans...") stage_start = time.time() trade_plans = construct_all_plans(top_signals) stage_duration = (time.time() - stage_start) * 1000
final_tickers = list(set(s["ticker"] for s in trade_plans)) pipeline_stages.append(_make_stage( "final", "Final Trade Plans", "fa-trophy", count_in=len(top_signals), count_out=len(trade_plans), tickers=final_tickers, duration_ms=stage_duration, details=f"Complete trade plans with entry strategy, scaling, stop-loss, 3 targets (T1/T2/T3), and risk management rules.", ))
# ── Store results ── for plan in trade_plans: store.save_signal(plan)
duration = time.time() - start_time store.log_scan("full_scan", len(tickers), len(trade_plans), duration)
stats = { "universe_size": len(tickers), "features_computed": len(feature_results), "raw_signals": len(raw_signals), "regime_filtered": len(regime_filtered), "fundamental_filtered": len(fundamental_filtered), "news_filtered": len(news_filtered), "risk_filtered": len(risk_filtered), "sized": len(sized), "final_signals": len(trade_plans), "duration_seconds": round(duration, 1), }
logger.info(f"═══ SCAN COMPLETE: {len(trade_plans)} opportunities in {duration:.1f}s ═══") logger.info( f"Pipeline: {len(tickers)} universe → {len(raw_signals)} signals → " f"{len(regime_filtered)} regime → {len(fundamental_filtered)} fundamental → " f"{len(news_filtered)} news → {len(risk_filtered)} risk → " f"{len(trade_plans)} final" )
return { "signals": trade_plans, "regimes": regimes, "stats": stats, "pipeline_stages": pipeline_stages, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""Signal Agent — Alpha signal generation.100% rule-based detection (zero LLM tokens for scanning).LLM used ONLY for synthesizing narrative explanations when presenting to user."""import loggingimport time
import numpy as npimport pandas as pd
from config import SIGNAL_PARAMS as SP
logger = logging.getLogger(__name__)
def detect_signals(ticker: str, latest: dict, df: pd.DataFrame) -> list[dict]: """ Detect swing trading signals from computed features. Returns a list of signal dicts for the ticker.
Args: ticker: Stock symbol latest: Latest feature row as dict (from feature_store) df: Full feature DataFrame for pattern detection """ signals = [] close = latest.get("Close") if not close: return signals
# ── 1. Momentum Breakout ── # Price above SMA50, RSI in bullish zone (40-65), volume spike sma50 = latest.get(f"sma_{SP['sma_medium']}") rsi = latest.get("rsi_14") vol_ratio = latest.get("vol_ratio") adx = latest.get("ADX_14")
if sma50 and rsi and vol_ratio: bullish_zone = SP["rsi_bullish_zone"] if (close > sma50 and bullish_zone[0] <= rsi <= bullish_zone[1] and vol_ratio >= SP["volume_spike_threshold"]): strength = min(1.0, (vol_ratio - 1.0) * 0.5 + (rsi - 40) / 50) atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(entry - 2.5 * atr, 2) target_1 = round(entry + 4 * atr, 2) target_2 = round(entry + 6 * atr, 2) target_3 = round(entry + 8 * atr, 2) rr = round((target_1 - entry) / max(entry - stop_loss, 0.01), 2)
signals.append({ "ticker": ticker, "signal_type": "momentum_breakout", "strength": round(strength, 3), "confidence": 0.70 + (0.1 if adx and adx > SP["adx_trending"] else 0), "horizon_days": 10, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": target_2, "target_3": target_3, "risk_reward": rr, "reason": f"Price above SMA50, RSI={rsi:.1f} in bullish zone, volume {vol_ratio:.1f}x avg", })
# ── 2. RSI Oversold Bounce ── if rsi and rsi < SP["rsi_oversold"]: # Check for bullish divergence: price making lower low but RSI making higher low atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(entry - 2 * atr, 2) target_1 = round(entry + 3 * atr, 2) target_2 = round(entry + 5 * atr, 2) target_3 = round(entry + 7 * atr, 2) rr = round((target_1 - entry) / max(entry - stop_loss, 0.01), 2)
strength = min(1.0, (SP["rsi_oversold"] - rsi) / 20) signals.append({ "ticker": ticker, "signal_type": "rsi_oversold_bounce", "strength": round(strength, 3), "confidence": 0.60, "horizon_days": 7, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": target_2, "target_3": round(entry + 7 * atr, 2), "risk_reward": rr, "reason": f"RSI={rsi:.1f} oversold, potential mean reversion setup", })
# ── 3. Bollinger Band Squeeze Breakout ── bb_squeeze = latest.get("bb_squeeze") bb_pct = latest.get("bb_pct") if bb_squeeze and bb_pct is not None and vol_ratio: if bb_squeeze < 3.0 and bb_pct > 0.8 and vol_ratio > SP["breakout_volume_confirm"]: atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(entry - 2.5 * atr, 2) target_1 = round(entry + 4 * atr, 2) strength = min(1.0, vol_ratio / 2.0)
signals.append({ "ticker": ticker, "signal_type": "bb_squeeze_breakout", "strength": round(strength, 3), "confidence": 0.72, "horizon_days": 12, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": round(entry + 5 * atr, 2), "target_3": round(entry + 7 * atr, 2), "risk_reward": round((target_1 - entry) / max(entry - stop_loss, 0.01), 2), "reason": f"Bollinger squeeze (width={bb_squeeze:.1f}%), breakout with volume {vol_ratio:.1f}x", })
# ── 4. MACD Bullish Crossover ── macd_val = latest.get("MACD_12_26_9") macd_signal = latest.get("MACDs_12_26_9") macd_hist = latest.get("MACDh_12_26_9") if macd_val is not None and macd_signal is not None and macd_hist is not None: # Check if histogram just turned positive (crossover) if len(df) > 2: prev_hist = df["MACDh_12_26_9"].iloc[-2] if "MACDh_12_26_9" in df.columns else None if prev_hist is not None and not pd.isna(prev_hist): if prev_hist < 0 and macd_hist > 0: trending = adx and adx > SP["adx_trending"] atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(entry - 2.5 * atr, 2) target_1 = round(entry + 4 * atr, 2)
signals.append({ "ticker": ticker, "signal_type": "macd_bullish_cross", "strength": 0.65 + (0.15 if trending else 0), "confidence": 0.68 + (0.1 if trending else 0), "horizon_days": 15, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": round(entry + 6 * atr, 2), "target_3": round(entry + 8 * atr, 2), "risk_reward": round((target_1 - entry) / max(entry - stop_loss, 0.01), 2), "reason": f"MACD bullish crossover" + (f", ADX={adx:.1f} confirms trend" if trending else ""), })
# ── 5. Golden Cross (SMA20 crosses above SMA50) ── golden = latest.get("golden_cross") if golden and golden == 1: atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(entry - 2.5 * atr, 2) target_1 = round(entry + 4 * atr, 2)
signals.append({ "ticker": ticker, "signal_type": "golden_cross", "strength": 0.75, "confidence": 0.72, "horizon_days": 20, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": round(entry + 6 * atr, 2), "target_3": round(entry + 8 * atr, 2), "risk_reward": round((target_1 - entry) / max(entry - stop_loss, 0.01), 2), "reason": "SMA20 crossed above SMA50 — medium-term trend reversal", })
# ── 6. Support Bounce ── at_support = latest.get("at_support") if at_support and at_support == 1 and rsi and rsi < 40: support = latest.get("support", close * 0.97) atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(support - atr, 2) target_1 = round(entry + 3 * atr, 2)
signals.append({ "ticker": ticker, "signal_type": "support_bounce", "strength": 0.60, "confidence": 0.62, "horizon_days": 8, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": round(entry + 5 * atr, 2), "target_3": round(entry + 7 * atr, 2), "risk_reward": round((target_1 - entry) / max(entry - stop_loss, 0.01), 2), "reason": f"Price at support ({support:.2f}), RSI={rsi:.1f} — potential bounce", })
# ── 7. Volume Breakout (price new high + volume confirmation) ── resistance = latest.get("resistance") at_resistance = latest.get("at_resistance") if at_resistance and at_resistance == 1 and vol_ratio and vol_ratio > SP["breakout_volume_confirm"]: if close >= (resistance or 0) * 0.99: atr = latest.get("atr_14", close * 0.02) entry = close stop_loss = round(resistance - 1.5 * atr, 2) if resistance else round(entry - 2 * atr, 2) target_1 = round(entry + 3 * atr, 2)
signals.append({ "ticker": ticker, "signal_type": "volume_breakout", "strength": min(1.0, vol_ratio / 2.5), "confidence": 0.70, "horizon_days": 12, "entry_price": round(entry, 2), "stop_loss": stop_loss, "target_1": target_1, "target_2": round(entry + 5 * atr, 2), "target_3": round(entry + 7 * atr, 2), "risk_reward": round((target_1 - entry) / max(entry - stop_loss, 0.01), 2), "reason": f"Breaking resistance ({resistance:.2f}) with volume {vol_ratio:.1f}x avg", })
for s in signals: s["agent_name"] = "signal_agent" s["detected_at"] = time.time()
if signals: logger.info(f"{ticker}: Detected {len(signals)} signals: {[s['signal_type'] for s in signals]}")
return signals
def scan_universe(feature_results: list[dict]) -> list[dict]: """ Scan an entire universe of pre-computed features for signals. Returns all detected signals across all tickers. """ all_signals = [] for result in feature_results: ticker = result.get("ticker", "") latest = result.get("latest", {}) df = result.get("df", pd.DataFrame()) if latest and not df.empty: signals = detect_signals(ticker, latest, df) all_signals.extend(signals)
all_signals.sort(key=lambda s: s.get("strength", 0), reverse=True) logger.info(f"Universe scan: {len(all_signals)} signals from {len(feature_results)} tickers") return all_signals1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889"""Supervisor Agent — LangGraph orchestrator for HITL chat mode.Routes user queries to the appropriate tools/specialists."""import jsonimport loggingimport operatorfrom typing import Annotated, Sequence, TypedDict
from langchain_core.messages import BaseMessage, HumanMessage, SystemMessagefrom langchain_openai import ChatOpenAIfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.prebuilt import ToolNodefrom langchain_core.tools import tool
from backend.agents.scan_pipeline import run_full_scanfrom backend.agents.regime_agent import detect_regimefrom backend.agents.news_agent import fetch_market_news
logger = logging.getLogger(__name__)
class AgentState(TypedDict): messages: Annotated[Sequence[BaseMessage], operator.add]
@tooldef get_market_regime(market: str = "india") -> str: """Get the current market regime, trend, and volatility state for a given market ('india' or 'us').""" res = detect_regime(market) return json.dumps(res, indent=2)
@tooldef run_swing_scan(market: str = "both", top_n: int = 5) -> str: """Run a full pipeline scan to find the top swing trading opportunities. Returns scan stats.""" res = run_full_scan(market=market, top_n=top_n) # Return stats summary to avoid massive text in chat return json.dumps(res.get("stats", {"error": "Scan failed"}), indent=2)
@tooldef get_market_news() -> str: """Fetch the latest market news from various RSS feeds.""" news = fetch_market_news() # Summarize to avoid massive context summary = [{"title": n["title"], "source": n["source"]} for n in news[:10]] return json.dumps(summary, indent=2)
tools = [get_market_regime, run_swing_scan, get_market_news]tool_node = ToolNode(tools)
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)llm_with_tools = llm.bind_tools(tools)
def supervisor_node(state: AgentState): messages = state["messages"] # Prepend system message if not present if not any(isinstance(m, SystemMessage) for m in messages): sys_msg = SystemMessage( content="You are a senior quantitative trading supervisor agent. " "You have access to specialists via tools. " "Use tools to answer queries about market regime or swing trading scans. " "If a tool fails, report the error to the user gracefully." ) messages = [sys_msg] + messages
response = llm_with_tools.invoke(messages) return {"messages": [response]}
def should_continue(state: AgentState) -> str: messages = state["messages"] last_message = messages[-1] if last_message.tool_calls: return "tools" return END
workflow = StateGraph(AgentState)workflow.add_node("supervisor", supervisor_node)workflow.add_node("tools", tool_node)
workflow.add_edge(START, "supervisor")workflow.add_conditional_edges("supervisor", should_continue, ["tools", END])workflow.add_edge("tools", "supervisor")
app = workflow.compile()
def invoke_supervisor(query: str) -> str: """Entry point for the HITL chat.""" initial_state = {"messages": [HumanMessage(content=query)]} result = app.invoke(initial_state) return result["messages"][-1].content123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181import loggingimport timeimport pandas as pdimport numpy as npfrom datetime import datetime
from backend.agents.signal_agent import detect_signalsfrom backend.agents.regime_agent import detect_regime, filter_signals_by_regimefrom backend.agents.risk_agent import evaluate_riskfrom backend.agents.portfolio_agent import size_positionfrom backend.agents.alpha_scorer import compute_alpha_scorefrom backend.features.feature_store import compute_universe_featuresfrom config import BACKTEST_PARAMS as BPfrom config import RISK_PARAMS as RP
logger = logging.getLogger(__name__)
def run_portfolio_backtest(tickers: list[str], period: str = "2y", initial_capital: float = 10_00_000): """ Run a walk-forward portfolio backtest. Simulates the daily scan pipeline over historical data. """ start_time = time.time() logger.info(f"🚀 Starting Walk-Forward Backtest: {len(tickers)} tickers, period={period}")
# 1. Fetch data and compute all features upfront # We get a list of dicts: {"ticker": str, "df": DataFrame, "latest": dict} # For backtesting, we'll use the 'df' which contains the full history feature_results = compute_universe_features(tickers, period=period) if not feature_results: return {"error": "No data found for backtest"}
# Find common date range across all tickers all_dates = [] for r in feature_results: all_dates.extend(r["df"].index.tolist()) unique_dates = sorted(list(set(all_dates))) # Start from index 100 to ensure indicators (like SMA200) are warmed up test_dates = unique_dates[100:] logger.info(f"Backtesting over {len(test_dates)} trading days...")
# Portfolio State capital = initial_capital portfolio_value = initial_capital active_trades = [] # List of trade dicts equity_curve = [] trade_log = []
# 2. Walk-forward loop (Day by Day) for i, current_date in enumerate(test_dates): # Update current portfolio value based on latest prices current_equity = capital still_active = [] for trade in active_trades: ticker = trade["ticker"] # Get price at current_date for this ticker ticker_data = next((r["df"] for r in feature_results if r["ticker"] == ticker), None) if ticker_data is not None and current_date in ticker_data.index: current_price = ticker_data.loc[current_date, "Close"] high_price = ticker_data.loc[current_date, "High"] low_price = ticker_data.loc[current_date, "Low"] # Check Stop Loss / Targets if low_price <= trade["stop_loss"]: # SL Hit exit_price = trade["stop_loss"] pnl = (exit_price - trade["entry_price"]) * trade["quantity"] capital += (trade["quantity"] * exit_price) trade_log.append({**trade, "exit_date": current_date, "exit_price": exit_price, "pnl": pnl, "status": "SL"}) elif high_price >= trade["target_1"]: # Target 1 Hit (Simplification: Exit 50% at T1, 50% at T2 or SL) # For this V1, let's just exit full at Target 1 exit_price = trade["target_1"] pnl = (exit_price - trade["entry_price"]) * trade["quantity"] capital += (trade["quantity"] * exit_price) trade_log.append({**trade, "exit_date": current_date, "exit_price": exit_price, "pnl": pnl, "status": "TP1"}) else: # Trade still open current_equity += (trade["quantity"] * current_price) still_active.append(trade) else: # No data for this day, assume trade continues still_active.append(trade) active_trades = still_active portfolio_value = current_equity equity_curve.append({"date": current_date, "equity": portfolio_value})
# --- Daily Scan Simulation --- # 1. Detect signals for this day daily_signals = [] for r in feature_results: ticker = r["ticker"] df_until_now = r["df"].loc[:current_date] if len(df_until_now) < 2 or current_date not in df_until_now.index: continue latest_row = df_until_now.iloc[-1].to_dict() # Wrap detect_signals to only see history signals = detect_signals(ticker, latest_row, df_until_now) daily_signals.extend(signals)
if not daily_signals: continue
# 2. Simple Regime (Backtest version) # Note: In a real backtest, we'd fetch index data for each date. # For V1, we assume a neutral regime or use a simplified index check if available. regime = {"regime": "trend_up", "confidence": 0.8, "valid_signals": ["momentum_breakout", "golden_cross", "macd_bullish_cross", "volume_breakout"]}
# 3. Filter & Score # (Filtering logic simplified for backtest) scored_signals = [] for s in daily_signals: ticker = s["ticker"] r = next((res for res in feature_results if res["ticker"] == ticker), None) latest_features = r["df"].loc[:current_date].iloc[-1].to_dict() # Risk check risk = evaluate_risk(s, latest_features, active_trades) if risk["decision"] in ("approve", "reduce"): s["alpha_score"] = compute_alpha_score(s, latest_features) scored_signals.append(s)
scored_signals.sort(key=lambda x: x["alpha_score"], reverse=True)
# 4. Execute Top Signals (Limited by available capital) for s in scored_signals[:3]: # Max 3 new trades per day if any(t["ticker"] == s["ticker"] for t in active_trades): continue # Already in this stock # Size position s = size_position(s, portfolio_value, active_trades) cost = s["quantity"] * s["entry_price"] if cost > 0 and capital >= cost: capital -= cost active_trades.append({**s, "entry_date": current_date})
# 3. Performance Metrics duration = time.time() - start_time performance = _calculate_metrics(equity_curve, trade_log, initial_capital) logger.info(f"✅ Backtest Complete in {duration:.1f}s. Final Equity: {portfolio_value:,.0f}") return { "metrics": performance, "equity_curve": equity_curve, "trades": trade_log, "duration_seconds": duration }
def _calculate_metrics(equity_curve, trade_log, initial_capital): if not equity_curve: return {} df_equity = pd.DataFrame(equity_curve) final_equity = df_equity["equity"].iloc[-1] total_return_pct = (final_equity / initial_capital - 1) * 100 # Drawdown df_equity["peak"] = df_equity["equity"].cummax() df_equity["drawdown"] = (df_equity["equity"] - df_equity["peak"]) / df_equity["peak"] * 100 max_drawdown = df_equity["drawdown"].min() # Trade stats df_trades = pd.DataFrame(trade_log) win_rate = 0 if not df_trades.empty: win_rate = (df_trades["pnl"] > 0).mean() * 100 return { "total_return_pct": round(total_return_pct, 2), "max_drawdown_pct": round(max_drawdown, 2), "win_rate_pct": round(win_rate, 1), "total_trades": len(trade_log), "final_equity": round(final_equity, 2) }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Monte Carlo Simulation — Stress testing the strategy by shuffling trade sequences."""import numpy as npimport pandas as pdfrom typing import List
def run_monte_carlo(trades: List[dict], initial_capital: float, iterations: int = 1000): """ Run Monte Carlo simulation on a list of historical trades. Args: trades: List of trade dictionaries with 'pnl' and 'entry_price'. initial_capital: Starting capital. iterations: Number of simulations. """ if not trades: return {"error": "No trades to simulate"}
pnls = [t["pnl"] for t in trades] results = []
for _ in range(iterations): # Shuffle the order of trades shuffled_pnls = np.random.choice(pnls, size=len(pnls), replace=True) equity = initial_capital equity_curve = [initial_capital] max_dd = 0 peak = initial_capital for pnl in shuffled_pnls: equity += pnl equity_curve.append(equity) if equity > peak: peak = equity dd = (peak - equity) / peak if dd > max_dd: max_dd = dd results.append({ "final_equity": equity, "max_drawdown": max_dd * 100, "return_pct": (equity / initial_capital - 1) * 100 })
df_results = pd.DataFrame(results) stats = { "avg_return": df_results["return_pct"].mean(), "median_return": df_results["return_pct"].median(), "worst_case_return": df_results["return_pct"].min(), "best_case_return": df_results["return_pct"].max(), "avg_drawdown": df_results["max_drawdown"].mean(), "max_drawdown_95th": df_results["max_drawdown"].quantile(0.95), # Risk at 95% confidence "ruin_probability": (df_results["final_equity"] < initial_capital * 0.5).mean() * 100 # Prob of losing 50% } return stats, df_results
def print_mc_report(stats): print("\n" + "="*40) print(" MONTE CARLO STRESS TEST") print("="*40) print(f"Avg Return: {stats['avg_return']:.2f}%") print(f"Median Return: {stats['median_return']:.2f}%") print(f"Best Case: {stats['best_case_return']:.2f}%") print(f"Worst Case: {stats['worst_case_return']:.2f}%") print(f"Avg Drawdown: {stats['avg_drawdown']:.2f}%") print(f"Max DD (95% CI): {stats['max_drawdown_95th']:.2f}%") print(f"Prob. of Ruin: {stats['ruin_probability']:.1f}%") print("="*40)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849"""Sample Backtest Script — Test the walk-forward engine on a small subset."""import loggingfrom backend.backtesting.backtester import run_portfolio_backtestfrom config import INDIA_UNIVERSE, US_UNIVERSE
# Setup logginglogging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
def main(): # 1. Select a small test universe (5 India, 5 US) test_tickers = INDIA_UNIVERSE[:5] + US_UNIVERSE[:5] # 2. Run backtest for last 1 year print(f"Starting sample backtest on: {test_tickers}") results = run_portfolio_backtest(test_tickers, period="1y", initial_capital=10_00_000) if "error" in results: print(f"Error: {results['error']}") return
# 3. Print Summary metrics = results["metrics"] print("\n" + "="*40) print(" BACKTEST RESULTS SUMMARY") print("="*40) print(f"Total Return: {metrics['total_return_pct']}%") print(f"Max Drawdown: {metrics['max_drawdown_pct']}%") print(f"Win Rate: {metrics['win_rate_pct']}%") print(f"Total Trades: {metrics['total_trades']}") print(f"Final Equity: ₹{metrics['final_equity']:,.2f}") print("="*40) # 4. Run Monte Carlo Stress Test if results["trades"]: from backend.backtesting.monte_carlo import run_monte_carlo, print_mc_report mc_stats, _ = run_monte_carlo(results["trades"], 10_00_000) print_mc_report(mc_stats)
# List last 5 trades if results["trades"]: print("\nLast 5 Trades:") for t in results["trades"][-5:]: status = t.get("status", "Open") print(f"- {t['ticker']}: Entry {t['entry_price']} | Exit {t.get('exit_price', 'N/A')} | PnL {t.get('pnl', 0):.2f} | {status}")
if __name__ == "__main__": main()1# Data layer123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Fundamentals — Fetch key fundamental data from yfinance.Provides value, growth, and quality metrics for alpha scoring."""import logging
import yfinance as yf
logger = logging.getLogger(__name__)
def fetch_fundamentals(ticker: str) -> dict: """ Fetch key fundamental metrics for a ticker. Returns a dict with value, growth, and quality indicators. """ try: stock = yf.Ticker(ticker) info = stock.info or {}
fundamentals = { "ticker": ticker, # Valuation "pe_ratio": info.get("trailingPE") or info.get("forwardPE"), "pb_ratio": info.get("priceToBook"), "ps_ratio": info.get("priceToSalesTrailing12Months"), "ev_ebitda": info.get("enterpriseToEbitda"), "peg_ratio": info.get("pegRatio"), # Growth "revenue_growth": info.get("revenueGrowth"), "earnings_growth": info.get("earningsGrowth"), "earnings_quarterly_growth": info.get("earningsQuarterlyGrowth"), # Profitability "profit_margin": info.get("profitMargins"), "operating_margin": info.get("operatingMargins"), "roe": info.get("returnOnEquity"), "roa": info.get("returnOnAssets"), # Dividend "dividend_yield": info.get("dividendYield"), # Size & Liquidity "market_cap": info.get("marketCap"), "avg_volume": info.get("averageVolume"), "avg_volume_10d": info.get("averageDailyVolume10Day"), # Analyst "target_mean": info.get("targetMeanPrice"), "target_low": info.get("targetLowPrice"), "target_high": info.get("targetHighPrice"), "recommendation": info.get("recommendationKey"), "num_analysts": info.get("numberOfAnalystOpinions"), # Info "sector": info.get("sector", "Unknown"), "industry": info.get("industry", "Unknown"), "name": info.get("shortName", ticker), "currency": info.get("currency", "USD"), }
logger.info(f"{ticker}: Fetched fundamentals (PE={fundamentals['pe_ratio']}, sector={fundamentals['sector']})") return fundamentals
except Exception as e: logger.error(f"{ticker}: Failed to fetch fundamentals: {e}") return {"ticker": ticker, "error": str(e)}
def compute_fundamental_score(fundamentals: dict) -> float: """ Compute a composite fundamental quality score (0-100). Blends value, growth, and quality. """ score = 50.0 # Start neutral
# Value component (lower PE = more value, capped) pe = fundamentals.get("pe_ratio") if pe and pe > 0: if pe < 15: score += 10 elif pe < 25: score += 5 elif pe > 50: score -= 10
# Growth component rev_growth = fundamentals.get("revenue_growth") if rev_growth: if rev_growth > 0.20: score += 15 elif rev_growth > 0.10: score += 8 elif rev_growth < 0: score -= 10
earn_growth = fundamentals.get("earnings_growth") if earn_growth: if earn_growth > 0.20: score += 10 elif earn_growth > 0.10: score += 5 elif earn_growth < -0.10: score -= 10
# Profitability roe = fundamentals.get("roe") if roe: if roe > 0.20: score += 10 elif roe > 0.15: score += 5 elif roe < 0: score -= 15
margin = fundamentals.get("profit_margin") if margin: if margin > 0.20: score += 5 elif margin < 0: score -= 10
# Analyst sentiment rec = fundamentals.get("recommendation") if rec: rec_scores = {"strongBuy": 10, "buy": 5, "hold": 0, "sell": -10, "strongSell": -15} score += rec_scores.get(rec, 0)
return max(0.0, min(100.0, score))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""Market Data — yfinance wrapper with smart Parquet caching.Fetches OHLCV data for individual tickers and batches with rate limiting."""import loggingimport timefrom datetime import datetime, timedelta
import pandas as pdimport yfinance as yf
from backend.data.store import get_storefrom config import PARQUET_DIR
logger = logging.getLogger(__name__)
# Rate limiting: max 5 requests per second_last_request_time = 0.0_REQUEST_INTERVAL = 0.25 # 250ms between requests
def _rate_limit(): global _last_request_time elapsed = time.time() - _last_request_time if elapsed < _REQUEST_INTERVAL: time.sleep(_REQUEST_INTERVAL - elapsed) _last_request_time = time.time()
def fetch_ohlcv(ticker: str, period: str = "1y", force_refresh: bool = False) -> pd.DataFrame: """ Fetch OHLCV data for a single ticker with Parquet caching. Only fetches new data since last cached date (incremental).
Args: ticker: Stock symbol (e.g., 'TCS.NS', 'AAPL') period: yfinance period string (default '1y') force_refresh: If True, re-download everything
Returns: DataFrame with columns: Open, High, Low, Close, Volume """ store = get_store()
if not force_refresh: cached = store.load_ohlcv(ticker) if cached is not None and not cached.empty: last_date = cached.index[-1] # If data is recent enough (within 1 day for weekdays), return cache days_stale = (datetime.now() - last_date.to_pydatetime().replace(tzinfo=None)).days if days_stale <= 1: logger.debug(f"{ticker}: Using cached data ({len(cached)} rows, last: {last_date.date()})") return cached
# Incremental: fetch only new data start_date = (last_date + timedelta(days=1)).strftime("%Y-%m-%d") try: _rate_limit() new_data = yf.download( ticker, start=start_date, progress=False, auto_adjust=True, threads=False ) if new_data is not None and not new_data.empty: # Handle MultiIndex columns from yfinance if isinstance(new_data.columns, pd.MultiIndex): new_data.columns = new_data.columns.get_level_values(0) combined = pd.concat([cached, new_data]) combined = combined[~combined.index.duplicated(keep='last')] combined.sort_index(inplace=True) store.save_ohlcv(ticker, combined) logger.info(f"{ticker}: Updated with {len(new_data)} new rows (total: {len(combined)})") return combined else: logger.debug(f"{ticker}: No new data since {last_date.date()}") return cached except Exception as e: logger.warning(f"{ticker}: Incremental update failed ({e}), using cache") return cached
# Full download try: _rate_limit() logger.info(f"{ticker}: Downloading {period} of OHLCV data...") df = yf.download(ticker, period=period, progress=False, auto_adjust=True, threads=False)
if df is None or df.empty: logger.warning(f"{ticker}: No data returned from yfinance") return pd.DataFrame()
# Handle MultiIndex columns from yfinance if isinstance(df.columns, pd.MultiIndex): df.columns = df.columns.get_level_values(0)
# Cache to Parquet store.save_ohlcv(ticker, df) logger.info(f"{ticker}: Cached {len(df)} rows ({df.index[0].date()} to {df.index[-1].date()})") return df
except Exception as e: logger.error(f"{ticker}: Failed to fetch OHLCV: {e}") # Try returning stale cache as fallback cached = store.load_ohlcv(ticker) if cached is not None: logger.warning(f"{ticker}: Serving stale cache as fallback") return cached return pd.DataFrame()
def fetch_batch(tickers: list[str], period: str = "1y") -> dict[str, pd.DataFrame]: """ Fetch OHLCV for multiple tickers with rate limiting. Returns dict of {ticker: DataFrame}. """ results = {} total = len(tickers)
for i, ticker in enumerate(tickers): try: df = fetch_ohlcv(ticker, period=period) if not df.empty: results[ticker] = df if (i + 1) % 10 == 0: logger.info(f"Batch progress: {i + 1}/{total} tickers fetched") except Exception as e: logger.error(f"{ticker}: Batch fetch error: {e}")
logger.info(f"Batch complete: {len(results)}/{total} tickers successful") return results
def get_latest_price(ticker: str) -> dict: """Get the latest available price data for a ticker.""" df = fetch_ohlcv(ticker, period="5d") if df.empty: return {} last = df.iloc[-1] prev = df.iloc[-2] if len(df) > 1 else last return { "ticker": ticker, "close": round(float(last["Close"]), 2), "prev_close": round(float(prev["Close"]), 2), "change_pct": round((float(last["Close"]) - float(prev["Close"])) / float(prev["Close"]) * 100, 2), "volume": int(last["Volume"]), "high": round(float(last["High"]), 2), "low": round(float(last["Low"]), 2), "date": str(last.name.date()), }
def is_indian_ticker(ticker: str) -> bool: """Check if ticker is an Indian stock (NSE/BSE).""" return ticker.endswith(".NS") or ticker.endswith(".BO")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""Storage Layer — SQLite for structured data, Parquet for OHLCV time series.Provides a unified interface for persisting and querying all quant data."""import jsonimport loggingimport sqlite3import timefrom contextlib import contextmanagerfrom pathlib import Path
import pandas as pd
from config import DB_PATH, PARQUET_DIR
logger = logging.getLogger(__name__)
class QuantStore: """Unified storage: SQLite (signals, features, logs) + Parquet (OHLCV)."""
def __init__(self, db_path: Path = DB_PATH): self.db_path = db_path self._init_db()
def _init_db(self): """Create SQLite tables if they don't exist.""" with self._conn() as conn: conn.executescript(""" -- Feature cache CREATE TABLE IF NOT EXISTS feature_cache ( ticker TEXT NOT NULL, feature_name TEXT NOT NULL, computed_at REAL NOT NULL, data_json TEXT NOT NULL, PRIMARY KEY (ticker, feature_name) );
-- Signals generated by agents CREATE TABLE IF NOT EXISTS signals ( id INTEGER PRIMARY KEY AUTOINCREMENT, ticker TEXT NOT NULL, signal_type TEXT NOT NULL, strength REAL, confidence REAL, horizon_days INTEGER, entry_price REAL, stop_loss REAL, target_1 REAL, target_2 REAL, target_3 REAL, risk_reward REAL, alpha_score REAL, regime TEXT, concern_level TEXT, agent_name TEXT, narrative TEXT, created_at REAL DEFAULT (strftime('%s','now')), status TEXT DEFAULT 'active' );
-- Agent decision log CREATE TABLE IF NOT EXISTS agent_logs ( id INTEGER PRIMARY KEY AUTOINCREMENT, agent_name TEXT NOT NULL, action TEXT NOT NULL, input_summary TEXT, output_summary TEXT, tokens_used INTEGER DEFAULT 0, latency_ms REAL, created_at REAL DEFAULT (strftime('%s','now')) );
-- Trade tracking (paper + live) CREATE TABLE IF NOT EXISTS trades ( id INTEGER PRIMARY KEY AUTOINCREMENT, ticker TEXT NOT NULL, side TEXT NOT NULL, -- 'long' or 'short' entry_price REAL, exit_price REAL, stop_loss REAL, quantity INTEGER, entry_date TEXT, exit_date TEXT, pnl REAL, pnl_pct REAL, status TEXT DEFAULT 'open', -- open, closed, stopped signal_id INTEGER, notes TEXT, created_at REAL DEFAULT (strftime('%s','now')), FOREIGN KEY (signal_id) REFERENCES signals(id) );
-- Scan history CREATE TABLE IF NOT EXISTS scan_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, scan_type TEXT NOT NULL, universe_size INTEGER, signals_found INTEGER, duration_seconds REAL, created_at REAL DEFAULT (strftime('%s','now')) ); """) logger.info(f"SQLite initialized at {self.db_path}")
@contextmanager def _conn(self): """Context manager for SQLite connections with WAL mode.""" conn = sqlite3.connect(str(self.db_path), timeout=10) conn.execute("PRAGMA journal_mode=WAL") conn.execute("PRAGMA busy_timeout=5000") conn.row_factory = sqlite3.Row try: yield conn conn.commit() except Exception: conn.rollback() raise finally: conn.close()
# ── Parquet (OHLCV) ──
def save_ohlcv(self, ticker: str, df: pd.DataFrame): """Save OHLCV DataFrame to Parquet file (one per ticker).""" safe_name = ticker.replace(".", "_").replace("-", "_") path = PARQUET_DIR / f"{safe_name}.parquet" df.to_parquet(path, engine="pyarrow", index=True) logger.debug(f"Saved {len(df)} rows OHLCV for {ticker}")
def load_ohlcv(self, ticker: str) -> pd.DataFrame | None: """Load cached OHLCV from Parquet. Returns None if not cached.""" safe_name = ticker.replace(".", "_").replace("-", "_") path = PARQUET_DIR / f"{safe_name}.parquet" if not path.exists(): return None try: df = pd.read_parquet(path, engine="pyarrow") return df except Exception as e: logger.warning(f"Error reading Parquet for {ticker}: {e}") return None
def get_ohlcv_last_date(self, ticker: str) -> str | None: """Get the last date in cached OHLCV for incremental updates.""" df = self.load_ohlcv(ticker) if df is None or df.empty: return None return str(df.index[-1].date())
# ── Feature Cache ──
def save_features(self, ticker: str, feature_name: str, data: dict): """Cache computed features in SQLite.""" with self._conn() as conn: conn.execute( "INSERT OR REPLACE INTO feature_cache (ticker, feature_name, computed_at, data_json) VALUES (?, ?, ?, ?)", (ticker, feature_name, time.time(), json.dumps(data)), )
def load_features(self, ticker: str, feature_name: str, max_age_hours: float = 12) -> dict | None: """Load cached features if not stale.""" with self._conn() as conn: row = conn.execute( "SELECT data_json, computed_at FROM feature_cache WHERE ticker=? AND feature_name=?", (ticker, feature_name), ).fetchone() if not row: return None age_hours = (time.time() - row["computed_at"]) / 3600 if age_hours > max_age_hours: return None return json.loads(row["data_json"])
# ── Signals ──
def save_signal(self, signal: dict) -> int: """Store a generated signal. Returns signal ID.""" with self._conn() as conn: cursor = conn.execute( """INSERT INTO signals (ticker, signal_type, strength, confidence, horizon_days, entry_price, stop_loss, target_1, target_2, target_3, risk_reward, alpha_score, regime, concern_level, agent_name, narrative) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", ( signal.get("ticker"), signal.get("signal_type"), signal.get("strength"), signal.get("confidence"), signal.get("horizon_days"), signal.get("entry_price"), signal.get("stop_loss"), signal.get("target_1"), signal.get("target_2"), signal.get("target_3"), signal.get("risk_reward"), signal.get("alpha_score"), signal.get("regime"), signal.get("concern_level"), signal.get("agent_name"), signal.get("narrative"), ), ) return cursor.lastrowid
def get_active_signals(self, limit: int = 50) -> list[dict]: """Get currently active signals, ordered by alpha score.""" with self._conn() as conn: rows = conn.execute( "SELECT * FROM signals WHERE status='active' ORDER BY alpha_score DESC LIMIT ?", (limit,), ).fetchall() return [dict(r) for r in rows]
def deactivate_old_signals(self, max_age_days: int = 14): """Mark old signals as expired.""" cutoff = time.time() - (max_age_days * 86400) with self._conn() as conn: conn.execute( "UPDATE signals SET status='expired' WHERE status='active' AND created_at < ?", (cutoff,), )
# ── Agent Logs ──
def log_agent(self, agent_name: str, action: str, input_summary: str = "", output_summary: str = "", tokens_used: int = 0, latency_ms: float = 0): """Log an agent decision for auditing.""" with self._conn() as conn: conn.execute( """INSERT INTO agent_logs (agent_name, action, input_summary, output_summary, tokens_used, latency_ms) VALUES (?, ?, ?, ?, ?, ?)""", (agent_name, action, input_summary[:500], output_summary[:500], tokens_used, latency_ms), )
# ── Scan History ──
def log_scan(self, scan_type: str, universe_size: int, signals_found: int, duration: float): with self._conn() as conn: conn.execute( "INSERT INTO scan_history (scan_type, universe_size, signals_found, duration_seconds) VALUES (?, ?, ?, ?)", (scan_type, universe_size, signals_found, duration), )
def get_scan_history(self, limit: int = 20) -> list[dict]: with self._conn() as conn: rows = conn.execute( "SELECT * FROM scan_history ORDER BY created_at DESC LIMIT ?", (limit,) ).fetchall() return [dict(r) for r in rows]
# ── Singleton ──_store: QuantStore | None = None
def get_store() -> QuantStore: global _store if _store is None: _store = QuantStore() return _store1# Feature engine123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Feature Store — Central registry for computing and caching all features.Single entry point for the signal engine to get a complete feature set."""import loggingimport time
import pandas as pd
from backend.data.market_data import fetch_ohlcvfrom backend.features.fundamental import compute_fundamental_featuresfrom backend.features.momentum import compute_momentum_featuresfrom backend.features.technical import compute_technical_featuresfrom backend.features.volatility import compute_volatility_features
logger = logging.getLogger(__name__)
def compute_all_features(ticker: str, period: str = "1y") -> dict: """ Compute ALL features for a single ticker.
Returns a dict with: - 'df': Full feature DataFrame (time series) - 'latest': Latest row as a flat dict (for signal engine) - 'fundamentals': Fundamental metrics dict - 'ticker': The ticker symbol - 'computed_at': Timestamp """ start = time.time() logger.info(f"{ticker}: Computing all features...")
# 1. Fetch OHLCV ohlcv = fetch_ohlcv(ticker, period=period) if ohlcv.empty: logger.error(f"{ticker}: No OHLCV data — cannot compute features") return {"ticker": ticker, "error": "no_data"}
# 2. Technical features df = compute_technical_features(ohlcv, ticker)
# 3. Momentum features df = compute_momentum_features(df, ticker)
# 4. Volatility features df = compute_volatility_features(df, ticker)
# 5. Fundamentals (separate — not time-series) fundamentals = compute_fundamental_features(ticker)
# 6. Extract latest row as flat dict latest = {} if not df.empty: last_row = df.iloc[-1] for k, v in last_row.items(): try: if pd.notna(v): latest[k] = round(float(v), 4) if isinstance(v, (int, float)) else str(v) else: latest[k] = None except (TypeError, ValueError): latest[k] = str(v) if v is not None else None
# Add fundamental score to latest latest["fundamental_score"] = fundamentals.get("fundamental_score", 50.0) latest["sector"] = fundamentals.get("sector", "Unknown") latest["industry"] = fundamentals.get("industry", "Unknown") latest["market_cap"] = fundamentals.get("market_cap") latest["pe_ratio"] = fundamentals.get("pe_ratio")
elapsed = round(time.time() - start, 2) logger.info(f"{ticker}: All features computed in {elapsed}s ({len(df)} rows, {len(df.columns)} cols)")
return { "ticker": ticker, "df": df, "latest": latest, "fundamentals": fundamentals, "computed_at": time.time(), "elapsed_seconds": elapsed, }
def compute_universe_features(tickers: list[str], period: str = "1y") -> list[dict]: """ Compute features for an entire universe of tickers. Returns a list of feature dicts (one per ticker). """ results = [] total = len(tickers)
for i, ticker in enumerate(tickers): try: result = compute_all_features(ticker, period) if "error" not in result: results.append(result) else: logger.warning(f"{ticker}: Skipped — {result.get('error')}") except Exception as e: logger.error(f"{ticker}: Feature computation failed: {e}")
if (i + 1) % 10 == 0: logger.info(f"Universe progress: {i + 1}/{total} tickers processed")
logger.info(f"Universe features complete: {len(results)}/{total} successful") return results
def get_cross_sectional_matrix(feature_results: list[dict], columns: list[str] | None = None) -> pd.DataFrame: """ Build a cross-sectional matrix (tickers × features) from computed results. Useful for ranking and comparison. """ rows = [] for result in feature_results: latest = result.get("latest", {}) latest["ticker"] = result["ticker"] rows.append(latest)
df = pd.DataFrame(rows) if columns and not df.empty: available = [c for c in columns if c in df.columns] df = df[["ticker"] + available]
return df12345678910111213141516171819202122232425262728293031323334353637383940"""Fundamental Features — Value, growth, quality scores from yfinance data."""import logging
from backend.data.fundamentals import compute_fundamental_score, fetch_fundamentalsfrom backend.data.store import get_store
logger = logging.getLogger(__name__)
def compute_fundamental_features(ticker: str) -> dict: """ Fetch fundamentals and compute a composite score. Uses SQLite cache to avoid refetching within 24 hours.
Returns: dict with all fundamental metrics + composite score """ store = get_store()
# Check cache (24h TTL for fundamentals) cached = store.load_features(ticker, "fundamentals", max_age_hours=24) if cached: logger.debug(f"{ticker}: Using cached fundamentals") return cached
# Fetch fresh fundamentals = fetch_fundamentals(ticker) if "error" in fundamentals: return {"ticker": ticker, "fundamental_score": 50.0, "error": fundamentals["error"]}
# Compute composite score fundamentals["fundamental_score"] = compute_fundamental_score(fundamentals)
# Cache store.save_features(ticker, "fundamentals", fundamentals) logger.info(f"{ticker}: Fundamental score = {fundamentals['fundamental_score']:.1f}")
return fundamentals1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374"""Momentum Features — Returns, relative strength, and trend momentum metrics."""import logging
import numpy as npimport pandas as pd
logger = logging.getLogger(__name__)
def compute_momentum_features(df: pd.DataFrame, ticker: str = "") -> pd.DataFrame: """ Compute momentum-specific features on top of OHLCV data.
Adds: - Multi-horizon returns (1d, 5d, 10d, 20d, 60d) - Cumulative returns - Rate of change - Momentum score (composite) """ if df.empty or len(df) < 60: logger.warning(f"{ticker}: Insufficient data for momentum features") return df
features = df.copy()
# ── Multi-Horizon Returns ── for period in [1, 5, 10, 20, 60]: features[f"return_{period}d"] = features["Close"].pct_change(period)
# ── Cumulative Return (since start of data) ── features["cum_return"] = (features["Close"] / features["Close"].iloc[0]) - 1
# ── Momentum (price vs N-day ago price) ── features["momentum_10d"] = features["Close"] - features["Close"].shift(10) features["momentum_20d"] = features["Close"] - features["Close"].shift(20)
# ── Relative Strength (simple: stock return vs rolling mean) ── features["rs_20d"] = features["return_20d"] / features["return_20d"].rolling(20).std().replace(0, np.nan)
# ── Acceleration (change in momentum) ── features["momentum_accel"] = features["momentum_10d"] - features["momentum_10d"].shift(5)
# ── Trend Consistency (% of positive days over last 20 days) ── daily_returns = features["Close"].pct_change() features["positive_day_pct_20"] = daily_returns.rolling(20).apply(lambda x: (x > 0).sum() / len(x), raw=True)
# ── Composite Momentum Score (0-100) ── def _momentum_score(row): score = 50.0 r5 = row.get("return_5d") r20 = row.get("return_20d") r60 = row.get("return_60d") accel = row.get("momentum_accel") pos_pct = row.get("positive_day_pct_20")
if r5 and not np.isnan(r5): score += min(15, max(-15, r5 * 500)) if r20 and not np.isnan(r20): score += min(15, max(-15, r20 * 200)) if r60 and not np.isnan(r60): score += min(10, max(-10, r60 * 100)) if accel and not np.isnan(accel): score += 5 if accel > 0 else -5 if pos_pct and not np.isnan(pos_pct): score += (pos_pct - 0.5) * 20
return max(0.0, min(100.0, score))
features["momentum_score"] = features.apply(_momentum_score, axis=1)
logger.info(f"{ticker}: Computed momentum features") return features123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Technical Features — Compute all standard TA indicators using pandas-ta.Returns a feature DataFrame that can be fed into the signal engine."""import logging
import pandas as pdimport pandas_ta as ta
from config import SIGNAL_PARAMS as SP
logger = logging.getLogger(__name__)
def compute_technical_features(df: pd.DataFrame, ticker: str = "") -> pd.DataFrame: """ Compute comprehensive technical indicators for a single ticker's OHLCV DataFrame.
Args: df: DataFrame with columns Open, High, Low, Close, Volume (DatetimeIndex) ticker: For logging
Returns: DataFrame with original OHLCV + all computed features """ if df.empty or len(df) < 50: logger.warning(f"{ticker}: Insufficient data ({len(df)} rows) for technical features") return df
features = df.copy()
# ── Trend Indicators ── features[f"sma_{SP['sma_short']}"] = ta.sma(features["Close"], length=SP["sma_short"]) features[f"sma_{SP['sma_medium']}"] = ta.sma(features["Close"], length=SP["sma_medium"]) features[f"sma_{SP['sma_long']}"] = ta.sma(features["Close"], length=SP["sma_long"]) features[f"ema_{SP['ema_fast']}"] = ta.ema(features["Close"], length=SP["ema_fast"]) features[f"ema_{SP['ema_slow']}"] = ta.ema(features["Close"], length=SP["ema_slow"])
# MACD macd = ta.macd(features["Close"], fast=SP["macd_fast"], slow=SP["macd_slow"], signal=SP["macd_signal"]) if macd is not None: features = pd.concat([features, macd], axis=1)
# ADX (trend strength) adx = ta.adx(features["High"], features["Low"], features["Close"], length=14) if adx is not None: features = pd.concat([features, adx], axis=1)
# ── Momentum Indicators ── features["rsi_14"] = ta.rsi(features["Close"], length=14) features["rsi_7"] = ta.rsi(features["Close"], length=7)
stoch = ta.stoch(features["High"], features["Low"], features["Close"]) if stoch is not None: features = pd.concat([features, stoch], axis=1)
features["willr"] = ta.willr(features["High"], features["Low"], features["Close"]) features["roc_10"] = ta.roc(features["Close"], length=10) features["roc_20"] = ta.roc(features["Close"], length=20) features["cci_20"] = ta.cci(features["High"], features["Low"], features["Close"], length=20)
# ── Volatility Indicators ── bb = ta.bbands(features["Close"], length=SP["bb_period"], std=SP["bb_std"]) if bb is not None: features = pd.concat([features, bb], axis=1)
features["atr_14"] = ta.atr(features["High"], features["Low"], features["Close"], length=SP["atr_period"]) features["atr_pct"] = (features["atr_14"] / features["Close"]) * 100 # ATR as % of price
kc = ta.kc(features["High"], features["Low"], features["Close"]) if kc is not None: features = pd.concat([features, kc], axis=1)
# ── Volume Indicators ── features["obv"] = ta.obv(features["Close"], features["Volume"]) features[f"vol_sma_{SP['volume_sma_period']}"] = ta.sma(features["Volume"], length=SP["volume_sma_period"]) features["vol_ratio"] = features["Volume"] / features[f"vol_sma_{SP['volume_sma_period']}"]
# ── Price Position Relative to MAs ── features["price_vs_sma20"] = (features["Close"] / features[f"sma_{SP['sma_short']}"]) - 1 features["price_vs_sma50"] = (features["Close"] / features[f"sma_{SP['sma_medium']}"]) - 1 features["price_vs_sma200"] = (features["Close"] / features[f"sma_{SP['sma_long']}"]) - 1
# ── Crossover Signals (binary) ── sma_s = features[f"sma_{SP['sma_short']}"] sma_m = features[f"sma_{SP['sma_medium']}"] features["golden_cross"] = ((sma_s > sma_m) & (sma_s.shift(1) <= sma_m.shift(1))).astype(int) features["death_cross"] = ((sma_s < sma_m) & (sma_s.shift(1) >= sma_m.shift(1))).astype(int)
ema_f = features[f"ema_{SP['ema_fast']}"] ema_sl = features[f"ema_{SP['ema_slow']}"] features["ema_bullish_cross"] = ((ema_f > ema_sl) & (ema_f.shift(1) <= ema_sl.shift(1))).astype(int)
# ── Support / Resistance (rolling highs/lows) ── lookback = SP["breakout_lookback"] features["resistance"] = features["High"].rolling(lookback).max() features["support"] = features["Low"].rolling(lookback).min() features["at_resistance"] = (features["Close"] >= features["resistance"] * 0.98).astype(int) features["at_support"] = (features["Close"] <= features["support"] * 1.02).astype(int)
# ── Bollinger Band Position ── bb_upper = features.get(f"BBU_{SP['bb_period']}_{SP['bb_std']}") bb_lower = features.get(f"BBL_{SP['bb_period']}_{SP['bb_std']}") if bb_upper is not None and bb_lower is not None: bb_width = bb_upper - bb_lower features["bb_pct"] = (features["Close"] - bb_lower) / bb_width.replace(0, float("nan")) features["bb_squeeze"] = (bb_width / features["Close"] * 100) # Width as % of price
logger.info(f"{ticker}: Computed {len(features.columns) - len(df.columns)} technical features") return features
def get_latest_features(features_df: pd.DataFrame) -> dict: """Extract the latest row of features as a flat dict (for signal engine).""" if features_df.empty: return {} last = features_df.iloc[-1] return {k: (round(float(v), 4) if pd.notna(v) else None) for k, v in last.items()}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970"""Volatility Features — Historical volatility, compression detection, regime."""import logging
import numpy as npimport pandas as pd
logger = logging.getLogger(__name__)
def compute_volatility_features(df: pd.DataFrame, ticker: str = "") -> pd.DataFrame: """ Compute volatility-related features.
Adds: - Historical volatility (10d, 20d, 60d) - Volatility ratio (short-term vs long-term) - Bollinger bandwidth compression detection - Average True Range % of price - Volatility regime classification """ if df.empty or len(df) < 60: logger.warning(f"{ticker}: Insufficient data for volatility features") return df
features = df.copy() log_returns = np.log(features["Close"] / features["Close"].shift(1))
# ── Historical Volatility (annualized) ── features["hv_10d"] = log_returns.rolling(10).std() * np.sqrt(252) * 100 features["hv_20d"] = log_returns.rolling(20).std() * np.sqrt(252) * 100 features["hv_60d"] = log_returns.rolling(60).std() * np.sqrt(252) * 100
# ── Volatility Ratio (short vs long — compression signal) ── features["vol_ratio_10_60"] = features["hv_10d"] / features["hv_60d"].replace(0, np.nan)
# ── Compression Detection ── # When short-term vol < 0.7x long-term vol, a breakout may be incoming features["vol_compressed"] = (features["vol_ratio_10_60"] < 0.7).astype(int) features["vol_expanding"] = (features["vol_ratio_10_60"] > 1.3).astype(int)
# ── True Range metrics ── high_low = features["High"] - features["Low"] high_pc = abs(features["High"] - features["Close"].shift(1)) low_pc = abs(features["Low"] - features["Close"].shift(1)) features["true_range"] = pd.concat([high_low, high_pc, low_pc], axis=1).max(axis=1) features["true_range_pct"] = (features["true_range"] / features["Close"]) * 100
# ── Daily Range as % (intraday volatility proxy) ── features["daily_range_pct"] = ((features["High"] - features["Low"]) / features["Close"]) * 100 features["avg_range_20d"] = features["daily_range_pct"].rolling(20).mean()
# ── Volatility Regime ── def _vol_regime(hv20): if pd.isna(hv20): return "unknown" if hv20 < 15: return "low" elif hv20 < 30: return "medium" elif hv20 < 50: return "high" else: return "extreme"
features["vol_regime"] = features["hv_20d"].apply(_vol_regime)
logger.info(f"{ticker}: Computed volatility features") return features1# Intelligence layer (adapted from portfolio_website)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Alert Classifier — Categorizes news into three concern tiers.Uses keyword rules first (zero tokens), LLM fallback for ambiguous items.
Tiers: 🔴 high — Black swan, major earnings miss, CEO departure, legal action ⚠️ medium — Analyst downgrade, rate changes, sector regulatory, >5% price move 🟢 low — Standard disclosures, minor analyst changes, general commentary"""import loggingimport re
logger = logging.getLogger(__name__)
# ── Rule-Based Classification (Zero Token Cost) ──
HIGH_KEYWORDS = [ r"\bfraud\b", r"\bscam\b", r"\bbankrupt", r"\bdefault\b", r"\bceo\s+(resign|depart|step|fired|ousted|quit)", r"\bcfo\s+(resign|depart|step|fired|ousted|quit)", r"\blegal\s+action", r"\blawsuit\b", r"\bsec\s+investigat", r"\bearnings\s+miss", r"\bprofit\s+warning", r"\bcrash\b", r"\bplunge\b", r"\btumble\b", r"\bhalt\s+trad", r"\bsuspend\b", r"\bblack\s*swan\b", r"\bwar\b", r"\bsanction\b", r"\brecall\b", r"\bdata\s+breach\b", r"\bcollaps\b", r"\bliquidat\b", r"\b(drop|fall|crash|sink|plummet|tank)\w*\s+\d{2,}%", # >10% drop]
MEDIUM_KEYWORDS = [ r"\bdowngrade\b", r"\bupgrade\b", r"\brate\s+(cut|hike|change|decision)", r"\binterest\s+rate", r"\brbi\b", r"\bfed\b.*\brate\b", r"\bregulat\w+\s+(inquiry|probe|action|scrutiny)", r"\btariff\b", r"\btrade\s+war\b", r"\bsector\s+(rotation|shift|sell)", r"\banalyst\b.*\b(target|cut|raise|lower)", r"\bmerger\b", r"\bacquisition\b", r"\btakeover\b", r"\bipo\b", r"\bdelisting\b", r"\b(rise|gain|surge|jump|rally)\w*\s+[5-9]%", # 5-9% move r"\b(drop|fall|decline)\w*\s+[5-9]%", r"\binflation\b", r"\bgdp\b", r"\bearnings\b.*\b(beat|miss|surprise)", r"\bdividend\s+(cut|slash|suspend)", r"\brestructur", r"\blayoff\b", r"\bjob\s+cut",]
# Compile patterns_HIGH_PATTERNS = [re.compile(p, re.IGNORECASE) for p in HIGH_KEYWORDS]_MEDIUM_PATTERNS = [re.compile(p, re.IGNORECASE) for p in MEDIUM_KEYWORDS]
def classify_concern_level( title: str, summary: str = "", sentiment: str = "neutral", confidence: float = 0.5, tickers_mentioned: list[str] | None = None,) -> str: """ Classify a news item into concern level: 'high', 'medium', or 'low'. Uses rule-based keyword matching first (zero token cost). """ text = f"{title} {summary}".lower()
# ── High Priority Check ── for pattern in _HIGH_PATTERNS: if pattern.search(text): logger.debug(f"HIGH match: {pattern.pattern} in '{title[:60]}'") return "high"
# ── Medium Priority Check ── for pattern in _MEDIUM_PATTERNS: if pattern.search(text): logger.debug(f"MEDIUM match: {pattern.pattern} in '{title[:60]}'") return "medium"
# ── Sentiment-Based Boost ── # Strong negative sentiment on portfolio holdings → upgrade to medium if (sentiment == "negative" and confidence >= 0.7 and tickers_mentioned and len(tickers_mentioned) > 0): return "medium"
# ── Default ── return "low"
def get_concern_label(level: str) -> dict: """Get display label and emoji for a concern level.""" labels = { "high": {"emoji": "🔴", "label": "IMMEDIATE", "color": "#f43f5e"}, "medium": {"emoji": "⚠️", "label": "MEDIUM CONCERN", "color": "#f59e0b"}, "low": {"emoji": "🟢", "label": "REGULAR", "color": "#34d399"}, } return labels.get(level, labels["low"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127"""News Intelligence Cache — Local JSON-based cache with URL dedup and TTL eviction.Stores processed news items to avoid re-analyzing the same headlines."""import hashlibimport jsonimport loggingimport timefrom pathlib import Pathfrom threading import Lock
logger = logging.getLogger(__name__)
CACHE_PATH = Path(__file__).parent.parent.parent / "data" / "news_cache.json"MAX_ITEMS = 500TTL_SECONDS = 24 * 60 * 60 # 24 hours
class NewsCache: """Thread-safe local JSON cache for processed news intelligence."""
def __init__(self, path: Path = CACHE_PATH): self._path = path self._lock = Lock() self._data: dict = self._load()
def _load(self) -> dict: if self._path.exists(): try: with open(self._path, "r", encoding="utf-8") as f: return json.load(f) except (json.JSONDecodeError, IOError): logger.warning("Corrupted cache file, starting fresh") return {"items": {}, "last_refresh": None}
def _save(self): self._path.parent.mkdir(parents=True, exist_ok=True) with open(self._path, "w", encoding="utf-8") as f: json.dump(self._data, f, indent=2, ensure_ascii=False)
@staticmethod def _url_hash(url: str) -> str: return hashlib.sha256(url.encode()).hexdigest()[:16]
def has(self, url: str) -> bool: """Check if a URL has already been processed.""" h = self._url_hash(url) with self._lock: if h not in self._data["items"]: return False item = self._data["items"][h] # Check TTL if time.time() - item.get("cached_at", 0) > TTL_SECONDS: del self._data["items"][h] return False return True
def get(self, url: str) -> dict | None: """Get a cached item by URL.""" h = self._url_hash(url) with self._lock: return self._data["items"].get(h)
def put(self, url: str, item: dict): """Store a processed news item.""" h = self._url_hash(url) with self._lock: item["cached_at"] = time.time() item["url_hash"] = h self._data["items"][h] = item self._evict() self._save()
def put_batch(self, items: list[dict]): """Store multiple items at once (single write).""" with self._lock: now = time.time() for item in items: url = item.get("url", "") h = self._url_hash(url) item["cached_at"] = now item["url_hash"] = h self._data["items"][h] = item self._evict() self._data["last_refresh"] = now self._save()
def get_all(self, concern_level: str | None = None) -> list[dict]: """Get all cached items, optionally filtered by concern level.""" with self._lock: now = time.time() items = [] for item in self._data["items"].values(): if now - item.get("cached_at", 0) > TTL_SECONDS: continue if concern_level and item.get("concern_level") != concern_level: continue items.append(item) # Sort by published time (newest first) items.sort(key=lambda x: x.get("published", ""), reverse=True) return items
def get_stats(self) -> dict: """Get summary counts per concern level.""" all_items = self.get_all() counts = {"total": len(all_items), "high": 0, "medium": 0, "low": 0} for item in all_items: level = item.get("concern_level", "low") counts[level] = counts.get(level, 0) + 1 counts["last_refresh"] = self._data.get("last_refresh") return counts
def _evict(self): """Remove oldest items if cache exceeds MAX_ITEMS.""" items = self._data["items"] if len(items) <= MAX_ITEMS: return sorted_keys = sorted(items.keys(), key=lambda k: items[k].get("cached_at", 0)) to_remove = len(items) - MAX_ITEMS for key in sorted_keys[:to_remove]: del items[key]
def clear(self): """Clear all cached items.""" with self._lock: self._data = {"items": {}, "last_refresh": None} self._save()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250"""Multi-Source News Fetcher — Ingests financial news from RSS feeds and Finnhub API.Extracts portfolio-relevant tickers and fetches targeted news."""import jsonimport loggingimport osimport reimport timefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom pathlib import Path
import feedparserimport requests
logger = logging.getLogger(__name__)
PORTFOLIO_JSON = Path(__file__).parent.parent.parent / "data" / "portfolio_data.json"
# ── RSS Feed Sources ──RSS_FEEDS = [ { "name": "Reuters Business", "url": "https://feeds.reuters.com/reuters/businessNews", "category": "global", }, { "name": "Reuters Markets", "url": "https://feeds.reuters.com/reuters/companyNews", "category": "global", }, { "name": "Yahoo Finance", "url": "https://finance.yahoo.com/news/rssindex", "category": "global", }, { "name": "CNBC Top News", "url": "https://search.cnbc.com/rs/search/combinedcms/view.xml?partnerId=wrss01&id=100003114", "category": "global", }, { "name": "Moneycontrol Markets", "url": "https://www.moneycontrol.com/rss/marketreports.xml", "category": "india", }, { "name": "Moneycontrol Stocks", "url": "https://www.moneycontrol.com/rss/latestnews.xml", "category": "india", }, { "name": "Economic Times Markets", "url": "https://economictimes.indiatimes.com/markets/rssfeeds/1977021501.cms", "category": "india", },]
@dataclassclass NewsItem: """Normalized news item from any source.""" title: str summary: str = "" url: str = "" source: str = "" category: str = "" # global, india, us published: str = "" # ISO format tickers_mentioned: list[str] = field(default_factory=list)
def _extract_portfolio_tickers() -> dict[str, list[str]]: """ Extract ticker symbols and company names from portfolio_data.json. Returns dict mapping normalized name → list of search terms. """ if not PORTFOLIO_JSON.exists(): return {}
with open(PORTFOLIO_JSON, "r") as f: data = json.load(f)
tickers = {} for _key, asset_class in data.get("assets", {}).items(): for h in asset_class.get("holdings", []): name = h.get("name", "").strip() if not name or name in ("Physical Gold (22K)", "Gold ETF (IBKR)", "Cash (UAE — AED)", "Cash (India — INR)", "House (India)", "Land (India)", "Corporate Bond (Primary)", "Corporate Bond (Secondary)"): continue # Create search terms: ticker itself + cleaned company name search_terms = [name.upper()] # Clean common suffixes for better matching cleaned = re.sub(r'\b(LTD|LIMITED|CORP|INC|SERV|LT)\b', '', name, flags=re.IGNORECASE).strip() if cleaned and cleaned.upper() != name.upper(): search_terms.append(cleaned.upper()) tickers[name] = search_terms return tickers
def _parse_feed_date(entry) -> str: """Extract and normalize publication date from RSS entry.""" published = entry.get("published_parsed") or entry.get("updated_parsed") if published: try: dt = datetime(*published[:6], tzinfo=timezone.utc) return dt.isoformat() except (ValueError, TypeError): pass return datetime.now(timezone.utc).isoformat()
def _match_tickers(text: str, ticker_map: dict[str, list[str]]) -> list[str]: """Match portfolio tickers mentioned in a text string.""" text_upper = text.upper() matched = [] for name, search_terms in ticker_map.items(): for term in search_terms: if len(term) >= 3 and term in text_upper: matched.append(name) break return matched
def fetch_rss_news(max_age_hours: int = 48) -> list[NewsItem]: """Fetch news from all configured RSS feeds.""" items = [] cutoff = datetime.now(timezone.utc) - timedelta(hours=max_age_hours) ticker_map = _extract_portfolio_tickers()
for feed_cfg in RSS_FEEDS: try: feed = feedparser.parse(feed_cfg["url"]) for entry in feed.entries[:15]: # Max 15 per feed title = entry.get("title", "").strip() if not title: continue
summary = entry.get("summary", entry.get("description", "")) # Strip HTML tags from summary summary = re.sub(r"<[^>]+>", "", summary or "").strip()[:300]
published = _parse_feed_date(entry)
# Check age try: pub_dt = datetime.fromisoformat(published.replace("Z", "+00:00")) if pub_dt < cutoff: continue except (ValueError, TypeError): pass
# Match tickers combined_text = f"{title} {summary}" matched = _match_tickers(combined_text, ticker_map)
items.append(NewsItem( title=title, summary=summary, url=entry.get("link", ""), source=feed_cfg["name"], category=feed_cfg["category"], published=published, tickers_mentioned=matched, ))
except Exception as e: logger.warning(f"RSS fetch error for {feed_cfg['name']}: {e}")
logger.info(f"Fetched {len(items)} items from {len(RSS_FEEDS)} RSS feeds") return items
def fetch_finnhub_news(tickers: list[str] | None = None) -> list[NewsItem]: """ Fetch company-specific news from Finnhub API. Free tier: 60 calls/min. Only fetches for portfolio tickers. """ api_key = os.getenv("FINNHUB_API_KEY", "").strip() if not api_key: logger.debug("No FINNHUB_API_KEY set, skipping Finnhub news") return []
if not tickers: # Extract US tickers from portfolio (Finnhub is best for US) ticker_map = _extract_portfolio_tickers() # For Finnhub, only use short ticker-like names (typically US stocks) tickers = [name for name in ticker_map.keys() if len(name) <= 6 and name.isalpha()][:10] # Max 10 to respect rate limits
items = [] today = datetime.now().strftime("%Y-%m-%d") week_ago = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
for ticker in tickers: try: resp = requests.get( "https://finnhub.io/api/v1/company-news", params={"symbol": ticker, "from": week_ago, "to": today, "token": api_key}, timeout=10, ) if resp.status_code != 200: continue
for article in resp.json()[:5]: # Max 5 per ticker title = article.get("headline", "").strip() if not title: continue pub_ts = article.get("datetime", 0) published = datetime.fromtimestamp(pub_ts, tz=timezone.utc).isoformat() if pub_ts else ""
items.append(NewsItem( title=title, summary=article.get("summary", "")[:300], url=article.get("url", ""), source=f"Finnhub ({article.get('source', 'unknown')})", category="us", published=published, tickers_mentioned=[ticker], ))
time.sleep(0.2) # Rate limiting: stay well under 60/min
except Exception as e: logger.warning(f"Finnhub error for {ticker}: {e}")
logger.info(f"Fetched {len(items)} items from Finnhub for {len(tickers)} tickers") return items
def fetch_all_news() -> list[NewsItem]: """Fetch news from all configured sources.""" items = [] items.extend(fetch_rss_news()) items.extend(fetch_finnhub_news())
# Deduplicate by URL seen_urls = set() unique = [] for item in items: if item.url and item.url not in seen_urls: seen_urls.add(item.url) unique.append(item) elif not item.url: unique.append(item)
logger.info(f"Total unique news items: {len(unique)}") return unique123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Perplexity API Client — Thin async wrapper for deep financial research queries.Uses the Sonar model for fast, web-grounded responses."""import loggingimport os
import httpx
logger = logging.getLogger(__name__)
PERPLEXITY_BASE_URL = "https://api.perplexity.ai"DEFAULT_MODEL = "sonar"
RESEARCH_SYSTEM_PROMPT = """You are a financial research analyst. Provide concise, data-backed answers to investment and market questions. Focus on:- Current market data and trends- Specific numbers, dates, and percentages- Impact on the user's portfolio holdings- Actionable insights
Keep responses under 200 words. Use bullet points for clarity. Include source attribution where possible."""
async def research(query: str, context: str = "") -> str: """ Perform deep financial research via Perplexity API. Returns a structured research summary.
Args: query: The research question context: Optional context about user's portfolio """ api_key = os.getenv("PERPLEXITY_API_KEY", "").strip() if not api_key: return "Perplexity API key not configured. Unable to perform deep research."
messages = [ {"role": "system", "content": RESEARCH_SYSTEM_PROMPT}, ] if context: messages.append({"role": "user", "content": f"Context about my portfolio: {context}"}) messages.append({"role": "assistant", "content": "Understood. I'll factor in your portfolio context."})
messages.append({"role": "user", "content": query})
try: async with httpx.AsyncClient(timeout=30) as client: resp = await client.post( f"{PERPLEXITY_BASE_URL}/chat/completions", json={ "model": DEFAULT_MODEL, "messages": messages, "temperature": 0.1, "max_tokens": 1000, }, headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }, ) resp.raise_for_status() data = resp.json() content = data["choices"][0]["message"]["content"] logger.info(f"Perplexity research completed for: {query[:60]}...") return content
except httpx.HTTPStatusError as e: logger.error(f"Perplexity API error: {e.response.status_code} — {e.response.text[:200]}") return f"Research API error (status {e.response.status_code}). Please try again." except Exception as e: logger.error(f"Perplexity client error: {e}") return f"Unable to perform research: {str(e)}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Sentiment Analyzer — Batched target-level financial sentiment via OpenAI gpt-4o-mini.Processes headlines in a single API call for maximum token efficiency."""import jsonimport loggingimport os
from openai import OpenAI
logger = logging.getLogger(__name__)
SENTIMENT_SYSTEM_PROMPT = """You are a financial sentiment classifier. You will receive numbered headlines.Return a JSON object with key "results" containing an array. Each element must have these exact keys:- "idx": the headline number (integer)- "overall_sentiment": "positive", "negative", or "neutral"- "confidence": float 0.0 to 1.0- "targets": array of {"name": string, "sentiment": string} for specific companies mentioned- "impact_summary": one sentence, max 20 words, explaining financial impact
Distinguish target-level sentiment. Example:"Netflix dips despite Apple's surge" → Netflix=negative, Apple=positive
You MUST return exactly one result per headline, in order."""
SENTIMENT_USER_TEMPLATE = """Analyze these {count} financial headlines:
{headlines}
Return: {{"results": [{{"idx": 0, "overall_sentiment": "positive", "confidence": 0.8, "targets": [{{"name": "AAPL", "sentiment": "positive"}}], "impact_summary": "Apple gains on strong earnings"}}]}}"""
def analyze_sentiment_batch(headlines: list[dict]) -> list[dict]: """ Analyze sentiment for a batch of news items using OpenAI. Each item should have at least 'title' and optionally 'summary'. Returns list of sentiment results in same order as input. """ if not headlines: return []
api_key = os.getenv("OPENAI_API_KEY", "") if not api_key: logger.warning("No OPENAI_API_KEY set, returning neutral sentiment for all") return [_neutral("No API key") for _ in headlines]
model = os.getenv("OPENAI_MODEL", "gpt-4o-mini") client = OpenAI(api_key=api_key)
# Format headlines for the prompt formatted = "\n".join( f"[{i}] {item['title']}" + (f" — {item.get('summary', '')[:80]}" if item.get("summary") else "") for i, item in enumerate(headlines) )
try: response = client.chat.completions.create( model=model, messages=[ {"role": "system", "content": SENTIMENT_SYSTEM_PROMPT}, {"role": "user", "content": SENTIMENT_USER_TEMPLATE.format( count=len(headlines), headlines=formatted )}, ], temperature=0.1, max_tokens=max(1500, len(headlines) * 80), response_format={"type": "json_object"}, )
content = response.choices[0].message.content or "{}" logger.debug(f"Raw sentiment response: {content[:500]}")
raw = json.loads(content)
# Extract the results array from various possible wrapper keys results = [] if isinstance(raw, dict): for key in ("results", "headlines", "analysis", "data", "sentiments"): if key in raw and isinstance(raw[key], list): results = raw[key] break if not results: # Try first list value in the dict for v in raw.values(): if isinstance(v, list) and len(v) > 0: results = v break elif isinstance(raw, list): results = raw
# Normalize each result to ensure expected keys exist normalized = [] for r in results: if not isinstance(r, dict): continue normalized.append({ "overall_sentiment": r.get("overall_sentiment", r.get("sentiment", "neutral")), "confidence": float(r.get("confidence", 0.5)), "targets": r.get("targets", []), "impact_summary": r.get("impact_summary", r.get("summary", "")), })
# Pad if model returned fewer than expected while len(normalized) < len(headlines): normalized.append(_neutral("Model returned fewer results"))
tokens = response.usage.total_tokens if response.usage else "?" logger.info(f"Sentiment analyzed: {len(headlines)} headlines, " f"{len(results)} results parsed (tokens: {tokens})") return normalized[:len(headlines)]
except Exception as e: logger.error(f"Sentiment analysis error: {e}") return [_neutral(f"Error: {str(e)[:50]}") for _ in headlines]
def _neutral(reason: str = "") -> dict: return { "overall_sentiment": "neutral", "confidence": 0.3, "targets": [], "impact_summary": reason or "Unable to analyze", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127import loggingimport osfrom pathlib import Pathfrom fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import HTMLResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesimport uvicornfrom pydantic import BaseModel
# Import our quant engine modulesfrom backend.agents.scan_pipeline import run_full_scanfrom backend.agents.supervisor_agent import invoke_supervisorfrom backend.data.store import get_store
# Setup logginglogging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")logger = logging.getLogger(__name__)
# Initialize FastAPI Appapp = FastAPI(title="Swing Quant Engine API", version="2.0.0")
# CORSapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# PathsBASE_DIR = Path(__file__).parent.parentFRONTEND_DIR = BASE_DIR / "frontend"FRONTEND_DIR.mkdir(exist_ok=True)(FRONTEND_DIR / "css").mkdir(exist_ok=True)(FRONTEND_DIR / "js").mkdir(exist_ok=True)
# Mount static filesapp.mount("/css", StaticFiles(directory=str(FRONTEND_DIR / "css")), name="css")app.mount("/js", StaticFiles(directory=str(FRONTEND_DIR / "js")), name="js")
# ── In-memory cache for last scan results ──_last_scan_result: dict | None = None
class ChatRequest(BaseModel): query: str
class ScanRequest(BaseModel): market: str = "both" top_n: int = 10
@app.get("/", response_class=HTMLResponse)async def serve_index(): index_path = FRONTEND_DIR / "index.html" if index_path.exists(): return index_path.read_text() return "Frontend not built yet. Create frontend/index.html"
@app.get("/api/dashboard")async def get_dashboard_data(): """Get the latest saved signals and stats for the dashboard.""" global _last_scan_result store = get_store() history = store.get_scan_history(limit=1) if not history: return JSONResponse({"status": "no_data", "signals": [], "stats": {}, "pipeline_stages": [], "regimes": {}}) signals = store.get_active_signals(limit=10) # Use cached pipeline stages from last scan if available pipeline_stages = [] regimes = {} stats = { "universe_size": history[0]["universe_size"], "raw_signals": history[0]["signals_found"], "final_signals": len(signals), } if _last_scan_result: pipeline_stages = _last_scan_result.get("pipeline_stages", []) regimes = _last_scan_result.get("regimes", {}) stats = _last_scan_result.get("stats", stats) return { "status": "success", "last_scan_date": history[0]["created_at"] * 1000, "stats": stats, "signals": signals, "pipeline_stages": pipeline_stages, "regimes": regimes, }
@app.post("/api/scan")async def trigger_scan(req: ScanRequest): """Trigger a new full scan with step-by-step pipeline tracking.""" global _last_scan_result logger.info(f"Triggering manual scan for market: {req.market}") results = run_full_scan(market=req.market, top_n=req.top_n) if "error" in results and not results.get("pipeline_stages"): return JSONResponse({"status": "error", "message": results["error"]}, status_code=500) # Cache the full result for dashboard _last_scan_result = results return { "status": "success", "stats": results.get("stats"), "pipeline_stages": results.get("pipeline_stages", []), "regimes": results.get("regimes", {}), "signals": results.get("signals", []), }
@app.post("/api/chat")async def chat_with_supervisor(req: ChatRequest): """Chat with the LangGraph supervisor.""" try: response = invoke_supervisor(req.query) return {"status": "success", "response": response} except Exception as e: logger.error(f"Chat error: {e}") return JSONResponse({"status": "error", "message": str(e)}, status_code=500)
if __name__ == "__main__": uvicorn.run("backend.server:app", host="0.0.0.0", port=8001, reload=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145"""Swing Quant Engine — Central ConfigurationAll tunable parameters, universe definitions, and thresholds."""import osfrom pathlib import Path
from dotenv import load_dotenv
# ── Paths ──BASE_DIR = Path(__file__).parentDATA_DIR = BASE_DIR / "data"PARQUET_DIR = DATA_DIR / "parquet"DB_PATH = DATA_DIR / "quant.db"
# Ensure dirs existDATA_DIR.mkdir(exist_ok=True)PARQUET_DIR.mkdir(exist_ok=True)
# Load env from portfolio_website if local .env doesn't exist_local_env = BASE_DIR / ".env"_portfolio_env = BASE_DIR.parent / "portfolio_website" / ".env"if _local_env.exists(): load_dotenv(_local_env)elif _portfolio_env.exists(): load_dotenv(_portfolio_env)
# ── API Keys ──OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")PERPLEXITY_API_KEY = os.getenv("PERPLEXITY_API_KEY", "")FINNHUB_API_KEY = os.getenv("FINNHUB_API_KEY", "")
# ── Stock Universe ──# Indian blue-chips (NSE) — top Nifty 50 + select mid-capsINDIA_UNIVERSE = [ "RELIANCE.NS", "TCS.NS", "HDFCBANK.NS", "INFY.NS", "ICICIBANK.NS", "HINDUNILVR.NS", "BHARTIARTL.NS", "SBIN.NS", "ITC.NS", "KOTAKBANK.NS", "LT.NS", "AXISBANK.NS", "BAJFINANCE.NS", "ASIANPAINT.NS", "MARUTI.NS", "HCLTECH.NS", "WIPRO.NS", "SUNPHARMA.NS", "TITAN.NS", "ULTRACEMCO.NS", "ONGC.NS", "NTPC.NS", "POWERGRID.NS", "TATAMOTORS.NS", "TATASTEEL.NS", "ADANIENT.NS", "ADANIPORTS.NS", "COALINDIA.NS", "JSWSTEEL.NS", "M&M.NS", "BAJAJ-AUTO.NS", "TECHM.NS", "HEROMOTOCO.NS", "DRREDDY.NS", "CIPLA.NS", "DIVISLAB.NS", "APOLLOHOSP.NS", "EICHERMOT.NS", "BPCL.NS", "GRASIM.NS", "TATACONSUM.NS", "NESTLEIND.NS", "BRITANNIA.NS", "INDUSINDBK.NS", "HINDALCO.NS", "SBILIFE.NS", "HDFCLIFE.NS", "BAJAJFINSV.NS", "SHREECEM.NS", "PIDILITIND.NS",]
# US blue-chips — S&P 100 subsetUS_UNIVERSE = [ "AAPL", "MSFT", "GOOGL", "AMZN", "NVDA", "META", "TSLA", "BRK-B", "UNH", "JNJ", "V", "XOM", "JPM", "PG", "MA", "HD", "CVX", "MRK", "ABBV", "LLY", "PEP", "KO", "COST", "AVGO", "WMT", "MCD", "CSCO", "ACN", "TMO", "ABT", "DHR", "NEE", "LIN", "PM", "TXN", "UNP", "RTX", "HON", "LOW", "AMGN", "COP", "QCOM", "ORCL", "GS", "BAC", "CAT", "SBUX", "AXP", "PFE", "AMD",]
# Combined default universeDEFAULT_UNIVERSE = INDIA_UNIVERSE + US_UNIVERSE
# ── Technical Signal Thresholds ──SIGNAL_PARAMS = { # RSI "rsi_oversold": 30, "rsi_overbought": 75, "rsi_bullish_zone": (45, 76), # Tightened momentum sweet spot
# MACD "macd_fast": 12, "macd_slow": 26, "macd_signal": 9,
# Bollinger Bands "bb_period": 20, "bb_std": 2.0,
# Moving Averages "sma_short": 20, "sma_medium": 50, "sma_long": 200, "ema_fast": 9, "ema_slow": 21,
# Volume "volume_spike_threshold": 2.0, # Increased to 2.0x avg volume for higher conviction "volume_sma_period": 20,
# ADX (trend strength) "adx_trending": 25, # ADX > 25 = trending market
# ATR "atr_period": 14,
# Breakout "breakout_lookback": 20, # days to look for resistance "breakout_volume_confirm": 1.3, # min volume multiplier for confirmation}
# ── Risk Parameters ──RISK_PARAMS = { "max_position_pct": 5.0, # Max 5% of portfolio in one position "max_sector_pct": 15.0, # Reduced to 15% for better diversification "max_drawdown_pct": 15.0, # Kill switch at 15% portfolio drawdown "min_liquidity_inr": 5_00_00_000, # ₹5Cr daily volume for India "min_liquidity_usd": 10_000_000, # $10M daily volume for US "max_atr_pct": 5.0, # Skip stocks with ATR% > 5% "max_correlation": 0.85, # Reject if corr > 0.85 with existing "kelly_fraction": 0.25, # Use 25% of Kelly optimal (conservative)}
# ── Alpha Scoring Weights ──ALPHA_WEIGHTS = { "momentum": 0.35, "volume_breakout": 0.20, "sentiment": 0.20, "regime_fit": 0.15, "fundamental": 0.10,}
# ── Scan Schedule ──SCAN_INTERVAL_HOURS = 4 # Re-scan every 4 hours during market hours
# ── Market Hours (for scheduling) ──MARKET_HOURS = { "india": {"open": "09:15", "close": "15:30", "tz": "Asia/Kolkata"}, "us": {"open": "09:30", "close": "16:00", "tz": "America/New_York"},}
# ── Backtest Defaults ──BACKTEST_PARAMS = { "in_sample_months": 12,#6 "out_sample_months": 3,#1 "commission_india_pct": 0.1, "commission_us_pct": 0.05, "slippage_pct": 0.05, "initial_capital": 10_00_000, # ₹10L or $10K equivalent}
# ── Logging ──import logging
LOG_FORMAT = "%(asctime)s [%(levelname)s] %(name)s: %(message)s"logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap');
:root { --bg-primary: #0a0a0f; --bg-secondary: #12121c; --bg-card: rgba(18,18,28,0.85); --bg-card-hover: rgba(24,24,36,0.95); --accent-gold: #d4a853; --accent-emerald: #34d399; --accent-rose: #f43f5e; --accent-blue: #3b82f6; --accent-purple: #a78bfa; --accent-cyan: #22d3ee; --text-primary: #f0f0f5; --text-secondary: #a1a1aa; --text-muted: #6b7280; --glass-border: rgba(255,255,255,0.08); --glass-border-hover: rgba(255,255,255,0.15); --glass-blur: 16px; --radius-sm: 8px; --radius-md: 14px; --radius-lg: 20px; --shadow-glow: 0 0 40px rgba(212,168,83,0.15); --shadow-card: 0 8px 32px rgba(0,0,0,0.3); --transition: 0.3s cubic-bezier(0.4,0,0.2,1); --font-body: 'Inter', sans-serif; --font-mono: 'JetBrains Mono', monospace;}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: var(--font-body); background: var(--bg-primary); color: var(--text-primary); line-height: 1.6; min-height: 100vh; overflow-x: hidden;}
body::before { content: ''; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: radial-gradient(ellipse 800px 600px at 10% 10%, rgba(99,102,241,0.08), transparent), radial-gradient(ellipse 600px 500px at 80% 20%, rgba(212,168,83,0.06), transparent), radial-gradient(ellipse 500px 400px at 50% 80%, rgba(52,211,153,0.04), transparent); pointer-events: none; z-index: 0;}
.dashboard { position: relative; z-index: 1; max-width: 1500px; margin: 0 auto; padding: 24px 28px 80px; }
/* ── Animations ── */@keyframes fadeSlideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); }}@keyframes pulse-glow { 0%, 100% { box-shadow: 0 0 8px rgba(212,168,83,0.2); } 50% { box-shadow: 0 0 20px rgba(212,168,83,0.4); }}@keyframes countUp { from { opacity: 0; transform: scale(0.5); } to { opacity: 1; transform: scale(1); } }@keyframes shimmer { 0% { background-position: -200% 0; } 100% { background-position: 200% 0; }}.animate-in { animation: fadeSlideUp 0.5s ease-out both; }
/* ── Header ── */.header { display: flex; justify-content: space-between; align-items: center; padding: 16px 0 28px; border-bottom: 1px solid var(--glass-border); margin-bottom: 28px;}.header-title { font-size: 1.6rem; font-weight: 700; letter-spacing: -0.02em; }.header-title span { color: var(--accent-gold); }.header-right { display: flex; align-items: center; gap: 16px; }.last-updated { font-size: 0.8rem; color: var(--text-muted); }.btn-scan { padding: 10px 20px; background: rgba(212,168,83,0.1); border: 1px solid rgba(212,168,83,0.3); color: var(--accent-gold); border-radius: var(--radius-sm); font-weight: 600; cursor: pointer; transition: var(--transition); display: flex; align-items: center; gap: 8px; font-size: 0.85rem;}.btn-scan:hover { background: rgba(212,168,83,0.2); transform: translateY(-1px); box-shadow: 0 4px 16px rgba(212,168,83,0.2); }.btn-scan:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }
/* ── Pipeline Funnel ── */.pipeline-container { margin-bottom: 32px;}.pipeline-header { display: flex; align-items: center; gap: 10px; font-size: 1.1rem; font-weight: 700; margin-bottom: 16px;}.pipeline-header::after { content: ''; flex: 1; height: 1px; background: var(--glass-border); }
.pipeline-funnel { display: flex; align-items: stretch; gap: 0; position: relative; background: var(--bg-card); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); padding: 20px 8px; overflow-x: auto; backdrop-filter: blur(var(--glass-blur));}
.pipeline-stage { flex: 1; min-width: 110px; display: flex; flex-direction: column; align-items: center; text-align: center; position: relative; padding: 8px 6px; cursor: pointer; transition: var(--transition); border-radius: var(--radius-sm);}.pipeline-stage:hover { background: rgba(255,255,255,0.03); }.pipeline-stage.active { background: rgba(212,168,83,0.08); }
.stage-icon { width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1rem; margin-bottom: 8px; transition: var(--transition); border: 2px solid var(--glass-border); background: var(--bg-secondary);}.pipeline-stage.completed .stage-icon { border-color: var(--accent-emerald); color: var(--accent-emerald); }.pipeline-stage.active .stage-icon { border-color: var(--accent-gold); color: var(--accent-gold); animation: pulse-glow 2s infinite; }.pipeline-stage.empty .stage-icon { border-color: var(--accent-rose); color: var(--accent-rose); }
.stage-label { font-size: 0.65rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 4px; font-weight: 600; }.stage-count { font-family: var(--font-mono); font-size: 1.2rem; font-weight: 700; animation: countUp 0.4s ease-out both;}.pipeline-stage.completed .stage-count { color: var(--accent-emerald); }.pipeline-stage.active .stage-count { color: var(--accent-gold); }.pipeline-stage.empty .stage-count { color: var(--accent-rose); }
.stage-arrow { display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 0.8rem; padding: 0 2px; flex-shrink: 0;}.stage-time { font-size: 0.6rem; color: var(--text-muted); margin-top: 2px; font-family: var(--font-mono); }
/* ── Pipeline Details Panel ── */.pipeline-details { background: var(--bg-card); border: 1px solid var(--glass-border); border-radius: var(--radius-md); padding: 20px; margin-top: 12px; display: none; animation: fadeSlideUp 0.3s ease-out; backdrop-filter: blur(var(--glass-blur));}.pipeline-details.visible { display: block; }.details-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }.details-title { font-weight: 700; font-size: 1rem; display: flex; align-items: center; gap: 8px; }.details-stats { display: flex; gap: 16px; font-size: 0.8rem; color: var(--text-secondary); }.details-stats .stat { display: flex; align-items: center; gap: 4px; }.details-stats .stat i { font-size: 0.7rem; }.details-body { font-size: 0.85rem; color: var(--text-secondary); line-height: 1.6; margin-bottom: 12px; }.details-tickers { display: flex; flex-wrap: wrap; gap: 6px; }.details-ticker-tag { padding: 3px 8px; border-radius: 4px; font-size: 0.7rem; font-family: var(--font-mono); background: rgba(255,255,255,0.05); color: var(--text-secondary); font-weight: 500;}.details-ticker-tag.passed { background: rgba(52,211,153,0.1); color: var(--accent-emerald); border: 1px solid rgba(52,211,153,0.2); }.details-ticker-tag.rejected { background: rgba(244,63,94,0.1); color: var(--accent-rose); border: 1px solid rgba(244,63,94,0.2); text-decoration: line-through; }
.rejected-list { margin-top: 12px; }.rejected-item { display: flex; align-items: flex-start; gap: 8px; padding: 6px 0; font-size: 0.78rem; border-bottom: 1px solid rgba(255,255,255,0.03);}.rejected-item:last-child { border-bottom: none; }.rejected-item .ticker { font-family: var(--font-mono); color: var(--accent-rose); font-weight: 600; min-width: 80px; }.rejected-item .reason { color: var(--text-muted); }
/* ── Stats Row ── */.stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 14px; margin-bottom: 28px; }.stat-card { background: var(--bg-card); border: 1px solid var(--glass-border); border-radius: var(--radius-md); padding: 16px 18px; backdrop-filter: blur(var(--glass-blur)); transition: var(--transition);}.stat-card:hover { border-color: var(--glass-border-hover); transform: translateY(-2px); }.stat-label { font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.1em; margin-bottom: 6px; }.stat-value { font-family: var(--font-mono); font-size: 1.4rem; font-weight: 700; }.stat-value.gold { color: var(--accent-gold); }.stat-value.green { color: var(--accent-emerald); }.stat-value.blue { color: var(--accent-blue); }
/* ── Regime Banner ── */.regime-banner { display: flex; gap: 16px; margin-bottom: 28px; flex-wrap: wrap;}.regime-card { flex: 1; min-width: 280px; background: var(--bg-card); border: 1px solid var(--glass-border); border-radius: var(--radius-md); padding: 16px 20px; backdrop-filter: blur(var(--glass-blur));}.regime-card-title { font-size: 0.7rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.1em; margin-bottom: 8px; }.regime-badge { display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600;}.regime-badge.bullish { background: rgba(52,211,153,0.15); color: var(--accent-emerald); border: 1px solid rgba(52,211,153,0.3); }.regime-badge.bearish { background: rgba(244,63,94,0.15); color: var(--accent-rose); border: 1px solid rgba(244,63,94,0.3); }.regime-badge.neutral { background: rgba(161,161,170,0.15); color: var(--text-secondary); border: 1px solid rgba(161,161,170,0.3); }.regime-info { font-size: 0.8rem; color: var(--text-secondary); margin-top: 8px; line-height: 1.5; }
/* ── Signals Table ── */.section-title { font-size: 1.1rem; font-weight: 700; margin-bottom: 16px; display: flex; align-items: center; gap: 10px; }.section-title::after { content: ''; flex: 1; height: 1px; background: var(--glass-border); }
.table-container { background: var(--bg-card); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); backdrop-filter: blur(var(--glass-blur)); overflow-x: auto; margin-bottom: 32px;}.data-table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }.data-table th { text-align: left; padding: 14px 16px; color: var(--text-muted); font-weight: 600; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.08em; border-bottom: 1px solid var(--glass-border); position: sticky; top: 0; background: var(--bg-secondary);}.data-table td { padding: 14px 16px; border-bottom: 1px solid rgba(255,255,255,0.03); vertical-align: top; }.data-table tr { cursor: pointer; transition: var(--transition); }.data-table tr:hover td { background: rgba(255,255,255,0.02); }.data-table tr.expanded td { background: rgba(212,168,83,0.03); }.mono { font-family: var(--font-mono); }.positive { color: var(--accent-emerald); }.negative { color: var(--accent-rose); }
.ticker-cell { display: flex; flex-direction: column; gap: 2px; }.ticker-name { font-weight: 700; font-size: 0.95rem; }.ticker-sector { font-size: 0.65rem; color: var(--text-muted); }
/* ── Badges ── */.badge { padding: 4px 8px; border-radius: 6px; font-size: 0.7rem; font-weight: 600; background: rgba(255,255,255,0.05); color: var(--text-secondary); white-space: nowrap;}.badge.gold { background: rgba(212,168,83,0.15); color: var(--accent-gold); border: 1px solid rgba(212,168,83,0.3); }.badge.green { background: rgba(52,211,153,0.15); color: var(--accent-emerald); border: 1px solid rgba(52,211,153,0.2); }.badge.blue { background: rgba(59,130,246,0.15); color: var(--accent-blue); border: 1px solid rgba(59,130,246,0.2); }
/* ── Narrative / Reason Detail Panel ── */.narrative-row td { padding: 0 !important; border-bottom: 1px solid rgba(255,255,255,0.05) !important;}.narrative-container { padding: 16px 24px 20px; background: rgba(0,0,0,0.2); border-left: 3px solid var(--accent-gold);}.narrative-section { margin-bottom: 12px; }.narrative-section:last-child { margin-bottom: 0; }.narrative-heading { font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: var(--accent-gold); margin-bottom: 6px; display: flex; align-items: center; gap: 6px;}.narrative-heading i { font-size: 0.7rem; }.narrative-body { font-size: 0.8rem; color: var(--text-secondary); line-height: 1.7; }.narrative-metric { font-family: var(--font-mono); font-weight: 600; color: var(--text-primary); }.narrative-metric.gold { color: var(--accent-gold); }.narrative-tag { display: inline-block; padding: 1px 6px; border-radius: 4px; font-size: 0.7rem; background: rgba(255,255,255,0.05); font-weight: 500;}.narrative-source { font-size: 0.7rem; color: var(--text-muted); }.narrative-sentiment { font-weight: 600; }.narrative-sentiment.positive { color: var(--accent-emerald); }.narrative-sentiment.negative { color: var(--accent-rose); }.narrative-sentiment.neutral { color: var(--text-secondary); }
/* ── Expand indicator ── */.expand-indicator { color: var(--text-muted); font-size: 0.8rem; transition: var(--transition); }.expanded .expand-indicator { transform: rotate(90deg); color: var(--accent-gold); }
/* ── Scan Progress Overlay ── */.scan-progress { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(10,10,15,0.85); z-index: 9998; backdrop-filter: blur(8px); justify-content: center; align-items: center;}.scan-progress.active { display: flex; }.progress-card { background: var(--bg-secondary); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); padding: 40px 48px; text-align: center; max-width: 420px; width: 90%; box-shadow: 0 16px 64px rgba(0,0,0,0.5);}.progress-spinner { font-size: 2.5rem; color: var(--accent-gold); margin-bottom: 16px; }.progress-title { font-size: 1.2rem; font-weight: 700; margin-bottom: 8px; }.progress-step { font-size: 0.85rem; color: var(--text-secondary); }.progress-bar-track { width: 100%; height: 4px; background: rgba(255,255,255,0.05); border-radius: 2px; margin-top: 16px; overflow: hidden;}.progress-bar-fill { height: 100%; background: linear-gradient(90deg, var(--accent-gold), var(--accent-emerald)); border-radius: 2px; width: 0%; transition: width 0.5s ease; background-size: 200% 100%; animation: shimmer 2s linear infinite;}
/* ── Chat Panel ── */.chat-fab { position: fixed; bottom: 28px; right: 28px; width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, var(--accent-gold), #b8892a); border: none; color: var(--bg-primary); cursor: pointer; box-shadow: 0 4px 24px rgba(212,168,83,0.4); z-index: 9999; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; transition: all 0.3s ease;}.chat-fab:hover { transform: scale(1.1); }
.chat-panel { position: fixed; bottom: 28px; right: 28px; width: 420px; height: 600px; background: var(--bg-secondary); border: 1px solid var(--glass-border); border-radius: var(--radius-lg); box-shadow: 0 16px 64px rgba(0,0,0,0.5); z-index: 10000; display: flex; flex-direction: column; overflow: hidden; transform: scale(0.5) translateY(100px); opacity: 0; pointer-events: none; transition: all 0.35s cubic-bezier(0.34, 1.56, 0.64, 1); transform-origin: bottom right;}.chat-panel.open { transform: scale(1) translateY(0); opacity: 1; pointer-events: all; }
.chat-header { display: flex; justify-content: space-between; align-items: center; padding: 16px 18px; border-bottom: 1px solid var(--glass-border); background: rgba(212,168,83,0.05);}.chat-title { font-weight: 700; color: var(--text-primary); }.chat-close { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1.2rem; }
.chat-messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; }.chat-msg { display: flex; gap: 8px; max-width: 90%; }.chat-msg-user { align-self: flex-end; flex-direction: row-reverse; }.chat-msg-bot { align-self: flex-start; }.chat-bubble { padding: 12px 16px; border-radius: 14px; font-size: 0.85rem; line-height: 1.5; }.chat-msg-user .chat-bubble { background: linear-gradient(135deg, var(--accent-gold), #b8892a); color: var(--bg-primary); border-bottom-right-radius: 4px; font-weight: 500; }.chat-msg-bot .chat-bubble { background: rgba(255,255,255,0.05); border: 1px solid var(--glass-border); color: var(--text-primary); border-bottom-left-radius: 4px; }
.chat-input-area { padding: 16px; border-top: 1px solid var(--glass-border); display: flex; gap: 8px; }.chat-input { flex: 1; padding: 12px 16px; background: var(--bg-card); border: 1px solid var(--glass-border); border-radius: var(--radius-md); color: var(--text-primary); font-family: var(--font-body); outline: none; transition: var(--transition);}.chat-input:focus { border-color: var(--accent-gold); }.chat-send { background: var(--accent-gold); color: var(--bg-primary); border: none; border-radius: var(--radius-md); padding: 0 16px; cursor: pointer; font-weight: 700; transition: var(--transition);}.chat-send:hover { background: #e9c06a; }
/* ── Scrollbar ── */::-webkit-scrollbar { width: 6px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 3px; }::-webkit-scrollbar-thumb:hover { background: rgba(255,255,255,0.2); }
/* ── Responsive ── */@media (max-width: 768px) { .dashboard { padding: 16px 12px 80px; } .header { flex-direction: column; gap: 12px; align-items: flex-start; } .pipeline-funnel { padding: 12px 4px; } .pipeline-stage { min-width: 80px; } .regime-banner { flex-direction: column; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Swing Quant Engine — Multi-Agent Trading Intelligence</title> <meta name="description" content="AI-powered multi-agent swing trading pipeline with step-by-step signal filtering, fundamental analysis, and sentiment scoring."> <link rel="stylesheet" href="/css/styles.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"></head><body>
<div class="dashboard"> <!-- Header --> <header class="header"> <div class="header-title">Swing Quant <span>Engine</span></div> <div class="header-right"> <div class="last-updated" id="lastUpdated">Last Scan: Never</div> <button class="btn-scan" id="btnScanUS"><i class="fa-solid fa-radar"></i> Scan US</button> <button class="btn-scan" id="btnScanIN"><i class="fa-solid fa-radar"></i> Scan India</button> </div> </header>
<!-- Pipeline Funnel --> <div class="pipeline-container animate-in" style="animation-delay: 0.1s;" id="pipelineContainer"> <div class="pipeline-header"> <i class="fa-solid fa-filter"></i> Scan Pipeline </div> <div class="pipeline-funnel" id="pipelineFunnel"> <div class="pipeline-stage" style="text-align:center; padding:40px; color:var(--text-muted); width:100%;"> <i class="fa-solid fa-play" style="margin-right:8px;"></i> Run a scan to see the filtering pipeline </div> </div> <div class="pipeline-details" id="pipelineDetails"></div> </div>
<!-- Regime Banner --> <div class="regime-banner animate-in" style="animation-delay: 0.15s; display:none;" id="regimeBanner"></div>
<!-- Stats Row --> <div class="stats-row animate-in" style="animation-delay: 0.2s;" id="statsRow"> <div class="stat-card"> <div class="stat-label">Universe</div> <div class="stat-value" id="statUniverse">0</div> </div> <div class="stat-card"> <div class="stat-label">Raw Signals</div> <div class="stat-value blue" id="statRaw">0</div> </div> <div class="stat-card"> <div class="stat-label">After Filters</div> <div class="stat-value green" id="statFiltered">0</div> </div> <div class="stat-card"> <div class="stat-label">Final Trades</div> <div class="stat-value gold" id="statFinal">0</div> </div> <div class="stat-card"> <div class="stat-label">Scan Duration</div> <div class="stat-value" id="statDuration">-</div> </div> </div>
<!-- Top Ranked Opportunities --> <div class="section-title animate-in" style="animation-delay: 0.25s;"> <i class="fa-solid fa-trophy"></i> Top Ranked Opportunities </div>
<div class="table-container animate-in" style="animation-delay: 0.3s;"> <table class="data-table" id="signalsTable"> <thead> <tr> <th></th> <th>Ticker</th> <th>Signal</th> <th>Alpha</th> <th>Entry</th> <th>Target 1</th> <th>Target 2</th> <th>Target 3</th> <th>Stop Loss</th> <th>R:R</th> <th>Qty</th> <th>Sentiment / Summary</th> </tr> </thead> <tbody id="signalsTableBody"> <tr><td colspan="12" style="text-align:center; padding:40px; color:var(--text-muted)">No recent scan data. Run a scan to discover opportunities.</td></tr> </tbody> </table> </div> </div>
<!-- Scan Progress Overlay --> <div class="scan-progress" id="scanProgress"> <div class="progress-card"> <div class="progress-spinner"><i class="fa-solid fa-spinner fa-spin"></i></div> <div class="progress-title">Running Pipeline...</div> <div class="progress-step" id="progressStep">Initializing scan engine</div> <div class="progress-bar-track"><div class="progress-bar-fill" id="progressBar"></div></div> </div> </div>
<!-- Chat FAB --> <button class="chat-fab" id="chatFab"><i class="fa-solid fa-message"></i></button>
<!-- Chat Panel --> <div class="chat-panel" id="chatPanel"> <div class="chat-header"> <div class="chat-title"><i class="fa-solid fa-robot"></i> Quant Supervisor</div> <button class="chat-close" id="chatClose"><i class="fa-solid fa-times"></i></button> </div> <div class="chat-messages" id="chatMessages"> <div class="chat-msg chat-msg-bot"> <div class="chat-bubble"> <strong>System Online.</strong><br> I have access to Signal, Regime, and News specialists. How can I help you today? </div> </div> </div> <div class="chat-input-area"> <input type="text" class="chat-input" id="chatInput" placeholder="Ask about markets, run a scan, etc..."> <button class="chat-send" id="chatSend"><i class="fa-solid fa-paper-plane"></i></button> </div> </div>
<script src="/js/app.js"></script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331document.addEventListener('DOMContentLoaded', () => { // --- Elements --- const btnScanUS = document.getElementById('btnScanUS'); const btnScanIN = document.getElementById('btnScanIN'); const signalsTableBody = document.getElementById('signalsTableBody'); const lastUpdated = document.getElementById('lastUpdated'); const pipelineFunnel = document.getElementById('pipelineFunnel'); const pipelineDetails = document.getElementById('pipelineDetails'); const regimeBanner = document.getElementById('regimeBanner'); const scanProgress = document.getElementById('scanProgress'); const progressStep = document.getElementById('progressStep'); const progressBar = document.getElementById('progressBar');
// Stats const statUniverse = document.getElementById('statUniverse'); const statRaw = document.getElementById('statRaw'); const statFiltered = document.getElementById('statFiltered'); const statFinal = document.getElementById('statFinal'); const statDuration = document.getElementById('statDuration');
// Chat const chatFab = document.getElementById('chatFab'); const chatPanel = document.getElementById('chatPanel'); const chatClose = document.getElementById('chatClose'); const chatInput = document.getElementById('chatInput'); const chatSend = document.getElementById('chatSend'); const chatMessages = document.getElementById('chatMessages');
const API_BASE = '/api'; const fmt = (n) => n != null ? Number(n).toLocaleString() : '0'; const fmtPrice = (n) => n ? parseFloat(n).toFixed(2) : '-';
// --- Pipeline Rendering --- const renderPipeline = (stages) => { if (!stages || stages.length === 0) { pipelineFunnel.innerHTML = `<div style="text-align:center; padding:40px; color:var(--text-muted); width:100%;"> <i class="fa-solid fa-play" style="margin-right:8px;"></i> Run a scan to see the filtering pipeline </div>`; return; }
let html = ''; stages.forEach((stage, i) => { const stateClass = stage.count_out === 0 ? 'empty' : (i === stages.length - 1 ? 'active' : 'completed'); const timeStr = stage.duration_ms > 0 ? `${(stage.duration_ms / 1000).toFixed(1)}s` : '';
html += ` <div class="pipeline-stage ${stateClass}" data-stage-idx="${i}" onclick="window._showStageDetails(${i})"> <div class="stage-icon"><i class="fa-solid ${stage.icon}"></i></div> <div class="stage-label">${stage.label}</div> <div class="stage-count" style="animation-delay:${i * 0.08}s">${stage.count_out}</div> ${timeStr ? `<div class="stage-time">${timeStr}</div>` : ''} </div>`;
if (i < stages.length - 1) { const dropPct = stage.count_in > 0 ? Math.round((1 - stage.count_out / stage.count_in) * 100) : 0; html += `<div class="stage-arrow"><i class="fa-solid fa-chevron-right"></i></div>`; } });
pipelineFunnel.innerHTML = html; };
// Stage details panel let _pipelineStages = []; window._showStageDetails = (idx) => { const stage = _pipelineStages[idx]; if (!stage) return;
// Toggle active class document.querySelectorAll('.pipeline-stage').forEach((el, i) => { el.classList.toggle('active', i === idx); });
const dropCount = stage.count_in - stage.count_out; const dropPct = stage.count_in > 0 ? ((dropCount / stage.count_in) * 100).toFixed(1) : 0;
let tickerHtml = ''; if (stage.tickers && stage.tickers.length > 0) { tickerHtml = '<div class="details-tickers">' + stage.tickers.slice(0, 30).map(t => `<span class="details-ticker-tag passed">${t}</span>`).join('') + (stage.tickers.length > 30 ? `<span class="details-ticker-tag">+${stage.tickers.length - 30} more</span>` : '') + '</div>'; }
let rejectedHtml = ''; if (stage.rejected && stage.rejected.length > 0) { rejectedHtml = '<div class="rejected-list"><div style="font-size:0.75rem;color:var(--accent-rose);font-weight:600;margin-bottom:6px;"><i class="fa-solid fa-xmark"></i> Rejected:</div>' + stage.rejected.slice(0, 10).map(r => `<div class="rejected-item"><span class="ticker">${r.ticker}</span><span class="reason">${r.reason || r.signal_type || ''}</span></div>` ).join('') + (stage.rejected.length > 10 ? `<div style="font-size:0.7rem;color:var(--text-muted);padding:4px 0;">+${stage.rejected.length - 10} more</div>` : '') + '</div>'; }
pipelineDetails.innerHTML = ` <div class="details-header"> <div class="details-title"><i class="fa-solid ${stage.icon}"></i> ${stage.label}</div> <div class="details-stats"> <div class="stat"><i class="fa-solid fa-arrow-right-to-bracket"></i> In: ${stage.count_in}</div> <div class="stat"><i class="fa-solid fa-arrow-right-from-bracket"></i> Out: ${stage.count_out}</div> ${dropCount > 0 ? `<div class="stat" style="color:var(--accent-rose)"><i class="fa-solid fa-filter-circle-xmark"></i> Dropped: ${dropCount} (${dropPct}%)</div>` : ''} ${stage.duration_ms > 0 ? `<div class="stat"><i class="fa-solid fa-clock"></i> ${(stage.duration_ms / 1000).toFixed(1)}s</div>` : ''} </div> </div> <div class="details-body">${stage.details}</div> ${tickerHtml} ${rejectedHtml} `; pipelineDetails.classList.add('visible'); };
// --- Regime Banner --- const renderRegimes = (regimes) => { if (!regimes || Object.keys(regimes).length === 0) { regimeBanner.style.display = 'none'; return; } regimeBanner.style.display = 'flex'; let html = ''; for (const [mkt, r] of Object.entries(regimes)) { const trendClass = r.trend === 'bullish' ? 'bullish' : (r.trend === 'bearish' ? 'bearish' : 'neutral'); const trendIcon = r.trend === 'bullish' ? 'fa-arrow-trend-up' : (r.trend === 'bearish' ? 'fa-arrow-trend-down' : 'fa-arrows-left-right'); html += ` <div class="regime-card"> <div class="regime-card-title"><i class="fa-solid fa-landmark"></i> ${mkt.toUpperCase()} Market Regime</div> <span class="regime-badge ${trendClass}"><i class="fa-solid ${trendIcon}"></i> ${(r.regime || '').replace(/_/g, ' ').toUpperCase()}</span> <div class="regime-info"> Trend: <strong>${r.trend}</strong> | Volatility: ${r.volatility_state} | VIX: ${r.vix || 'N/A'} | Breadth: ${r.breadth || 'N/A'}<br> ${r.description || ''} </div> </div>`; } regimeBanner.innerHTML = html; };
// --- Stats --- const updateStats = (stats) => { if (!stats) return; statUniverse.innerText = fmt(stats.universe_size); statRaw.innerText = fmt(stats.raw_signals); statFiltered.innerText = fmt(stats.risk_filtered || stats.news_filtered || stats.regime_filtered || stats.raw_signals); statFinal.innerText = fmt(stats.final_signals); statDuration.innerText = stats.duration_seconds ? `${stats.duration_seconds}s` : '-'; };
// --- Signals Table --- const updateTable = (signals) => { if (!signals || signals.length === 0) { signalsTableBody.innerHTML = `<tr><td colspan="12" style="text-align:center; padding:40px; color:var(--text-muted)">No opportunities found in the last scan.</td></tr>`; return; }
signalsTableBody.innerHTML = signals.map((s, i) => { const sector = (s.fundamental_data && s.fundamental_data.sector) || ''; const name = (s.fundamental_data && s.fundamental_data.name) || s.ticker; const narrative = s.narrative || s.reason || ''; const reasonSummary = s.reason_summary || s.reason || ''; const alphaColor = (s.alpha_score || 0) >= 70 ? 'gold' : ((s.alpha_score || 0) >= 50 ? 'green' : '');
return ` <tr class="signal-row" data-idx="${i}" onclick="window._toggleNarrative(${i})"> <td><span class="expand-indicator"><i class="fa-solid fa-chevron-right"></i></span></td> <td><div class="ticker-cell"><span class="ticker-name">${s.ticker}</span><span class="ticker-sector">${name !== s.ticker ? name : ''} ${sector ? '· ' + sector : ''}</span></div></td> <td><span class="badge">${(s.signal_type || '').replace(/_/g, ' ').toUpperCase()}</span></td> <td><span class="badge ${alphaColor}">${s.alpha_score || '-'}</span></td> <td class="mono">${fmtPrice(s.entry_price)}</td> <td class="mono positive">${fmtPrice(s.target_1)}</td> <td class="mono positive">${fmtPrice(s.target_2)}</td> <td class="mono positive">${fmtPrice(s.target_3)}</td> <td class="mono negative">${fmtPrice(s.stop_loss)}</td> <td class="mono">${s.risk_reward || '-'}</td> <td class="mono">${s.quantity || '-'}</td> <td style="font-size:0.78rem; color:var(--text-muted); max-width:200px;">${reasonSummary}</td> </tr> <tr class="narrative-row" id="narrative-${i}" style="display:none;"> <td colspan="12"><div class="narrative-container">${narrative}</div></td> </tr>`; }).join(''); };
window._toggleNarrative = (idx) => { const row = document.getElementById(`narrative-${idx}`); const signalRow = document.querySelector(`.signal-row[data-idx="${idx}"]`); if (!row) return; const isVisible = row.style.display !== 'none'; row.style.display = isVisible ? 'none' : 'table-row'; signalRow.classList.toggle('expanded', !isVisible); };
// --- Load Dashboard --- const loadDashboard = async () => { try { const res = await fetch(`${API_BASE}/dashboard?t=${Date.now()}`); const data = await res.json(); if (data.status === 'success') { updateStats(data.stats); updateTable(data.signals); if (data.pipeline_stages) { _pipelineStages = data.pipeline_stages; renderPipeline(data.pipeline_stages); } renderRegimes(data.regimes); if (data.last_scan_date) { lastUpdated.innerText = `Last Scan: ${new Date(data.last_scan_date).toLocaleString()}`; } } } catch (err) { console.error('Failed to load dashboard:', err); } };
// --- Scan Progress Simulation --- const pipelineStepNames = [ 'Determining universe...', 'Computing technical features...', 'Detecting signals...', 'Analyzing market regime...', 'Running fundamental checks...', 'Fetching news & sentiment...', 'Applying risk filters...', 'Sizing positions...', 'Scoring & ranking...', 'Building trade plans...' ];
let progressInterval = null; const showProgress = () => { scanProgress.classList.add('active'); let step = 0; progressStep.innerText = pipelineStepNames[0]; progressBar.style.width = '5%'; progressInterval = setInterval(() => { step++; if (step < pipelineStepNames.length) { progressStep.innerText = pipelineStepNames[step]; progressBar.style.width = `${(step / pipelineStepNames.length) * 90 + 5}%`; } }, 3000); }; const hideProgress = () => { progressBar.style.width = '100%'; setTimeout(() => { scanProgress.classList.remove('active'); if (progressInterval) clearInterval(progressInterval); progressBar.style.width = '0%'; }, 400); };
// --- Trigger Scans --- const triggerScan = async (market) => { const btn = market === 'us' ? btnScanUS : btnScanIN; const originalText = btn.innerHTML; btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin"></i> Scanning...`; btn.disabled = true; btnScanUS.disabled = true; btnScanIN.disabled = true; showProgress();
try { const res = await fetch(`${API_BASE}/scan`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ market, top_n: 10 }) }); const data = await res.json(); hideProgress();
if (data.status === 'success') { updateStats(data.stats); if (data.pipeline_stages) { _pipelineStages = data.pipeline_stages; renderPipeline(data.pipeline_stages); } renderRegimes(data.regimes); updateTable(data.signals); lastUpdated.innerText = `Last Scan: ${new Date().toLocaleString()}`; } else { alert('Scan failed: ' + (data.message || 'Unknown error')); } } catch (err) { hideProgress(); console.error('Scan error:', err); alert('Scan error. Check console.'); } finally { btn.innerHTML = originalText; btn.disabled = false; btnScanUS.disabled = false; btnScanIN.disabled = false; } };
btnScanUS.addEventListener('click', () => triggerScan('us')); btnScanIN.addEventListener('click', () => triggerScan('india'));
// --- Chat Logic --- const toggleChat = () => chatPanel.classList.toggle('open'); chatFab.addEventListener('click', toggleChat); chatClose.addEventListener('click', toggleChat);
const appendMessage = (text, isUser = false) => { const div = document.createElement('div'); div.className = `chat-msg ${isUser ? 'chat-msg-user' : 'chat-msg-bot'}`; const formatted = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>').replace(/\n/g, '<br>'); div.innerHTML = `<div class="chat-bubble">${formatted}</div>`; chatMessages.appendChild(div); chatMessages.scrollTop = chatMessages.scrollHeight; };
const sendMessage = async () => { const text = chatInput.value.trim(); if (!text) return; appendMessage(text, true); chatInput.value = ''; chatInput.disabled = true; chatSend.innerHTML = '<i class="fa-solid fa-ellipsis fa-bounce"></i>';
try { const res = await fetch(`${API_BASE}/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ query: text }) }); const data = await res.json(); appendMessage(data.status === 'success' ? data.response : `❌ Error: ${data.message}`); } catch (err) { appendMessage(`❌ Connection error.`); } finally { chatInput.disabled = false; chatSend.innerHTML = '<i class="fa-solid fa-paper-plane"></i>'; chatInput.focus(); } };
chatSend.addEventListener('click', sendMessage); chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); });
// Initial load loadDashboard();});1234567891011121314151617# Swing Quant Engineyfinance>=0.2.40pandas>=2.0pandas-ta>=0.3.14bnumpy>=1.24pyportfolioopt>=1.5backtesting>=0.3.3openai>=1.30httpx>=0.27langchain-openai>=0.1langchain-core>=0.2langgraph>=0.2python-dotenv>=1.0fastapi>=0.110uvicorn>=0.29pyarrow>=15.0feedparser>=6.0.gitignoreAdded+3
DockerfileAdded+31
README.mdAdded+12
backend/.DS_StoreAdded
backend/__init__.pyAdded+1
backend/agents/__init__.pyAdded+1
backend/agents/alpha_scorer.pyAdded+90
backend/agents/execution_agent.pyAdded+196
backend/agents/news_agent.pyAdded+186
backend/agents/portfolio_agent.pyAdded+104
backend/agents/regime_agent.pyAdded+190
backend/agents/risk_agent.pyAdded+150
backend/agents/scan_pipeline.pyAdded+491
backend/agents/signal_agent.pyAdded+250
backend/agents/supervisor_agent.pyAdded+89
backend/backtesting/backtester.pyAdded+181
backend/backtesting/monte_carlo.pyAdded+72
backend/backtesting/run_sample_test.pyAdded+49
backend/data/__init__.pyAdded+1
backend/data/fundamentals.pyAdded+124
backend/data/market_data.pyAdded+152
backend/data/store.pyAdded+252
backend/features/__init__.pyAdded+1
backend/features/feature_store.pyAdded+125
backend/features/fundamental.pyAdded+40
backend/features/momentum.pyAdded+74
backend/features/technical.pyAdded+118
backend/features/volatility.pyAdded+70
backend/intelligence/__init__.pyAdded+1
backend/intelligence/alert_classifier.pyAdded+96
backend/intelligence/cache.pyAdded+127
backend/intelligence/news_fetcher.pyAdded+250
backend/intelligence/perplexity_client.pyAdded+72
backend/intelligence/sentiment_analyzer.pyAdded+124
backend/server.pyAdded+127
config.pyAdded+145
frontend/css/styles.cssAdded+354
frontend/index.htmlAdded+129
frontend/js/app.jsAdded+331
requirements.txtAdded+17