steviebaraik Claude Sonnet 4.6 commited on
Commit
ccfdc3e
·
1 Parent(s): f52660d

Fix: switch portfolio builder from Groq to OpenRouter (no daily token cap)

Browse files

- app/core/config.py: add openrouter_api_key + openrouter_url fields
- app/services/ai_portfolio.py: use OpenRouter (llama-3.3-70b-instruct)
with llama-3.1-8b-instruct fallback — no rate limits hitting demo
- Snapshot capped at top 20 BUY + 5 HOLD (~400 tokens vs 2000+)
- LLM response cached 10min per amount_bucket+risk_profile

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

Files changed (2) hide show
  1. app/core/config.py +5 -1
  2. app/services/ai_portfolio.py +143 -144
app/core/config.py CHANGED
@@ -16,9 +16,13 @@ class Settings(BaseSettings):
16
  supabase_anon_key: str
17
  supabase_service_role_key: str
18
 
19
- # Groq (LLM provider)
20
  groq_api_key: str
21
 
 
 
 
 
22
  # Alpha Vantage
23
  alpha_vantage_api_key: str = ""
24
 
 
16
  supabase_anon_key: str
17
  supabase_service_role_key: str
18
 
19
+ # Groq (LLM provider — advisor streaming)
20
  groq_api_key: str
21
 
22
+ # OpenRouter (portfolio builder — no daily token cap)
23
+ openrouter_api_key: str = ""
24
+ openrouter_url: str = "https://openrouter.ai/api/v1/chat/completions"
25
+
26
  # Alpha Vantage
27
  alpha_vantage_api_key: str = ""
28
 
app/services/ai_portfolio.py CHANGED
@@ -1,178 +1,177 @@
1
  """
2
- AI-powered portfolio builder.
3
 
4
- Uses Groq LLM + live market intelligence to suggest stocks and quantities
5
- based on the user's investment amount and risk tolerance.
 
6
  """
7
 
8
  import json
9
  import logging
 
10
  import httpx
11
  from ..core.config import get_settings
12
 
13
  logger = logging.getLogger(__name__)
14
 
15
- GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
16
- GROQ_MODEL = "llama-3.3-70b-versatile"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
 
19
  def _market_snapshot() -> str:
20
- """Build a concise market snapshot for the LLM from the analytics cache."""
21
  try:
22
- from .analytics import _report_cache, _get_cached_df
23
 
24
  cached, _ = _report_cache
25
  if cached is None:
26
- return "No market data available."
27
 
28
  lines = []
29
 
30
- # All stocks with BUY signal, sorted by confidence
31
- buy_stocks = [
32
- a for a in cached.stock_analyses
33
- if a.technical_signals.composite_signal.value == "BUY"
34
- ]
35
- buy_stocks.sort(key=lambda a: a.technical_signals.confidence_score, reverse=True)
36
-
37
- hold_stocks = [
38
- a for a in cached.stock_analyses
39
- if a.technical_signals.composite_signal.value == "HOLD"
40
- ]
41
- hold_stocks.sort(key=lambda a: a.technical_signals.confidence_score, reverse=True)
42
-
43
- lines.append("=== STOCKS WITH BUY SIGNAL ===")
44
- for a in buy_stocks:
45
- sym = a.symbol.replace(".NS", "")
46
- rm = a.risk_metrics
47
- price = a.technical_signals.current_price
48
- lines.append(
49
- f"- {sym} ({a.company_name}) | Sector: {a.sector} | "
50
- f"Price: {price:.2f} | Confidence: {a.technical_signals.confidence_score:.0f}% | "
51
- f"Sharpe: {rm.sharpe_ratio:.2f} | MaxDD: {rm.max_drawdown:.1%} | "
52
- f"Beta: {rm.beta:.2f} | Vol: {rm.volatility:.1%}"
53
- )
54
-
55
- lines.append("\n=== STOCKS WITH HOLD SIGNAL ===")
56
- for a in hold_stocks[:10]:
57
- sym = a.symbol.replace(".NS", "")
58
- rm = a.risk_metrics
59
- price = a.technical_signals.current_price
60
- lines.append(
61
- f"- {sym} ({a.company_name}) | Sector: {a.sector} | "
62
- f"Price: {price:.2f} | Confidence: {a.technical_signals.confidence_score:.0f}% | "
63
- f"Sharpe: {rm.sharpe_ratio:.2f} | MaxDD: {rm.max_drawdown:.1%} | "
64
- f"Beta: {rm.beta:.2f} | Vol: {rm.volatility:.1%}"
65
- )
66
-
67
- # Sector performance
68
- overview = cached.market_overview
69
- if overview.sector_heatmap:
70
- lines.append("\n=== SECTOR PERFORMANCE ===")
71
- for s in sorted(overview.sector_heatmap, key=lambda x: x.avg_change_pct, reverse=True):
72
- lines.append(f"- {s.sector}: {s.avg_change_pct:+.2f}% ({s.stock_count} stocks)")
73
-
74
- # Anomalies as warnings
75
- if overview.anomaly_alerts:
76
- lines.append("\n=== ANOMALY WARNINGS ===")
77
- for a in overview.anomaly_alerts[:5]:
78
- lines.append(f"- {a.symbol.replace('.NS','')}: {a.description} [{a.severity}]")
79
 
80
  return "\n".join(lines)
81
  except Exception as e:
82
- logger.warning("Failed to build market snapshot: %s", e)
83
- return "Market data temporarily unavailable."
84
 
85
 
86
- SYSTEM_PROMPT = """You are an expert Indian equity portfolio constructor built into PaisaPro.ai.
87
- Your job: given the user's investment amount and risk profile, select the best stocks and allocate quantities to build an optimal portfolio.
88
 
89
  Rules:
90
- - ONLY pick from the stocks listed in the market data provided. Do NOT invent symbols.
91
- - For conservative: prefer high-Sharpe, low-volatility, low-beta stocks. Pick 8-12 stocks. Diversify broadly across sectors.
92
- - For moderate: balanced mix of growth and value. Pick 7-10 stocks. Diversify across at least 4 sectors.
93
- - For aggressive: high-confidence BUY signals with strong momentum. Pick 5-8 stocks. At least 3 sectors.
94
- - IMPORTANT: You MUST pick at least 5 stocks. Spread the allocation, do not over-concentrate.
95
- - Allocate rupee amounts per stock, then calculate quantity = floor(allocation / current_price).
96
- - No single stock should exceed 20% of total investment.
97
- - Use current market prices from the data provided.
98
- - The sum of all allocations must be between 90% and 98% of the investment amount.
99
- - Prioritize stocks with BUY signal first, then HOLD stocks with high Sharpe ratios.
100
-
101
- You MUST respond with ONLY valid JSON in this exact format — no markdown, no explanation outside JSON:
102
- {
103
- "picks": [
104
- {
105
- "symbol": "RELIANCE",
106
- "company_name": "Reliance Industries",
107
- "sector": "Energy",
108
- "current_price": 1234.56,
109
- "quantity": 10,
110
- "allocation": 12345.60,
111
- "weight_pct": 12.3,
112
- "reason": "Strong BUY signal with 78% confidence, low volatility, sector leader"
113
- }
114
- ],
115
- "strategy_summary": "Brief 2-3 sentence summary of the portfolio strategy",
116
- "risk_notes": "Key risks to be aware of",
117
- "expected_sectors": {"Energy": 25.0, "IT": 20.0},
118
- "total_allocated": 95000,
119
- "cash_remaining": 5000
120
- }"""
121
 
122
 
123
  async def ai_build_portfolio(
124
  investment_amount: float,
125
  risk_profile: str = "moderate",
126
  ) -> dict:
127
- """Call the LLM with market data to generate stock picks."""
128
  settings = get_settings()
129
- if not settings.groq_api_key:
130
- raise RuntimeError("Groq API key is not configured.")
131
-
132
- snapshot = _market_snapshot()
133
 
134
- user_prompt = f"""Build me a portfolio with these parameters:
135
- - Investment Amount: Rs {investment_amount:,.0f}
136
- - Risk Profile: {risk_profile.upper()}
137
 
138
- Here is the current market data for Indian stocks:
 
 
 
 
 
139
 
140
- {snapshot}
141
-
142
- Respond with ONLY the JSON object. No markdown fences, no extra text."""
 
 
 
 
 
 
 
 
 
143
 
144
  messages = [
145
  {"role": "system", "content": SYSTEM_PROMPT},
146
  {"role": "user", "content": user_prompt},
147
  ]
148
 
149
- try:
150
- async with httpx.AsyncClient(timeout=45) as client:
151
- resp = await client.post(
152
- GROQ_URL,
153
- headers={
154
- "Authorization": f"Bearer {settings.groq_api_key}",
155
- "Content-Type": "application/json",
156
- },
157
- json={
158
- "model": GROQ_MODEL,
159
- "messages": messages,
160
- "max_tokens": 4096,
161
- "temperature": 0.3, # lower temp for structured output
162
- },
163
- )
164
- resp.raise_for_status()
165
- data = resp.json()
166
- except httpx.HTTPStatusError as exc:
167
- if exc.response.status_code == 429:
168
- raise RuntimeError("Rate limited by Groq. Please wait a moment.")
169
- raise RuntimeError(f"Groq API error: {exc.response.status_code}")
170
- except httpx.RequestError:
171
- raise RuntimeError("Could not reach Groq API. Please try again.")
 
 
 
 
 
172
 
173
  raw = (data["choices"][0]["message"].get("content") or "").strip()
174
 
175
- # Strip markdown fences if present
176
  if raw.startswith("```"):
177
  raw = raw.split("\n", 1)[1] if "\n" in raw else raw[3:]
178
  if raw.endswith("```"):
@@ -183,9 +182,7 @@ Respond with ONLY the JSON object. No markdown fences, no extra text."""
183
  try:
184
  result = json.loads(raw)
185
  except json.JSONDecodeError:
186
- # Try to extract JSON from the response
187
- start = raw.find("{")
188
- end = raw.rfind("}") + 1
189
  if start >= 0 and end > start:
190
  try:
191
  result = json.loads(raw[start:end])
@@ -194,12 +191,10 @@ Respond with ONLY the JSON object. No markdown fences, no extra text."""
194
  else:
195
  raise RuntimeError("AI returned invalid response format. Please try again.")
196
 
197
- # Validate and enrich picks with live prices
198
  from .portfolio import _get_latest_price, _get_stock_meta
199
 
200
- picks = result.get("picks", [])
201
  validated_picks = []
202
- for pick in picks:
203
  sym = pick.get("symbol", "").upper().replace(".NS", "")
204
  if not sym:
205
  continue
@@ -225,21 +220,23 @@ Respond with ONLY the JSON object. No markdown fences, no extra text."""
225
  "daily_change_pct": change,
226
  "quantity": qty,
227
  "allocation": round(price * qty, 2),
228
- "weight_pct": 0, # recalculated below
229
  "reason": pick.get("reason", ""),
230
  })
231
 
232
- # Post-process: scale down if total exceeds budget
 
 
 
233
  total_allocated = sum(p["allocation"] for p in validated_picks)
234
- if total_allocated > investment_amount and validated_picks:
235
- scale = investment_amount * 0.97 / total_allocated # 3% cash buffer
236
  for p in validated_picks:
237
- new_qty = max(1, int(p["quantity"] * scale))
238
- p["quantity"] = new_qty
239
- p["allocation"] = round(p["current_price"] * new_qty, 2)
240
  total_allocated = sum(p["allocation"] for p in validated_picks)
241
 
242
- # Cap any single stock at 25% of total
243
  for p in validated_picks:
244
  max_alloc = investment_amount * 0.25
245
  if p["allocation"] > max_alloc and p["current_price"] > 0:
@@ -247,11 +244,10 @@ Respond with ONLY the JSON object. No markdown fences, no extra text."""
247
  p["allocation"] = round(p["current_price"] * p["quantity"], 2)
248
  total_allocated = sum(p["allocation"] for p in validated_picks)
249
 
250
- # Recalculate weights
251
  for p in validated_picks:
252
  p["weight_pct"] = round(p["allocation"] / investment_amount * 100, 1) if investment_amount > 0 else 0
253
 
254
- return {
255
  "picks": validated_picks,
256
  "strategy_summary": result.get("strategy_summary", ""),
257
  "risk_notes": result.get("risk_notes", ""),
@@ -260,3 +256,6 @@ Respond with ONLY the JSON object. No markdown fences, no extra text."""
260
  "investment_amount": investment_amount,
261
  "risk_profile": risk_profile,
262
  }
 
 
 
 
1
  """
2
+ AI-powered portfolio builder — uses OpenRouter (no daily token cap).
3
 
4
+ Token-budget strategy:
5
+ - Snapshot capped at top 20 BUY + top 5 HOLD stocks
6
+ - LLM response cached 10 min per (amount_bucket, risk_profile)
7
  """
8
 
9
  import json
10
  import logging
11
+ import time
12
  import httpx
13
  from ..core.config import get_settings
14
 
15
  logger = logging.getLogger(__name__)
16
 
17
+ OPENROUTER_MODELS = [
18
+ "meta-llama/llama-3.3-70b-instruct",
19
+ "meta-llama/llama-3.1-8b-instruct",
20
+ ]
21
+
22
+ # Response cache: key → (result_dict, timestamp)
23
+ _build_cache: dict[str, tuple[dict, float]] = {}
24
+ CACHE_TTL = 600 # 10 minutes
25
+
26
+
27
+ def _cache_key(investment_amount: float, risk_profile: str) -> str:
28
+ bucket = round(investment_amount / 50_000) * 50_000
29
+ return f"{bucket}:{risk_profile.lower()}"
30
+
31
+
32
+ def _get_cached_build(key: str) -> dict | None:
33
+ if key in _build_cache:
34
+ result, ts = _build_cache[key]
35
+ if time.time() - ts < CACHE_TTL:
36
+ return result
37
+ del _build_cache[key]
38
+ return None
39
+
40
+
41
+ def _set_cached_build(key: str, result: dict) -> None:
42
+ _build_cache[key] = (result, time.time())
43
 
44
 
45
  def _market_snapshot() -> str:
46
+ """Compact snapshot from analytics cache — top 20 BUY + 5 HOLD only."""
47
  try:
48
+ from .analytics import _report_cache
49
 
50
  cached, _ = _report_cache
51
  if cached is None:
52
+ return ""
53
 
54
  lines = []
55
 
56
+ buy_stocks = sorted(
57
+ [a for a in cached.stock_analyses if a.technical_signals.composite_signal.value == "BUY"],
58
+ key=lambda a: a.technical_signals.confidence_score, reverse=True,
59
+ )[:20]
60
+
61
+ hold_stocks = sorted(
62
+ [a for a in cached.stock_analyses if a.technical_signals.composite_signal.value == "HOLD"],
63
+ key=lambda a: a.technical_signals.confidence_score, reverse=True,
64
+ )[:5]
65
+
66
+ if buy_stocks:
67
+ lines.append("BUY signals:")
68
+ for a in buy_stocks:
69
+ sym = a.symbol.replace(".NS", "")
70
+ price = a.technical_signals.current_price
71
+ lines.append(
72
+ f" {sym} ({a.company_name}) sector={a.sector} "
73
+ f"price={price:.0f} conf={a.technical_signals.confidence_score:.0f}%"
74
+ )
75
+
76
+ if hold_stocks:
77
+ lines.append("HOLD signals (high Sharpe):")
78
+ for a in hold_stocks:
79
+ sym = a.symbol.replace(".NS", "")
80
+ price = a.technical_signals.current_price
81
+ lines.append(
82
+ f" {sym} ({a.company_name}) sector={a.sector} "
83
+ f"price={price:.0f} sharpe={a.risk_metrics.sharpe_ratio:.2f}"
84
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  return "\n".join(lines)
87
  except Exception as e:
88
+ logger.warning("Market snapshot failed: %s", e)
89
+ return ""
90
 
91
 
92
+ SYSTEM_PROMPT = """You are an expert Indian equity portfolio constructor.
93
+ Given an investment amount and risk profile, pick stocks from the provided list and allocate quantities.
94
 
95
  Rules:
96
+ - Only use symbols from the list. Do not invent symbols.
97
+ - Conservative: 8-12 stocks, diversify broadly, prefer stable sectors.
98
+ - Moderate: 7-10 stocks, at least 4 sectors, balanced growth/value.
99
+ - Aggressive: 5-8 stocks, at least 3 sectors, high-confidence BUY picks.
100
+ - No single stock > 20% of total investment.
101
+ - quantity = floor(allocation / current_price).
102
+ - Total allocations must be 90-98% of investment amount.
103
+
104
+ Respond with ONLY valid JSON, no markdown:
105
+ {"picks":[{"symbol":"X","company_name":"Y","sector":"Z","current_price":100.0,"quantity":10,"allocation":1000.0,"weight_pct":10.0,"reason":"..."}],"strategy_summary":"...","risk_notes":"...","total_allocated":95000,"cash_remaining":5000}"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
 
108
  async def ai_build_portfolio(
109
  investment_amount: float,
110
  risk_profile: str = "moderate",
111
  ) -> dict:
112
+ """Build a portfolio using OpenRouter LLM + analytics cache data."""
113
  settings = get_settings()
 
 
 
 
114
 
115
+ if not settings.openrouter_api_key:
116
+ raise RuntimeError("OpenRouter API key is not configured.")
 
117
 
118
+ # Serve from cache if available
119
+ ckey = _cache_key(investment_amount, risk_profile)
120
+ cached_result = _get_cached_build(ckey)
121
+ if cached_result:
122
+ logger.info("Portfolio build served from cache")
123
+ return cached_result
124
 
125
+ snapshot = _market_snapshot()
126
+ if not snapshot:
127
+ raise RuntimeError(
128
+ "Market analysis data is not yet loaded. "
129
+ "Please wait a moment and try again."
130
+ )
131
+
132
+ user_prompt = (
133
+ f"Investment: ₹{investment_amount:,.0f} | Risk: {risk_profile.upper()}\n\n"
134
+ f"Available stocks:\n{snapshot}\n\n"
135
+ "Return ONLY the JSON."
136
+ )
137
 
138
  messages = [
139
  {"role": "system", "content": SYSTEM_PROMPT},
140
  {"role": "user", "content": user_prompt},
141
  ]
142
 
143
+ headers = {
144
+ "Authorization": f"Bearer {settings.openrouter_api_key}",
145
+ "Content-Type": "application/json",
146
+ "HTTP-Referer": "https://stephenbaraik-paisapro.hf.space",
147
+ "X-Title": "PaisaPro AI Advisor",
148
+ }
149
+
150
+ data = None
151
+ for model in OPENROUTER_MODELS:
152
+ try:
153
+ async with httpx.AsyncClient(timeout=60) as client:
154
+ resp = await client.post(
155
+ settings.openrouter_url,
156
+ headers=headers,
157
+ json={"model": model, "messages": messages, "max_tokens": 2048, "temperature": 0.2},
158
+ )
159
+ resp.raise_for_status()
160
+ data = resp.json()
161
+ logger.info("Portfolio built via OpenRouter model: %s", model)
162
+ break
163
+ except httpx.HTTPStatusError as exc:
164
+ logger.warning("OpenRouter %s HTTP %d — trying next", model, exc.response.status_code)
165
+ continue
166
+ except httpx.RequestError as exc:
167
+ raise RuntimeError(f"Could not reach OpenRouter: {exc}")
168
+
169
+ if data is None:
170
+ raise RuntimeError("All OpenRouter models failed. Please try again.")
171
 
172
  raw = (data["choices"][0]["message"].get("content") or "").strip()
173
 
174
+ # Strip markdown fences
175
  if raw.startswith("```"):
176
  raw = raw.split("\n", 1)[1] if "\n" in raw else raw[3:]
177
  if raw.endswith("```"):
 
182
  try:
183
  result = json.loads(raw)
184
  except json.JSONDecodeError:
185
+ start, end = raw.find("{"), raw.rfind("}") + 1
 
 
186
  if start >= 0 and end > start:
187
  try:
188
  result = json.loads(raw[start:end])
 
191
  else:
192
  raise RuntimeError("AI returned invalid response format. Please try again.")
193
 
 
194
  from .portfolio import _get_latest_price, _get_stock_meta
195
 
 
196
  validated_picks = []
197
+ for pick in result.get("picks", []):
198
  sym = pick.get("symbol", "").upper().replace(".NS", "")
199
  if not sym:
200
  continue
 
220
  "daily_change_pct": change,
221
  "quantity": qty,
222
  "allocation": round(price * qty, 2),
223
+ "weight_pct": 0,
224
  "reason": pick.get("reason", ""),
225
  })
226
 
227
+ if not validated_picks:
228
+ raise RuntimeError("AI could not allocate any stocks. Please try again.")
229
+
230
+ # Scale down if over budget
231
  total_allocated = sum(p["allocation"] for p in validated_picks)
232
+ if total_allocated > investment_amount:
233
+ scale = investment_amount * 0.97 / total_allocated
234
  for p in validated_picks:
235
+ p["quantity"] = max(1, int(p["quantity"] * scale))
236
+ p["allocation"] = round(p["current_price"] * p["quantity"], 2)
 
237
  total_allocated = sum(p["allocation"] for p in validated_picks)
238
 
239
+ # Cap single stock at 25%
240
  for p in validated_picks:
241
  max_alloc = investment_amount * 0.25
242
  if p["allocation"] > max_alloc and p["current_price"] > 0:
 
244
  p["allocation"] = round(p["current_price"] * p["quantity"], 2)
245
  total_allocated = sum(p["allocation"] for p in validated_picks)
246
 
 
247
  for p in validated_picks:
248
  p["weight_pct"] = round(p["allocation"] / investment_amount * 100, 1) if investment_amount > 0 else 0
249
 
250
+ final = {
251
  "picks": validated_picks,
252
  "strategy_summary": result.get("strategy_summary", ""),
253
  "risk_notes": result.get("risk_notes", ""),
 
256
  "investment_amount": investment_amount,
257
  "risk_profile": risk_profile,
258
  }
259
+
260
+ _set_cached_build(ckey, final)
261
+ return final