PROSTLE commited on
Commit
c1893a4
·
1 Parent(s): 1d7914d

fix: migrate to OpenEnv LLM proxy and satisfy all grader criteria

Browse files
backend/llm_analysis.py CHANGED
@@ -14,91 +14,39 @@ from dotenv import load_dotenv
14
  load_dotenv()
15
 
16
  # ── New google-genai SDK ──────────────────────────────────────────────────────
17
- GEMINI_AVAILABLE = False
18
- _gemini_client = None
19
-
20
- try:
21
- from google import genai as _genai_sdk
22
- GEMINI_AVAILABLE = True
23
- except ImportError:
24
- pass
25
-
26
- # ── Model selection (tried in order until one works) ──────────────────────────
27
- GEMINI_MODELS = [
28
- "gemini-2.0-flash-lite",
29
- "gemini-2.5-flash",
30
- "gemini-2.0-flash",
31
- "gemini-flash-latest",
32
- ]
33
- _active_model: str | None = None
34
 
35
  # ── Cache: 30-minute TTL per ticker ──────────────────────────────────────────
36
  _LLM_CACHE_TTL = 30 * 60
37
  _llm_cache: dict = {} # {ticker: {"result": ..., "timestamp": ...}}
38
 
39
-
40
  def _get_cached(ticker: str) -> dict | None:
41
  entry = _llm_cache.get(ticker)
42
  if entry and (time.time() - entry["timestamp"]) < _LLM_CACHE_TTL:
43
  return entry["result"]
44
  return None
45
 
46
-
47
  def _set_cached(ticker: str, result: dict):
48
  _llm_cache[ticker] = {"result": result, "timestamp": time.time()}
49
  if len(_llm_cache) > 30:
50
  oldest = min(_llm_cache, key=lambda k: _llm_cache[k]["timestamp"])
51
  del _llm_cache[oldest]
52
 
53
-
54
- def _init_gemini() -> bool:
55
- global _gemini_client, _active_model
56
-
57
- if _gemini_client is not None and _active_model is not None:
58
- return True
59
-
60
- if not GEMINI_AVAILABLE:
61
- print("[LLM] ERROR: google-genai SDK not installed.")
62
- return False
63
-
64
- api_key = os.getenv("GEMINI_API_KEY")
65
- if not api_key:
66
- print("[LLM] ERROR: GEMINI_API_KEY not found in environment!")
67
- return False
68
-
69
- try:
70
- _gemini_client = _genai_sdk.Client(api_key=api_key)
71
- # Pick the first model that responds
72
- for model in GEMINI_MODELS:
73
- try:
74
- _gemini_client.models.generate_content(
75
- model=model, contents="ping"
76
- )
77
- _active_model = model
78
- print(f"[LLM] Ready: {model}")
79
- return True
80
- except Exception as probe_err:
81
- msg = str(probe_err)
82
- if "429" in msg or "RESOURCE_EXHAUSTED" in msg:
83
- print(f"[LLM] {model}: quota exhausted, trying next model...")
84
- continue
85
- elif "404" in msg or "NOT_FOUND" in msg:
86
- print(f"[LLM] {model}: not found, trying next model...")
87
- continue
88
- else:
89
- print(f"[LLM] {model}: {msg[:80]}")
90
- continue
91
-
92
- print("[LLM] All Gemini models exhausted quota or unavailable.")
93
- _gemini_client = None
94
- return False
95
-
96
- except Exception as e:
97
- print(f"[LLM] Gemini init error: {e}")
98
- _gemini_client = None
99
- return False
100
-
101
-
102
  def _build_prompt(
103
  ticker: str,
104
  current_price: float,
@@ -142,17 +90,15 @@ def analyze_with_llm(
142
  """
143
  Get LLM market analysis. Returns:
144
  {"score": float, "direction": str, "reasoning": str, "source": str}
145
- Falls back to neutral if Gemini is unavailable or quota is exhausted.
146
  """
147
- # Must declare global before any use of these names in this function
148
- global _gemini_client, _active_model
149
 
150
  # Check cache first
151
  cached = _get_cached(ticker)
152
  if cached is not None:
153
  return cached
154
 
155
- # Default fallback — use 0.5 (neutral mid-point), never 0.0 which can boundary-fail the grader
156
  fallback = {
157
  "score": 0.5,
158
  "direction": "neutral",
@@ -160,7 +106,7 @@ def analyze_with_llm(
160
  "source": "fallback",
161
  }
162
 
163
- if not _init_gemini():
164
  _set_cached(ticker, fallback)
165
  return fallback
166
 
@@ -173,17 +119,17 @@ def analyze_with_llm(
173
  )
174
 
175
  try:
176
- response = _gemini_client.models.generate_content(
177
- model=_active_model,
178
- contents=prompt,
179
- )
180
- text = response.text.strip()
181
 
182
  # Extract JSON from response (handle markdown code blocks)
183
  if "```" in text:
184
- text = text.split("```")[1]
185
- if text.startswith("json"):
186
- text = text[4:]
 
 
 
187
  text = text.strip()
188
 
189
  parsed = json.loads(text)
@@ -195,26 +141,13 @@ def analyze_with_llm(
195
  "score": round(score, 3),
196
  "direction": parsed.get("direction", "neutral"),
197
  "reasoning": parsed.get("reasoning", ""),
198
- "source": f"gemini/{_active_model}",
199
  }
200
  _set_cached(ticker, result)
201
  return result
202
 
203
  except Exception as e:
204
  error_msg = str(e)
205
-
206
- if "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
207
- # Quota hit — reset so next call tries to find a working model
208
- fallback["reasoning"] = "LLM quota exhausted — using technical/sentiment signals only"
209
- _gemini_client = None
210
- _active_model = None
211
- elif "API_KEY_INVALID" in error_msg or "API key expired" in error_msg:
212
- fallback["reasoning"] = "LLM API key invalid/expired — using technical/sentiment signals only"
213
- _gemini_client = None
214
- _active_model = None
215
- else:
216
- fallback["reasoning"] = f"LLM analysis failed: {error_msg[:100]}"
217
- # Cache non-auth errors so we don't spam the API
218
- _set_cached(ticker, fallback)
219
-
220
  return fallback
 
14
  load_dotenv()
15
 
16
  # ── New google-genai SDK ──────────────────────────────────────────────────────
17
+ from .llm_proxy import get_llm_client
18
+
19
+ # ── Model/Client state ────────────────────────────────────────────────────────
20
+ _llm_client = None
21
+
22
+ def _init_client() -> bool:
23
+ global _llm_client
24
+ if _llm_client is not None:
25
+ return True
26
+
27
+ _llm_client = get_llm_client()
28
+ if _llm_client.mode == "none":
29
+ print("[LLM] ERROR: No valid LLM client (Proxy or Gemini) could be initialized.")
30
+ return False
31
+ return True
32
+
 
33
 
34
  # ── Cache: 30-minute TTL per ticker ──────────────────────────────────────────
35
  _LLM_CACHE_TTL = 30 * 60
36
  _llm_cache: dict = {} # {ticker: {"result": ..., "timestamp": ...}}
37
 
 
38
  def _get_cached(ticker: str) -> dict | None:
39
  entry = _llm_cache.get(ticker)
40
  if entry and (time.time() - entry["timestamp"]) < _LLM_CACHE_TTL:
41
  return entry["result"]
42
  return None
43
 
 
44
  def _set_cached(ticker: str, result: dict):
45
  _llm_cache[ticker] = {"result": result, "timestamp": time.time()}
46
  if len(_llm_cache) > 30:
47
  oldest = min(_llm_cache, key=lambda k: _llm_cache[k]["timestamp"])
48
  del _llm_cache[oldest]
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def _build_prompt(
51
  ticker: str,
52
  current_price: float,
 
90
  """
91
  Get LLM market analysis. Returns:
92
  {"score": float, "direction": str, "reasoning": str, "source": str}
 
93
  """
94
+ global _llm_client
 
95
 
96
  # Check cache first
97
  cached = _get_cached(ticker)
98
  if cached is not None:
99
  return cached
100
 
101
+ # Default fallback — use 0.5 (neutral mid-point)
102
  fallback = {
103
  "score": 0.5,
104
  "direction": "neutral",
 
106
  "source": "fallback",
107
  }
108
 
109
+ if not _init_client():
110
  _set_cached(ticker, fallback)
111
  return fallback
112
 
 
119
  )
120
 
121
  try:
122
+ text = _llm_client.generate_content(prompt)
123
+ text = text.strip()
 
 
 
124
 
125
  # Extract JSON from response (handle markdown code blocks)
126
  if "```" in text:
127
+ # Try to grab the first code block
128
+ parts = text.split("```")
129
+ if len(parts) >= 2:
130
+ text = parts[1]
131
+ if text.startswith("json"):
132
+ text = text[4:]
133
  text = text.strip()
134
 
135
  parsed = json.loads(text)
 
141
  "score": round(score, 3),
142
  "direction": parsed.get("direction", "neutral"),
143
  "reasoning": parsed.get("reasoning", ""),
144
+ "source": f"llm_proxy/{_llm_client.mode}",
145
  }
146
  _set_cached(ticker, result)
147
  return result
148
 
149
  except Exception as e:
150
  error_msg = str(e)
151
+ fallback["reasoning"] = f"LLM analysis failed: {error_msg[:100]}"
152
+ _set_cached(ticker, fallback)
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  return fallback
backend/llm_proxy.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import base64
4
+ from openai import OpenAI
5
+ from dotenv import load_dotenv
6
+
7
+ load_dotenv()
8
+
9
+ class LLMProxy:
10
+ """
11
+ Unified LLM Client that routes calls through the OpenEnv proxy if available,
12
+ otherwise falls back to Google Gemini for local development.
13
+ """
14
+ def __init__(self):
15
+ # Grader-injected environment variables
16
+ self.api_base_url = os.getenv("API_BASE_URL")
17
+ self.api_key = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
18
+ self.model_name = os.getenv("MODEL_NAME")
19
+
20
+ # Local fallback variables
21
+ self.gemini_key = os.getenv("GEMINI_API_KEY")
22
+
23
+ self.client = None
24
+ self.mode = "none"
25
+
26
+ # 1. Prioritize Grader Proxy (OpenAI-compatible)
27
+ if self.api_base_url and self.api_key:
28
+ try:
29
+ self.client = OpenAI(
30
+ api_key=self.api_key,
31
+ base_url=self.api_base_url
32
+ )
33
+ self.mode = "proxy"
34
+ print(f"[LLM] Client initialized via Proxy: {self.api_base_url}")
35
+ except Exception as e:
36
+ print(f"[LLM] Proxy init failed: {e}")
37
+
38
+ # 2. Fallback to Gemini (Local)
39
+ elif self.gemini_key:
40
+ try:
41
+ from google import genai
42
+ self.client = genai.Client(api_key=self.gemini_key)
43
+ self.mode = "gemini"
44
+ print("[LLM] Client initialized via Google Gemini (Local Fallback)")
45
+ except ImportError:
46
+ print("[LLM] google-genai not installed for fallback.")
47
+ except Exception as e:
48
+ print(f"[LLM] Gemini init failed: {e}")
49
+
50
+ def generate_content(self, prompt: str, image_bytes: bytes = None) -> str:
51
+ """
52
+ Generic interface to generate content from text and optional image.
53
+ """
54
+ if not self.client:
55
+ return "Error: No LLM client initialized."
56
+
57
+ if self.mode == "proxy":
58
+ return self._generate_via_proxy(prompt, image_bytes)
59
+ elif self.mode == "gemini":
60
+ return self._generate_via_gemini(prompt, image_bytes)
61
+
62
+ return "Error: Unknown LLM mode."
63
+
64
+ def _generate_via_proxy(self, prompt: str, image_bytes: bytes = None) -> str:
65
+ model = self.model_name or "gpt-4o" # Default if not provided
66
+ messages = []
67
+
68
+ if image_bytes:
69
+ # OpenAI multimodal format
70
+ base64_image = base64.b64encode(image_bytes).decode('utf-8')
71
+ messages.append({
72
+ "role": "user",
73
+ "content": [
74
+ {"type": "text", "text": prompt},
75
+ {
76
+ "type": "image_url",
77
+ "image_url": {
78
+ "url": f"data:image/png;base64,{base64_image}"
79
+ }
80
+ }
81
+ ]
82
+ })
83
+ else:
84
+ messages.append({"role": "user", "content": prompt})
85
+
86
+ try:
87
+ response = self.client.chat.completions.create(
88
+ model=model,
89
+ messages=messages,
90
+ response_format={ "type": "json_object" } if "JSON" in prompt.upper() else None
91
+ )
92
+ return response.choices[0].message.content
93
+ except Exception as e:
94
+ print(f"[LLM Proxy] Error: {e}")
95
+ return f"Error: {str(e)}"
96
+
97
+ def _generate_via_gemini(self, prompt: str, image_bytes: bytes = None) -> str:
98
+ # Default models for Gemini fallback
99
+ model = "gemini-2.0-flash" if image_bytes else "gemini-2.0-flash-lite"
100
+
101
+ try:
102
+ contents = [prompt]
103
+ if image_bytes:
104
+ from google.genai import types
105
+ contents.append(types.Part.from_bytes(data=image_bytes, mime_type="image/png"))
106
+
107
+ response = self.client.models.generate_content(
108
+ model=model,
109
+ contents=contents
110
+ )
111
+ return response.text
112
+ except Exception as e:
113
+ print(f"[LLM Gemini] Error: {e}")
114
+ return f"Error: {str(e)}"
115
+
116
+ # Global singleton
117
+ _proxy_instance = None
118
+ def get_llm_client():
119
+ global _proxy_instance
120
+ if _proxy_instance is None:
121
+ _proxy_instance = LLMProxy()
122
+ return _proxy_instance
backend/llm_vision_analysis.py CHANGED
@@ -9,33 +9,18 @@ from dotenv import load_dotenv
9
 
10
  load_dotenv()
11
 
12
- # Gemini SDK (New google-genai)
13
- GEMINI_AVAILABLE = False
14
- try:
15
- from google import genai as _genai_sdk
16
- from google.genai import types
17
- GEMINI_AVAILABLE = True
18
- except ImportError:
19
- pass
20
 
21
  class LLMVisionEngine:
22
  def __init__(self):
23
- self.api_key = os.getenv("GEMINI_API_KEY")
24
- self.client = None
25
- self.model = "gemini-2.0-flash" # Best for vision/speed
26
-
27
- if GEMINI_AVAILABLE and self.api_key:
28
- try:
29
- self.client = _genai_sdk.Client(api_key=self.api_key)
30
- except Exception as e:
31
- print(f"[Vision] Init error: {e}")
32
 
33
  def analyze_chart(self, ticker: str, df: pd.DataFrame) -> dict:
34
  """
35
- Generates a chart image and asks Gemini to interpret the patterns.
36
  """
37
- if not self.client:
38
- return {"error": "Gemini Vision unavailable"}
39
 
40
  # 1. Generate the Chart
41
  img_bytes = self._generate_chart_bytes(ticker, df)
@@ -49,35 +34,36 @@ class LLMVisionEngine:
49
  Respond ONLY with this JSON format:
50
  {{
51
  "direction": "bullish|bearish|neutral",
52
- "score": <float -1.0 to 1.0>,
53
  "reasoning": "<one sentence analysis of visual patterns>",
54
  "patterns": ["pattern1", "pattern2"]
55
  }}
56
  """
57
 
58
  try:
59
- # 3. Send to Gemini
60
- response = self.client.models.generate_content(
61
- model=self.model,
62
- contents=[
63
- prompt,
64
- types.Part.from_bytes(data=img_bytes, mime_type="image/png")
65
- ]
66
- )
67
-
68
- text = response.text.strip()
69
  if "```" in text:
70
- text = text.split("```")[1]
71
- if text.startswith("json"):
72
- text = text[4:]
 
 
73
  text = text.strip()
74
 
75
  prediction = json.loads(text)
76
- prediction["source"] = f"gemini-vision/{self.model}"
 
 
 
 
 
77
  return prediction
78
 
79
  except Exception as e:
80
- print(f"[Vision] API error: {e}")
81
  return {"error": str(e)}
82
 
83
  def _generate_chart_bytes(self, ticker: str, df: pd.DataFrame) -> bytes:
 
9
 
10
  load_dotenv()
11
 
12
+ from .llm_proxy import get_llm_client
 
 
 
 
 
 
 
13
 
14
  class LLMVisionEngine:
15
  def __init__(self):
16
+ self.proxy = get_llm_client()
 
 
 
 
 
 
 
 
17
 
18
  def analyze_chart(self, ticker: str, df: pd.DataFrame) -> dict:
19
  """
20
+ Generates a chart image and asks the LLM to interpret the patterns.
21
  """
22
+ if self.proxy.mode == "none":
23
+ return {"error": "LLM Proxy unavailable"}
24
 
25
  # 1. Generate the Chart
26
  img_bytes = self._generate_chart_bytes(ticker, df)
 
34
  Respond ONLY with this JSON format:
35
  {{
36
  "direction": "bullish|bearish|neutral",
37
+ "score": <float -0.99 to 0.99>,
38
  "reasoning": "<one sentence analysis of visual patterns>",
39
  "patterns": ["pattern1", "pattern2"]
40
  }}
41
  """
42
 
43
  try:
44
+ # 3. Send to Proxy
45
+ text = self.proxy.generate_content(prompt, image_bytes=img_bytes)
46
+ text = text.strip()
47
+
 
 
 
 
 
 
48
  if "```" in text:
49
+ parts = text.split("```")
50
+ if len(parts) >= 2:
51
+ text = parts[1]
52
+ if text.startswith("json"):
53
+ text = text[4:]
54
  text = text.strip()
55
 
56
  prediction = json.loads(text)
57
+ prediction["source"] = f"llm_proxy_vision/{self.proxy.mode}"
58
+
59
+ # Ensure score is rounded and clamped
60
+ raw_score = float(prediction.get("score", 0.0))
61
+ prediction["score"] = round(max(-0.99, min(0.99, raw_score)), 3)
62
+
63
  return prediction
64
 
65
  except Exception as e:
66
+ print(f"[Vision] Engine error: {e}")
67
  return {"error": str(e)}
68
 
69
  def _generate_chart_bytes(self, ticker: str, df: pd.DataFrame) -> bytes:
backend/requirements.txt CHANGED
@@ -14,4 +14,5 @@ nltk>=3.8.1
14
  google-generativeai>=0.3.0
15
  python-dotenv>=1.0.0
16
  matplotlib>=3.8.0
 
17
  # Note: torch is installed separately in Dockerfile to use CPU-only index
 
14
  google-generativeai>=0.3.0
15
  python-dotenv>=1.0.0
16
  matplotlib>=3.8.0
17
+ openai>=1.2.0
18
  # Note: torch is installed separately in Dockerfile to use CPU-only index
inference.py CHANGED
@@ -20,6 +20,12 @@ _BACKEND = os.path.join(os.path.dirname(__file__), "backend")
20
  if _BACKEND not in sys.path:
21
  sys.path.insert(0, _BACKEND)
22
 
 
 
 
 
 
 
23
  # ── Epsilon for strict open-interval clamping ─────────────────────────────────
24
  _EPS = 1e-6 # 0.000001 — safely away from both 0 and 1
25
 
 
20
  if _BACKEND not in sys.path:
21
  sys.path.insert(0, _BACKEND)
22
 
23
+ # ── OpenEnv Grader Requirements (Explict Environment Mappings) ─────────────
24
+ API_BASE_URL = os.getenv("API_BASE_URL", "https://api.openai.com/v1")
25
+ MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4o")
26
+ HF_TOKEN = os.getenv("HF_TOKEN")
27
+ LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME")
28
+
29
  # ── Epsilon for strict open-interval clamping ─────────────────────────────────
30
  _EPS = 1e-6 # 0.000001 — safely away from both 0 and 1
31
 
pyproject.toml CHANGED
@@ -28,6 +28,7 @@ dependencies = [
28
  "matplotlib",
29
  "openenv-core>=0.2.0",
30
  "torch>=2.11.0",
 
31
  ]
32
 
33
  [project.scripts]
 
28
  "matplotlib",
29
  "openenv-core>=0.2.0",
30
  "torch>=2.11.0",
31
+ "openai>=2.31.0",
32
  ]
33
 
34
  [project.scripts]
stocksense_ai.egg-info/PKG-INFO ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: stocksense-ai
3
+ Version: 3.0.0
4
+ Summary: Enterprise-grade AI trading engine for Indian markets (NSE/BSE)
5
+ Author: Prostle Team
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: fastapi
9
+ Requires-Dist: uvicorn
10
+ Requires-Dist: yfinance
11
+ Requires-Dist: pandas
12
+ Requires-Dist: numpy
13
+ Requires-Dist: scikit-learn
14
+ Requires-Dist: transformers
15
+ Requires-Dist: requests
16
+ Requires-Dist: python-dateutil
17
+ Requires-Dist: ta
18
+ Requires-Dist: pydantic
19
+ Requires-Dist: xgboost
20
+ Requires-Dist: nltk
21
+ Requires-Dist: google-generativeai
22
+ Requires-Dist: python-dotenv
23
+ Requires-Dist: matplotlib
24
+ Requires-Dist: openenv-core>=0.2.0
25
+ Requires-Dist: torch>=2.11.0
26
+ Requires-Dist: openai>=2.31.0
27
+
28
+ ---
29
+ title: StockSense AI
30
+ emoji: 📈
31
+ colorFrom: indigo
32
+ colorTo: purple
33
+ sdk: docker
34
+ app_port: 8000
35
+ short_description: AI trading engine for Indian markets (NSE/BSE)
36
+ ---
37
+
38
+ # 📈 StockSense-AI — Enterprise-Grade Trading Engine
39
+
40
+ > **StockSense-AI** is a multi-factor hybrid intelligence platform that blends Deep Learning, Intraday ML, and LLM reasoning to provide high-precision stock signals for the Indian market (NSE/BSE).
41
+
42
+ ---
43
+
44
+ ## 🌟 Vision & Pitch
45
+
46
+ *"StockSense AI doesn't just predict prices; it understands market context. By fusing **LSTM-based daily forecasting** with **XGBoost intraday signals**, **FinBERT sentiment analysis**, and **Gemini LLM reasoning**, we've built a decision engine that adapts to market regimes in real-time. Whether you're tracking 5-day trends or hunting for intraday breakouts, StockSense AI provides the confidence score and risk-mitigation strategy you need."*
47
+
48
+ ---
49
+
50
+ ## 🚀 Key Features
51
+
52
+ ### 🧠 **The Hybrid Command Engine**
53
+ - **LSTM Neural Network**: 2-layer Deep Learning model trained on 2 years of daily data for 5-day price forecasting.
54
+ - **XGBoost Intraday Pipeline**: High-velocity ML model trained on 1-minute bars to capture micro-trends.
55
+ - **FinBERT Sentiment Analysis**: Advanced NLP scoring of real-time financial news and social sentiment.
56
+ - **Gemini LLM Reasoning**: Human-readable trade justifications and "why" analysis for every signal.
57
+ - **Factor Blending**: 5-factor weighted scoring (Technicals + Sentiment + LSTM + XGBoost + Market Context).
58
+
59
+ ### 🏦 **Paper Trading & Wallet Simulation**
60
+ - **Virtual Portfolio Management**: Track open positions, realized/unrealized P&L, and win rates.
61
+ - **Integrated Wallet**: Deposit and withdraw (Razorpay-style simulation) with full transaction history.
62
+ - **Account Performance Charting**: Visual snapshots of your portfolio growth over time.
63
+
64
+ ### 🛡️ **Advanced Risk Management**
65
+ - **Dynamic ATR-based Levels**: Stop-Loss and Take-Profit targets that adjust automatically to ticker volatility.
66
+ - **Adaptive Market Regimes**: System switches behavior across 4 states: *Bull Low-Vol, Bull High-Vol, Bear High-Vol, and Sideways*.
67
+ - **Risk-Based Position Sizing**: Automatic share calculation based on your "capital-at-risk" percentage.
68
+ - **Trailing Stop-Loss**: Intelligent profit-locking mechanism that follows the price as it rises.
69
+
70
+ ### 💎 **Glassmorphic Interactive UI**
71
+ - **Premium Aesthetics**: High-end translucent design system with vibrant neon accents.
72
+ - **Multi-Tab Dashboard**: Switch between **Charts**, **Unified Dashboard**, **Auto-Trade Engine**, and **Trading Portfolio**.
73
+ - **Real-Time Price Banner**: Live tracking of tickers with market-depth indicators.
74
+ - **High-Potential Scanner**: Real-time scanner for "Strong Buy" signals across Top 50 NSE stocks.
75
+
76
+ ---
77
+
78
+ ## 🏗️ Architecture & Stack
79
+
80
+ ```mermaid
81
+ graph LR
82
+ User((User)) -- "Ticker" --> API[FastAPI Gateway]
83
+
84
+ subgraph "Engine Layer"
85
+ API --> LSTM[Deep Learning: Daily Trends]
86
+ API --> XGB[XGBoost: Intraday Signals]
87
+ API --> NLP[FinBERT: News Sentiment]
88
+ API --> Gemini[LLM: Market Reasoning]
89
+ end
90
+
91
+ subgraph "Decision AI"
92
+ LSTM & XGB & NLP & Gemini --> Blender[Weighted Composite Blender]
93
+ Blender --> Regime[Regime/Volatility Filter]
94
+ end
95
+
96
+ subgraph "Execution Layer"
97
+ Regime --> Risk[ATR Risk Engine: SL/TP/Sizing]
98
+ Risk --> Sim[[Paper Trading Simulator]]
99
+ end
100
+ ```
101
+
102
+ ### **Tech Stack**
103
+ - **Backend**: Python 3.10+, FastAPI, Uvicorn, SQLAlchemy (SQLite).
104
+ - **ML/Science**: PyTorch (LSTM), XGBoost, Transformers (FinBERT), Scikit-learn, Pandas, yfinance.
105
+ - **Frontend**: Vanilla HTML5/JS (ES6+), Chart.js for visualization, Glassmorphic CSS Engine.
106
+ - **Reasoning**: Google Gemini 2.0 API.
107
+
108
+ ---
109
+
110
+ ## 🔧 Installation & Setup
111
+
112
+ ### **1. Backend (The Brain)**
113
+ ```bash
114
+ cd backend
115
+ python -m venv venv
116
+ # Windows
117
+ .\venv\Scripts\activate
118
+ # Linux/Mac
119
+ source venv/bin/activate
120
+
121
+ pip install -r requirements.txt
122
+ # Create a .env file with your GEMINI_API_KEY
123
+ uvicorn app:app --port 8000
124
+ ```
125
+
126
+ ### **2. Frontend (The Interface)**
127
+ Simply host the `frontend` directory using any local server:
128
+ ```bash
129
+ cd frontend
130
+ python -m http.server 5500
131
+ ```
132
+ Visit `http://localhost:5500`.
133
+
134
+ ---
135
+
136
+ ## 📋 ML Pipeline Details
137
+
138
+ | Stage | Logic |
139
+ | :--- | :--- |
140
+ | **Data** | 1-min & Daily OHLCV via Yahoo Finance API. |
141
+ | **LSTM** | 60-bar lookback window, recursive 5-day out-of-sample forecast. |
142
+ | **XGBoost** | Feature-rich ensemble (RSI, MACD, BB, VWAP, Supertrend) for next-5-bar returns. |
143
+ | **Regime** | 4-state classification using India VIX and Sector Strength. |
144
+ | **Scoring** | Normal: 45% LSTM, 45% XGB, 10% Sent \| Volatile: 48.5% LSTM, 48.5% XGB, 3% Sent. |
145
+
146
+ ---
147
+
148
+ ## ⚠️ Disclaimer
149
+
150
+ StockSense AI is for **educational and simulation purposes only**. This is a paper-trading platform. Algorithms can fail, and market data can be delayed. **Never use this tool for actual financial investments without consulting a certified advisor.**
151
+
152
+ ---
153
+
154
+ ## 📜 License
155
+
156
+ Distributed under the **MIT License**. See `LICENSE` for more information.
stocksense_ai.egg-info/SOURCES.txt ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ README.md
2
+ pyproject.toml
3
+ backend/__init__.py
4
+ backend/app.py
5
+ backend/backend_wallet_api.py
6
+ backend/backtest.py
7
+ backend/brain_db.py
8
+ backend/check_labels.py
9
+ backend/dynamic_params.py
10
+ backend/enterprise_models.py
11
+ backend/eval_model_demo.py
12
+ backend/feedback_engine.py
13
+ backend/intraday_model.py
14
+ backend/llm_analysis.py
15
+ backend/llm_vision_analysis.py
16
+ backend/model.py
17
+ backend/optimizer_agent.py
18
+ backend/reliability_scoring.py
19
+ backend/reproduce_sentiment.py
20
+ backend/sentiment.py
21
+ backend/stock_data.py
22
+ backend/technical_signals.py
23
+ backend/test_intraday_signal.py
24
+ backend/test_sentiment_upgrades.py
25
+ backend/trader.py
26
+ server/__init__.py
27
+ server/app.py
28
+ stocksense_ai.egg-info/PKG-INFO
29
+ stocksense_ai.egg-info/SOURCES.txt
30
+ stocksense_ai.egg-info/dependency_links.txt
31
+ stocksense_ai.egg-info/entry_points.txt
32
+ stocksense_ai.egg-info/requires.txt
33
+ stocksense_ai.egg-info/top_level.txt
stocksense_ai.egg-info/dependency_links.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
stocksense_ai.egg-info/entry_points.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ [console_scripts]
2
+ server = server.app:main
stocksense_ai.egg-info/requires.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ yfinance
4
+ pandas
5
+ numpy
6
+ scikit-learn
7
+ transformers
8
+ requests
9
+ python-dateutil
10
+ ta
11
+ pydantic
12
+ xgboost
13
+ nltk
14
+ google-generativeai
15
+ python-dotenv
16
+ matplotlib
17
+ openenv-core>=0.2.0
18
+ torch>=2.11.0
19
+ openai>=2.31.0
stocksense_ai.egg-info/top_level.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ backend
2
+ server
uv.lock CHANGED
@@ -3570,6 +3570,7 @@ dependencies = [
3570
  { name = "matplotlib" },
3571
  { name = "nltk" },
3572
  { name = "numpy" },
 
3573
  { name = "openenv-core" },
3574
  { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' or python_full_version >= '3.14'" },
3575
  { name = "pandas", version = "3.0.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
@@ -3595,6 +3596,7 @@ requires-dist = [
3595
  { name = "matplotlib" },
3596
  { name = "nltk" },
3597
  { name = "numpy" },
 
3598
  { name = "openenv-core", specifier = ">=0.2.0" },
3599
  { name = "pandas" },
3600
  { name = "pydantic" },
 
3570
  { name = "matplotlib" },
3571
  { name = "nltk" },
3572
  { name = "numpy" },
3573
+ { name = "openai" },
3574
  { name = "openenv-core" },
3575
  { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' or python_full_version >= '3.14'" },
3576
  { name = "pandas", version = "3.0.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and python_full_version < '3.14'" },
 
3596
  { name = "matplotlib" },
3597
  { name = "nltk" },
3598
  { name = "numpy" },
3599
+ { name = "openai", specifier = ">=2.31.0" },
3600
  { name = "openenv-core", specifier = ">=0.2.0" },
3601
  { name = "pandas" },
3602
  { name = "pydantic" },