import os import json from feedback_engine import FeedbackEngine from dynamic_params import DynamicParams, KEYS # Re-using SDK logic from llm_analysis GEMINI_AVAILABLE = False try: from google import genai as _genai_sdk GEMINI_AVAILABLE = True except ImportError: pass # Same model order as llm_analysis.py GEMINI_MODELS = [ "gemini-2.5-flash", "gemini-2.0-flash", "gemini-2.0-flash-lite", "gemini-flash-latest", ] class OptimizerAgent: def __init__(self): self.api_key = os.getenv("GEMINI_API_KEY") self.client = None if GEMINI_AVAILABLE and self.api_key: try: self.client = _genai_sdk.Client(api_key=self.api_key) except Exception as e: print(f"[Optimizer] Init error: {e}") def _call_llm(self, prompt: str) -> str: """Try each model in order, skipping on quota errors. Return raw text or raise.""" if not self.client: raise RuntimeError("Gemini client not initialised — check GEMINI_API_KEY") last_err = None for model in GEMINI_MODELS: try: response = self.client.models.generate_content( model=model, contents=prompt ) print(f"[Optimizer] Used model: {model}") return response.text.strip() except Exception as e: msg = str(e) if "429" in msg or "RESOURCE_EXHAUSTED" in msg: print(f"[Optimizer] {model}: quota exhausted, trying next...") last_err = msg continue elif "404" in msg or "NOT_FOUND" in msg: print(f"[Optimizer] {model}: not found, trying next...") last_err = msg continue else: raise raise RuntimeError(f"All Gemini models quota-exhausted. Last error: {last_err}") def run_optimization(self): """ Analyze recent performance and update dynamic parameters. Falls back to a parameter-sanity review when there is no accuracy data yet. Tries all Gemini model variants before giving up on quota errors. """ if not self.client: return {"status": "error", "message": "LLM client unavailable — check GEMINI_API_KEY"} # 1. Gather Data report = FeedbackEngine.get_accuracy_report(days=7) params = DynamicParams.get_all() # 2. Build Optimization Prompt # When no accuracy data exists yet, do a parameter-sanity warm-start. if report: perf_section = ( f"Current Performance Report (last 7 days):\n{json.dumps(report, indent=2)}\n\n" "Based on the directional accuracy and average moves, suggest improvements:\n" "- If Accuracy < 50%, consider increasing BUY_THRESHOLD.\n" "- If XGB consistently outperforms LSTM, shift WEIGHT_XGB up and WEIGHT_LSTM down.\n" "- If Stop Losses (ATR_MULTIPLIER_SL) hit too often, raise them slightly." ) else: perf_section = ( "No trade history yet — there is no accuracy data to analyse.\n" "Please review the current parameters for sanity and suggest conservative\n" "starting values appropriate for Indian mid-/large-cap intraday trading.\n" "Typical safe ranges:\n" " BUY_THRESHOLD: 60-72 | ATR_MULTIPLIER_SL: 1.2-1.8 | ATR_MULTIPLIER_TP1: 2.0-3.0\n" " MIN_CONFIDENCE: 50-60 | WEIGHT_LSTM: 0.3-0.5 | WEIGHT_XGB: 0.3-0.5 | WEIGHT_SENTIMENT: 0.1-0.2" ) prompt = f"""You are an AI ML Optimizer for a stock trading bot. Current Dynamic Parameters: {json.dumps(params, indent=2)} {perf_section} Respond ONLY with a JSON object of key-value pairs for the parameters you want to change. Do NOT change parameters that are already at good values. Example format: {{"BUY_THRESHOLD": 65, "ATR_MULTIPLIER_SL": 1.5}}""" try: # 3. Call LLM with multi-model fallback text = self._call_llm(prompt) if "```" in text: text = text.split("```")[1] if text.startswith("json"): text = text[4:] text = text.strip() updates = json.loads(text) # 4. Apply Updates (only for known keys) applied = {} for key, val in updates.items(): if key in params: DynamicParams.update(key, val) applied[key] = val return { "status": "success", "updates_applied": applied, "report_summary": report, "note": "No trade history — parameter sanity review applied." if not report else "" } except RuntimeError as e: # Quota or availability error — surface a clean message msg = str(e) print(f"[Optimizer] {msg}") return { "status": "quota_exhausted", "message": "Gemini API daily quota exhausted. Optimization resumes automatically when quota resets (midnight Pacific Time).", "raw": msg[:300] } except Exception as e: print(f"[Optimizer] Optimization error: {e}") return {"status": "error", "message": str(e)}