import os import json from feedback_engine import FeedbackEngine from dynamic_params import DynamicParams, KEYS from llm_analysis import _init_gemini # Re-using SDK logic from llm_analysis GEMINI_AVAILABLE = False try: from google import genai as _genai_sdk GEMINI_AVAILABLE = True except ImportError: pass class OptimizerAgent: def __init__(self): self.api_key = os.getenv("GEMINI_API_KEY") self.client = None self.model = "gemini-2.0-flash" 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 run_optimization(self): """ Analyze recent performance and update dynamic parameters. Returns a summary of changes. """ if not self.client: return {"status": "error", "message": "LLM client unavailable"} # 1. Gather Data report = FeedbackEngine.get_accuracy_report(days=7) params = DynamicParams.get_all() if not report: return {"status": "skipped", "reason": "Not enough accuracy data to optimize"} # 2. Build Optimization Prompt prompt = f""" You are an AI ML Optimizer for a stock trading bot. Current Performance Report (last 7 days): {json.dumps(report, indent=2)} Current Dynamic Parameters: {json.dumps(params, indent=2)} Based on the directional accuracy and average moves, suggest improvements to the parameters. - If Accuracy is < 50%, consider increasing BUY_THRESHOLD. - If a certain model (e.g., XGB) is performing significantly better than LSTM, adjust weights. - If Stop Losses (ATR_MULTIPLIER_SL) are hitting too often in volatile markets, adjust them. Respond ONLY with a JSON object of key-value pairs representing ONLY the parameters you want to change: {{ "PARAMETER_KEY": }} """ try: # 3. Get LLM Recommendations response = self.client.models.generate_content( model=self.model, contents=prompt ) text = response.text.strip() if "```" in text: text = text.split("```")[1] if text.startswith("json"): text = text[4:] text = text.strip() updates = json.loads(text) # 4. Apply Updates 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 } except Exception as e: print(f"[Optimizer] Optimization error: {e}") return {"status": "error", "message": str(e)}