File size: 7,569 Bytes
8e4bb54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
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")