Spaces:
Sleeping
Sleeping
File size: 17,657 Bytes
d96a847 | 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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | # file: agent_system/brain_mpc.py
"""import numpy as np
import time
class MPCBoltzmannBrain:
def __init__(self, temperature=0.5, cash_bear_energy=1.0,
weight_smoothing_alpha=None,
rebalance_threshold=None,
rebalance_interval_seconds=None):
self.temperature = temperature
self.cash_bear_energy = cash_bear_energy
self.last_primary_trend = None
# Heartbeat-related fields
self._hb_tags_fn = None
# Allocation policy options (optional)
self.weight_smoothing_alpha = (
max(0.0, min(1.0, float(weight_smoothing_alpha)))
if weight_smoothing_alpha is not None else None
)
self.rebalance_threshold = (
max(0.0, float(rebalance_threshold))
if rebalance_threshold is not None else None
)
self.rebalance_interval_seconds = (
max(0.0, float(rebalance_interval_seconds))
if rebalance_interval_seconds is not None else None
)
# Internal allocation state
self._prev_weights = None
self._last_rebalance_ts = None
self._transition_changed = False
def _maybe_transition_alert(self, current):
if current != self.last_primary_trend:
print(f"[Transition Alert] Trend changed: {self.last_primary_trend} -> {current}")
self.last_primary_trend = current
self._transition_changed = True
def get_boltzmann_weights(self, energies):
Compute Boltzmann weights from energies using the current temperature.
Returns a numpy array of weights summing to 1.
energies = np.array(energies, dtype=float)
scaled = -energies / self.temperature
max_scaled = np.max(scaled)
exp_scaled = np.exp(scaled - max_scaled)
sum_exp = np.sum(exp_scaled)
if sum_exp > 0:
weights = exp_scaled / sum_exp
else:
weights = np.ones_like(exp_scaled) / len(exp_scaled)
return weights
def allocate_weights(self, energies, regime_tags=None, now=None):
Compute final weights from energies, applying optional weight smoothing
and scheduled/threshold rebalancing. Rebalancing occurs immediately if a
trend transition just occurred or if 'bear_trend' is active.
Parameters:
- energies: array-like of energy values per force
- regime_tags: optional set/list of tags for current regime
- now: optional timestamp (seconds). Defaults to time.time().
energies = np.array(energies, dtype=float)
target = self.get_boltzmann_weights(energies)
n = len(target)
prev = self._prev_weights
if prev is None or not isinstance(prev, np.ndarray) or len(prev) != n or not np.all(np.isfinite(prev)):
prev = target
now_ts = time.time() if now is None else float(now)
# Rebalance gates
meets_threshold = True
if self.rebalance_threshold is not None:
meets_threshold = np.max(np.abs(target - prev)) >= self.rebalance_threshold
meets_schedule = True
if self.rebalance_interval_seconds is not None and self._last_rebalance_ts is not None:
meets_schedule = (now_ts - self._last_rebalance_ts) >= self.rebalance_interval_seconds
immediate = False
if regime_tags is not None and ("bear_trend" in regime_tags):
immediate = True
if self._transition_changed:
immediate = True
should_update = immediate or meets_threshold or meets_schedule
if should_update:
w_new = target
if self.weight_smoothing_alpha is not None:
alpha = self.weight_smoothing_alpha
w_new = (1.0 - alpha) * prev + alpha * target
s = np.sum(w_new)
if s > 0:
w_new = w_new / s
else:
w_new = target
self._prev_weights = w_new
self._last_rebalance_ts = now_ts
self._transition_changed = False
return w_new
else:
# Keep previous weights
self._prev_weights = prev
return prev
def reset_allocation_state(self):
Reset internal state for smoothing and scheduled/threshold rebalancing.
self._prev_weights = None
self._last_rebalance_ts = None
self._transition_changed = False"""
"""class MPCBoltzmannBrain:
def __init__(self, temperature=1.0):
self.temperature = temperature"""
# brain_mpc.py
"""import numpy as np
class MPCBoltzmannBrain:
def __init__(self, temperature=0.5):
self.T = temperature
def calculate_weights(self, energies):
# Convert list to numpy array
e = np.array(energies)
# 1. Boltzmann Transform (Lower Energy = Higher Probability)
# We use -e because in physics, systems want to move to LOW energy
exp_e = np.exp(-e / self.T)
# 2. Normalization (This makes them sum to 1.0)
weights = exp_e / np.sum(exp_e)
return weights
def calculate_energy(self, query_scores, forces, regime_tags):
Energy (E) = -Reward + (Cost * Lambda)
Lower energy is better.
energies = []
for i, f in enumerate(forces):
# Base reward from LLM Query
reward = query_scores[i]
# Constraint Penalties (The Field)
penalty = 0
if "momentum" in f.tags and "bear_trend" in regime_tags:
penalty += 5.0 # High cost
if "aggressive" in f.tags and "high_vol" in regime_tags:
penalty += 10.0
# Energy = Cost - Reward
energies.append(penalty - reward)
return np.array(energies)
def calculate_energies(self, forces, regime_tags):
#Calculates the energy level for each force based on the current regime.
#'regime_tags' here is just the internal name for the argument.
energies = []
for f in forces:
e = -1.0 # Base reward
# Logic using regime_tags...
if "bear_trend" in regime_tags:
e += 10.0
energies.append(e)
return np.array(energies)
def get_boltzmann_weights(self, energies):
#Converts Energy levels into Allocation Weights.
# Subtract max energy for numerical stability (prevent overflow)
shifted_energies = (energies - np.min(energies)) / self.T
exp_energies = np.exp(-shifted_energies)
return exp_energies / np.sum(exp_energies)"""
import numpy as np
import threading
import time
import logging
from datetime import datetime
class MPCBoltzmannBrain:
def __init__(self, temperature=0.5, cash_bear_energy=1.0,
weight_smoothing_alpha=None,
rebalance_threshold=None,
rebalance_interval_seconds=None):
self.T = temperature
# Energy level to force Cash in bear regimes (lower is better)
self.cash_bear_energy = cash_bear_energy
# Track last primary trend to emit transition alerts only on change
self.last_primary_trend = None
# Heartbeat infrastructure
self._heartbeat_thread = None
self._heartbeat_stop = threading.Event()
self._heartbeat_logger = None
self._heartbeat_log_file = None
# Optional callables for heartbeat
self._hb_portfolio_fn = None
self._hb_conn_fn = None
self._hb_tags_fn = None
# Hysteresis / cooldown for trend transitions
self.transition_confirmation = 3 # require 3 consecutive readings
self.transition_cooldown_seconds = 900 # 15 minutes (tune for backtests)
self._pending_trend = None
self._pending_count = 0
self._last_transition_ts = 0.0
# Allocation policy options (optional)
self.weight_smoothing_alpha = (
max(0.0, min(1.0, float(weight_smoothing_alpha)))
if weight_smoothing_alpha is not None else None
)
self.rebalance_threshold = (
max(0.0, float(rebalance_threshold))
if rebalance_threshold is not None else None
)
self.rebalance_interval_seconds = (
max(0.0, float(rebalance_interval_seconds))
if rebalance_interval_seconds is not None else None
)
# Internal allocation state
self._prev_weights = None
self._last_rebalance_ts = None
self._transition_changed = False
def calculate_energies(self, forces, context):
"""
Calculates the energy level for each force based on the current regime context.
Delegates strict logic to the Force's own .get_energy() method.
"""
tags = context.get('tags', set()) if isinstance(context, dict) else context
# Emit transition alert only when tags change
self._maybe_transition_alert(tags)
energies = []
for f in forces:
try:
# Pass the full context to the Force
e = f.get_energy(context)
except Exception:
e = 0.0 # Default neutral
energies.append(e)
return np.array(energies)
def get_boltzmann_weights(self, energies):
max_energy = np.max(-energies / self.T)
exps = np.exp((-energies / self.T) - max_energy) # Subtract max for numerical stability
weights = exps / np.sum(exps)
return weights
# -------- Helpers: Cash detection and Trend transitions --------
def _is_cash_force(self, f):
"""
Best-effort detection of a Cash force.
Recognizes common patterns: explicit 'is_cash', name, or tags.
"""
try:
if hasattr(f, "is_cash") and bool(getattr(f, "is_cash")):
return True
name = str(getattr(f, "name", "")).lower()
if name in {"cash", "cashforce", "usd", "usdt", "stable"}:
return True
tags = getattr(f, "tags", None)
if tags and any(t in {"cash", "stable", "risk_off"} for t in tags):
return True
except Exception:
pass
return False
def _extract_primary_trend(self, context):
"""
Reduce the regime context to a single primary trend label for alerting.
"""
if context is None:
return "unknown"
tags = context.get('tags', set()) if isinstance(context, dict) else context
if not tags:
return "unknown"
if "bear_trend" in tags:
return "bear_trend"
if "bull_trend" in tags:
return "bull_trend"
return "other"
def _maybe_transition_alert(self, regime_tags):
"""
Print a one-time Transition Alert when the primary trend changes.
"""
current = self._extract_primary_trend(regime_tags)
if self.last_primary_trend is None:
# Initialize state without alert spam
self.last_primary_trend = current
return
if current != self.last_primary_trend:
print(f"[Transition Alert] Trend changed: {self.last_primary_trend} -> {current}")
self.last_primary_trend = current
# -------- Heartbeat logging --------
def _ensure_logger(self, log_file):
if self._heartbeat_logger and self._heartbeat_log_file == log_file:
return self._heartbeat_logger
logger = logging.getLogger("MPCBoltzmannBrainHeartbeat")
logger.setLevel(logging.INFO)
# Avoid adding multiple handlers to the same file
if not any(isinstance(h, logging.FileHandler) and getattr(h, 'baseFilename', None) == log_file for h in logger.handlers):
fh = logging.FileHandler(log_file)
fh.setLevel(logging.INFO)
fmt = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")
fh.setFormatter(fmt)
logger.addHandler(fh)
self._heartbeat_logger = logger
self._heartbeat_log_file = log_file
return logger
def allocate_weights(self, energies, context=None, now=None):
"""
Compute final weights from energies, applying optional weight smoothing
and scheduled/threshold rebalancing.
"""
tags = context.get('tags', set()) if isinstance(context, dict) else (context or set())
energies = np.array(energies, dtype=float)
target = self.get_boltzmann_weights(energies)
n = len(target)
prev = self._prev_weights
if prev is None or not isinstance(prev, np.ndarray) or len(prev) != n or not np.all(np.isfinite(prev)):
prev = target
now_ts = time.time() if now is None else float(now)
# Rebalance gates
meets_threshold = True
if self.rebalance_threshold is not None:
meets_threshold = np.max(np.abs(target - prev)) >= self.rebalance_threshold
meets_schedule = True
if self.rebalance_interval_seconds is not None and self._last_rebalance_ts is not None:
meets_schedule = (now_ts - self._last_rebalance_ts) >= self.rebalance_interval_seconds
immediate = False
if "bear_trend" in tags or "crash" in tags:
immediate = True
if self._transition_changed:
immediate = True
should_update = immediate or meets_threshold or meets_schedule
if should_update:
w_new = target
if self.weight_smoothing_alpha is not None:
alpha = self.weight_smoothing_alpha
w_new = (1.0 - alpha) * prev + alpha * target
s = np.sum(w_new)
if s > 0:
w_new = w_new / s
else:
w_new = target
self._prev_weights = w_new
self._last_rebalance_ts = now_ts
self._transition_changed = False
return w_new
else:
# Keep previous weights
self._prev_weights = prev
return prev
def reset_allocation_state(self):
"""
Reset internal state for smoothing and scheduled/threshold rebalancing.
"""
self._prev_weights = None
self._last_rebalance_ts = None
self._transition_changed = False
def start_heartbeat(self, log_file="mpc_heartbeat.log",
get_portfolio_value=None,
get_connectivity_status=None,
get_current_tags=None,
interval_seconds=1800):
"""
Start a background heartbeat that logs portfolio value, current primary trend,
and connectivity status every `interval_seconds` (default: 30 minutes).
Provide callables for each datum; if omitted, placeholders are used.
"""
self._hb_portfolio_fn = get_portfolio_value
self._hb_conn_fn = get_connectivity_status
self._hb_tags_fn = get_current_tags
logger = self._ensure_logger(log_file)
# If already running, do nothing
if self._heartbeat_thread and self._heartbeat_thread.is_alive():
logger.info("Heartbeat already running.")
return
self._heartbeat_stop.clear()
def loop():
while not self._heartbeat_stop.is_set():
try:
pv = None
if callable(self._hb_portfolio_fn):
pv = self._hb_portfolio_fn()
trend = None
if callable(self._hb_tags_fn):
tags = self._hb_tags_fn()
trend = self._extract_primary_trend(tags)
conn = None
if callable(self._hb_conn_fn):
conn = self._hb_conn_fn()
msg = (
f"Heartbeat | PortfolioValue={pv if pv is not None else 'n/a'} | "
f"Trend={trend if trend is not None else (self.last_primary_trend or 'unknown')} | "
f"Connectivity={conn if conn is not None else 'unknown'}"
)
logger.info(msg)
except Exception as ex:
logger.exception(f"Heartbeat error: {ex}")
finally:
# Sleep in small chunks to allow responsive stop
slept = 0
step = min(5, interval_seconds) # up to 5s steps
while slept < interval_seconds and not self._heartbeat_stop.is_set():
time.sleep(step)
slept += step
self._heartbeat_thread = threading.Thread(target=loop, name="MPCHeartbeat", daemon=True)
self._heartbeat_thread.start()
logger.info(f"Heartbeat started. Logging to {log_file} every {interval_seconds} seconds.")
def stop_heartbeat(self):
"""
Stop the background heartbeat thread, if running.
"""
if self._heartbeat_thread and self._heartbeat_thread.is_alive():
self._heartbeat_stop.set()
self._heartbeat_thread.join(timeout=5)
if self._heartbeat_logger:
self._heartbeat_logger.info("Heartbeat stopped.")
|