File size: 3,131 Bytes
e2bee6b | 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 | 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": <new_value>
}}
"""
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)}
|