Spaces:
Sleeping
Sleeping
Download backend/llm_analysis.py from PROSTLE/StockSense-AI: direct link, hf CLI and curl.
- Browser
- Download file 5.32 kB
-
https://huggingface.co/spaces/PROSTLE/StockSense-AI/resolve/main/backend/llm_analysis.py
- Command line
-
hf download hf://spaces/PROSTLE/StockSense-AI/backend/llm_analysis.py
-
curl -L -o llm_analysis.py https://huggingface.co/spaces/PROSTLE/StockSense-AI/resolve/main/backend/llm_analysis.py
5.32 kB
| """ | |
| LLM Market Analysis via Google Gemini API (google-genai SDK). | |
| Provides directional market insight (-1 to +1) with reasoning. | |
| Falls back gracefully to neutral (0) on API errors or quota exhaustion. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| import json | |
| import time | |
| from dotenv import load_dotenv | |
| # Load .env first | |
| load_dotenv() | |
| # ββ New google-genai SDK ββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| from llm_proxy import get_llm_client | |
| # ββ Model/Client state ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| _llm_client = None | |
| def _init_client() -> bool: | |
| global _llm_client | |
| if _llm_client is not None: | |
| return True | |
| _llm_client = get_llm_client() | |
| if _llm_client.mode == "none": | |
| print("[LLM] ERROR: No valid LLM client (Proxy or Gemini) could be initialized.") | |
| return False | |
| return True | |
| # ββ Cache: 30-minute TTL per ticker ββββββββββββββββββββββββββββββββββββββββββ | |
| _LLM_CACHE_TTL = 30 * 60 | |
| _llm_cache: dict = {} # {ticker: {"result": ..., "timestamp": ...}} | |
| def _get_cached(ticker: str) -> dict | None: | |
| entry = _llm_cache.get(ticker) | |
| if entry and (time.time() - entry["timestamp"]) < _LLM_CACHE_TTL: | |
| return entry["result"] | |
| return None | |
| def _set_cached(ticker: str, result: dict): | |
| _llm_cache[ticker] = {"result": result, "timestamp": time.time()} | |
| if len(_llm_cache) > 30: | |
| oldest = min(_llm_cache, key=lambda k: _llm_cache[k]["timestamp"]) | |
| del _llm_cache[oldest] | |
| def _build_prompt( | |
| ticker: str, | |
| current_price: float, | |
| indicators: dict, | |
| sentiment_score: float, | |
| sentiment_label: str, | |
| recent_prices: list[float], | |
| ) -> str: | |
| """Build a concise prompt for market analysis.""" | |
| price_change_5d = ((current_price - recent_prices[0]) / recent_prices[0] * 100) if recent_prices else 0 | |
| return f"""You are a stock market analyst. Analyze this Indian stock and give a prediction bias. | |
| STOCK: {ticker} | |
| CURRENT PRICE: βΉ{current_price:.2f} | |
| 5-DAY PRICE CHANGE: {price_change_5d:+.2f}% | |
| RECENT 5 CLOSES: {[round(p,2) for p in recent_prices[-5:]]} | |
| TECHNICAL INDICATORS: | |
| - RSI: {indicators.get('RSI', 'N/A')} (>70 overbought, <30 oversold) | |
| - MACD: {indicators.get('MACD', 'N/A')} (Signal: {indicators.get('MACD_Signal', 'N/A')}) | |
| - SMA_20: {indicators.get('SMA_20', 'N/A')} | SMA_50: {indicators.get('SMA_50', 'N/A')} | |
| - BB_Width: {indicators.get('BB_Width', 'N/A')} | ATR: {indicators.get('ATR', 'N/A')} | |
| NEWS SENTIMENT: {sentiment_label} (score: {sentiment_score:+.3f}) | |
| Respond ONLY with this exact JSON format, no other text: | |
| {{"score": <float strictly between -0.99 and 0.99, never exactly -1 or 1>, "direction": "<bullish/bearish/neutral>", "reasoning": "<one sentence>"}} | |
| Score guide: -0.99 = very bearish, 0 = neutral, +0.99 = very bullish. NEVER return exactly -1.0 or 1.0.""" | |
| def analyze_with_llm( | |
| ticker: str, | |
| current_price: float, | |
| indicators: dict, | |
| sentiment_score: float = 0.5, | |
| sentiment_label: str = "neutral", | |
| recent_prices: list[float] | None = None, | |
| ) -> dict: | |
| """ | |
| Get LLM market analysis. Returns: | |
| {"score": float, "direction": str, "reasoning": str, "source": str} | |
| """ | |
| global _llm_client | |
| # Check cache first | |
| cached = _get_cached(ticker) | |
| if cached is not None: | |
| return cached | |
| # Default fallback β use 0.5 (neutral mid-point) | |
| fallback = { | |
| "score": 0.5, | |
| "direction": "neutral", | |
| "reasoning": "LLM analysis unavailable β using technical/sentiment signals only", | |
| "source": "fallback", | |
| } | |
| if not _init_client(): | |
| _set_cached(ticker, fallback) | |
| return fallback | |
| if recent_prices is None: | |
| recent_prices = [current_price] | |
| prompt = _build_prompt( | |
| ticker, current_price, indicators, | |
| sentiment_score, sentiment_label, recent_prices, | |
| ) | |
| try: | |
| text = _llm_client.generate_content(prompt) | |
| text = text.strip() | |
| # Extract JSON from response (handle markdown code blocks) | |
| if "```" in text: | |
| # Try to grab the first code block | |
| parts = text.split("```") | |
| if len(parts) >= 2: | |
| text = parts[1] | |
| if text.startswith("json"): | |
| text = text[4:] | |
| text = text.strip() | |
| parsed = json.loads(text) | |
| # Clamp to strict (-0.99, 0.99) β never allow boundary values Β±1.0 | |
| raw_score = float(parsed.get("score", 0.5)) | |
| score = max(-0.99, min(0.99, raw_score)) | |
| result = { | |
| "score": round(score, 3), | |
| "direction": parsed.get("direction", "neutral"), | |
| "reasoning": parsed.get("reasoning", ""), | |
| "source": f"llm_proxy/{_llm_client.mode}", | |
| } | |
| _set_cached(ticker, result) | |
| return result | |
| except Exception as e: | |
| error_msg = str(e) | |
| fallback["reasoning"] = f"LLM analysis failed: {error_msg[:100]}" | |
| _set_cached(ticker, fallback) | |
| return fallback | |