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|
| 1 |
+
"""
|
| 2 |
+
LLM Market Analysis via Google Gemini API.
|
| 3 |
+
Provides directional market insight (-1 to +1) with reasoning.
|
| 4 |
+
Falls back gracefully to neutral (0) when no API key is configured.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import json
|
| 11 |
+
import time
|
| 12 |
+
import hashlib
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
|
| 15 |
+
# Optional: Google Gemini SDK
|
| 16 |
+
GEMINI_AVAILABLE = False
|
| 17 |
+
_gemini_model = None
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
import google.generativeai as genai
|
| 21 |
+
GEMINI_AVAILABLE = True
|
| 22 |
+
except ImportError:
|
| 23 |
+
pass
|
| 24 |
+
|
| 25 |
+
# ── Cache: 30-minute TTL per ticker ──
|
| 26 |
+
_LLM_CACHE_TTL = 30 * 60
|
| 27 |
+
_llm_cache = {} # {ticker: {"result": ..., "timestamp": ...}}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _get_cached(ticker: str) -> dict | None:
|
| 31 |
+
entry = _llm_cache.get(ticker)
|
| 32 |
+
if entry and (time.time() - entry["timestamp"]) < _LLM_CACHE_TTL:
|
| 33 |
+
return entry["result"]
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _set_cached(ticker: str, result: dict):
|
| 38 |
+
_llm_cache[ticker] = {"result": result, "timestamp": time.time()}
|
| 39 |
+
if len(_llm_cache) > 30:
|
| 40 |
+
oldest = min(_llm_cache, key=lambda k: _llm_cache[k]["timestamp"])
|
| 41 |
+
del _llm_cache[oldest]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _init_gemini():
|
| 45 |
+
"""Initialize Gemini model (lazy, once)."""
|
| 46 |
+
global _gemini_model
|
| 47 |
+
if _gemini_model is not None:
|
| 48 |
+
return True
|
| 49 |
+
api_key = os.environ.get("GEMINI_API_KEY", "").strip()
|
| 50 |
+
if not api_key or not GEMINI_AVAILABLE:
|
| 51 |
+
return False
|
| 52 |
+
try:
|
| 53 |
+
genai.configure(api_key=api_key)
|
| 54 |
+
_gemini_model = genai.GenerativeModel("gemini-2.0-flash")
|
| 55 |
+
return True
|
| 56 |
+
except Exception:
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _build_prompt(
|
| 61 |
+
ticker: str,
|
| 62 |
+
current_price: float,
|
| 63 |
+
indicators: dict,
|
| 64 |
+
sentiment_score: float,
|
| 65 |
+
sentiment_label: str,
|
| 66 |
+
recent_prices: list[float],
|
| 67 |
+
) -> str:
|
| 68 |
+
"""Build a concise prompt for market analysis."""
|
| 69 |
+
price_change_5d = ((current_price - recent_prices[0]) / recent_prices[0] * 100) if recent_prices else 0
|
| 70 |
+
|
| 71 |
+
return f"""You are a stock market analyst. Analyze this Indian stock and give a prediction bias.
|
| 72 |
+
|
| 73 |
+
STOCK: {ticker}
|
| 74 |
+
CURRENT PRICE: ₹{current_price:.2f}
|
| 75 |
+
5-DAY PRICE CHANGE: {price_change_5d:+.2f}%
|
| 76 |
+
RECENT 5 CLOSES: {[round(p,2) for p in recent_prices[-5:]]}
|
| 77 |
+
|
| 78 |
+
TECHNICAL INDICATORS:
|
| 79 |
+
- RSI: {indicators.get('RSI', 'N/A')} (>70 overbought, <30 oversold)
|
| 80 |
+
- MACD: {indicators.get('MACD', 'N/A')} (Signal: {indicators.get('MACD_Signal', 'N/A')})
|
| 81 |
+
- SMA_20: {indicators.get('SMA_20', 'N/A')} | SMA_50: {indicators.get('SMA_50', 'N/A')}
|
| 82 |
+
- BB_Width: {indicators.get('BB_Width', 'N/A')} | ATR: {indicators.get('ATR', 'N/A')}
|
| 83 |
+
|
| 84 |
+
NEWS SENTIMENT: {sentiment_label} (score: {sentiment_score:+.3f})
|
| 85 |
+
|
| 86 |
+
Respond ONLY with this exact JSON format, no other text:
|
| 87 |
+
{{"score": <float between -1.0 and 1.0>, "direction": "<bullish/bearish/neutral>", "reasoning": "<one sentence>"}}
|
| 88 |
+
|
| 89 |
+
Score guide: -1.0 = very bearish, 0 = neutral, +1.0 = very bullish"""
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def analyze_with_llm(
|
| 93 |
+
ticker: str,
|
| 94 |
+
current_price: float,
|
| 95 |
+
indicators: dict,
|
| 96 |
+
sentiment_score: float = 0.0,
|
| 97 |
+
sentiment_label: str = "neutral",
|
| 98 |
+
recent_prices: list[float] | None = None,
|
| 99 |
+
) -> dict:
|
| 100 |
+
"""
|
| 101 |
+
Get LLM market analysis. Returns:
|
| 102 |
+
{"score": float, "direction": str, "reasoning": str, "source": str}
|
| 103 |
+
Falls back to neutral if Gemini is unavailable.
|
| 104 |
+
"""
|
| 105 |
+
# Check cache first
|
| 106 |
+
cached = _get_cached(ticker)
|
| 107 |
+
if cached is not None:
|
| 108 |
+
return cached
|
| 109 |
+
|
| 110 |
+
# Default fallback
|
| 111 |
+
fallback = {
|
| 112 |
+
"score": 0.0,
|
| 113 |
+
"direction": "neutral",
|
| 114 |
+
"reasoning": "LLM analysis unavailable (no GEMINI_API_KEY configured)",
|
| 115 |
+
"source": "fallback",
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
if not _init_gemini():
|
| 119 |
+
_set_cached(ticker, fallback)
|
| 120 |
+
return fallback
|
| 121 |
+
|
| 122 |
+
if recent_prices is None:
|
| 123 |
+
recent_prices = [current_price]
|
| 124 |
+
|
| 125 |
+
prompt = _build_prompt(
|
| 126 |
+
ticker, current_price, indicators,
|
| 127 |
+
sentiment_score, sentiment_label, recent_prices,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
response = _gemini_model.generate_content(prompt)
|
| 132 |
+
text = response.text.strip()
|
| 133 |
+
|
| 134 |
+
# Extract JSON from response (handle markdown code blocks)
|
| 135 |
+
if "```" in text:
|
| 136 |
+
text = text.split("```")[1]
|
| 137 |
+
if text.startswith("json"):
|
| 138 |
+
text = text[4:]
|
| 139 |
+
text = text.strip()
|
| 140 |
+
|
| 141 |
+
parsed = json.loads(text)
|
| 142 |
+
score = max(-1.0, min(1.0, float(parsed.get("score", 0))))
|
| 143 |
+
|
| 144 |
+
result = {
|
| 145 |
+
"score": round(score, 3),
|
| 146 |
+
"direction": parsed.get("direction", "neutral"),
|
| 147 |
+
"reasoning": parsed.get("reasoning", ""),
|
| 148 |
+
"source": "gemini",
|
| 149 |
+
}
|
| 150 |
+
_set_cached(ticker, result)
|
| 151 |
+
return result
|
| 152 |
+
|
| 153 |
+
except Exception as e:
|
| 154 |
+
fallback["reasoning"] = f"LLM analysis failed: {str(e)[:80]}"
|
| 155 |
+
_set_cached(ticker, fallback)
|
| 156 |
+
return fallback
|