File size: 5,319 Bytes
af0538f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9f2b41
c1893a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af0538f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e4bb54
af0538f
8e4bb54
af0538f
 
 
 
 
 
8e4bb54
af0538f
 
 
 
 
 
 
c1893a4
af0538f
 
 
 
 
 
c1893a4
af0538f
8e4bb54
af0538f
 
 
 
 
c1893a4
af0538f
 
 
 
 
 
 
 
 
 
 
 
c1893a4
 
af0538f
 
 
c1893a4
 
 
 
 
 
af0538f
 
 
8e4bb54
 
 
af0538f
 
 
 
 
c1893a4
af0538f
 
 
 
 
 
c1893a4
 
af0538f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
"""
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