Spaces:
Sleeping
Sleeping
File size: 5,519 Bytes
e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 e2bee6b c165635 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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | 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)}
|