""" inference.py — Root-level hackathon grader entry point for StockSense AI. This file is required by the OpenEnv hackathon platform. It wraps the backend engine and returns task scores that are strictly in the open interval (0, 1) — never exactly 0.0 or 1.0. Compatible with the same grader constraints used in PROSTLE/AarthiAI. """ from __future__ import annotations import os import sys import json import math # ── Add backend to path so we can import modules ────────────────────────────── _BACKEND = os.path.join(os.path.dirname(__file__), "backend") if _BACKEND not in sys.path: sys.path.insert(0, _BACKEND) # ── Epsilon for strict open-interval clamping ───────────────────────────────── _EPS = 1e-6 # 0.000001 — safely away from both 0 and 1 # ── Core helpers (mirrored from AarthiAI) ───────────────────────────────────── def _strict_open_unit_interval(value: float, eps: float = _EPS) -> float: """Clamp value to the strict open interval (eps, 1-eps). The OpenEnv grader requires that each task score satisfies: 0 < score < 1 (exclusive on both ends) This helper guarantees that invariant regardless of the raw value. """ return float(max(eps, min(1.0 - eps, value))) def _sentiment_to_task_score(sentiment: float) -> float: """Convert a sentiment score in [-0.99, 0.99] to a task score in (0, 1). Maps: -0.99 → ~0.005 (very bearish — low score) 0.00 → 0.5 (neutral) +0.99 → ~0.995 (very bullish — high score) """ # Linear map from [-1, 1] → [0, 1] then clamp to strict open interval raw = (sentiment + 1.0) / 2.0 return _strict_open_unit_interval(raw) def _fallback(reason: str = "") -> dict: """Return a neutral fallback result when the engine cannot produce a score.""" return { "score": _strict_open_unit_interval(0.5), "score_100": 50.0, "direction": "neutral", "reasoning": reason or "Inference unavailable — returning neutral score.", "source": "fallback", } # ── Main inference function ─────────────────────────────────────────────────── def run_inference(ticker: str, sentiment_score: float = 0.5) -> dict: """ Run StockSense AI inference for a given ticker. Returns a dict with: - score: float strictly in (0, 1) — for the OpenEnv grader - score_100: float in [0, 100] — for human-readable display - direction: "bullish" | "bearish" | "neutral" - reasoning: one-sentence explanation - source: which engine produced the result Args: ticker: Stock ticker symbol (e.g. "RELIANCE.NS") sentiment_score: Pre-computed sentiment in [-0.99, 0.99]. Defaults to 0.5 (neutral). """ try: from stock_data import fetch_stock_data, add_technical_indicators, fetch_india_vix from sentiment import analyze_sentiment from technical_signals import score_technical_signals from llm_analysis import analyze_with_llm # 1. Fetch & prepare data df = fetch_stock_data(ticker) df = add_technical_indicators(df) latest = df.iloc[-1] # 2. Sentiment analysis sent = analyze_sentiment(ticker) raw_sent_score = float(sent.get("overall_score", 0.5)) # Clamp to (-0.99, 0.99) sent_score = max(-0.99, min(0.99, raw_sent_score)) sent_label = sent.get("overall_sentiment", "neutral") # 3. Technical signals tech = score_technical_signals(df) tech_score = max(-0.99, min(0.99, float(tech.get("score", 0.5)))) tech_dir = tech.get("direction", "neutral") # 4. LLM market reasoning indicators = { "RSI": round(float(latest["RSI"]), 2), "MACD": round(float(latest["MACD"]), 4), "MACD_Signal": round(float(latest["MACD_Signal"]), 4), "SMA_20": round(float(latest["SMA_20"]), 2), "SMA_50": round(float(latest["SMA_50"]), 2), "BB_Width": round(float(latest["BB_Width"]), 4), "ATR": round(float(latest["ATR"]), 2), } recent_prices = df["Close"].values[-10:].tolist() llm = analyze_with_llm( ticker=ticker, current_price=float(latest["Close"]), indicators=indicators, sentiment_score=sent_score, sentiment_label=sent_label, recent_prices=recent_prices, ) llm_score = max(-0.99, min(0.99, float(llm.get("score", 0.5)))) llm_dir = llm.get("direction", "neutral") # 5. Composite directional score (weighted blend) W_SENT = 0.25 W_TECH = 0.30 W_LLM = 0.45 composite = W_SENT * sent_score + W_TECH * tech_score + W_LLM * llm_score # Clamp composite to (-0.99, 0.99) before converting composite = max(-0.99, min(0.99, composite)) # 6. Convert to strict open interval task score task_score = _sentiment_to_task_score(composite) score_100 = round(task_score * 100, 1) # 7. Derive direction from composite if composite > 0.1: direction = "bullish" elif composite < -0.1: direction = "bearish" else: direction = "neutral" return { "ticker": ticker, "score": round(task_score, 6), # strict (0, 1) for the grader "score_100": score_100, # 0–100 for display "direction": direction, "reasoning": llm.get("reasoning", f"Composite score: {composite:+.3f}"), "source": llm.get("source", "engine"), "components": { "sentiment": round(sent_score, 4), "technical": round(tech_score, 4), "llm": round(llm_score, 4), "composite": round(composite, 4), }, } except ImportError as e: return {**_fallback(f"Import error: {e}"), "ticker": ticker} except Exception as e: return {**_fallback(f"Engine error: {str(e)[:120]}"), "ticker": ticker} def run_batch_inference(tickers: list[str]) -> list[dict]: """Run inference for a list of tickers. Returns a list of result dicts.""" return [run_inference(t) for t in tickers] # ── CLI entry point ─────────────────────────────────────────────────────────── if __name__ == "__main__": """ Usage: python inference.py RELIANCE.NS python inference.py RELIANCE.NS TCS.NS INFY.NS """ tickers = sys.argv[1:] if len(sys.argv) > 1 else ["RELIANCE.NS"] print(f"\n[StockSense AI] Running inference for: {tickers}\n") results = run_batch_inference(tickers) for r in results: print(json.dumps(r, indent=2)) # Validate constraint score = r.get("score", -1) if 0 < score < 1: print(f" ✅ Score {score} is strictly in (0, 1) — GRADER COMPLIANT\n") else: print(f" ❌ Score {score} is OUT OF BOUNDS — grader will FAIL\n")