# file: agent_system/perception_tuned.py import pandas as pd import numpy as np class RegimeClassifierTuned: def __init__(self, fast_window=10, slow_window=50, vol_window=14): # We shortened the windows: 20/50 -> 10/50 for faster reaction self.fast_w = fast_window self.slow_w = slow_window self.vol_w = vol_window def get_current_regime(self, df_slice: pd.DataFrame) -> dict: tags = set() metrics = {} if len(df_slice) < self.slow_w: return {"tags": {"calculating"}, "metrics": {}} prices = df_slice['close'] # 1. USE EMA (Exponential Moving Average) FOR SPEED # EMA weights recent prices higher, reducing lag significantly ema_fast = prices.ewm(span=self.fast_w, adjust=False).mean().iloc[-1] ema_slow = prices.ewm(span=self.slow_w, adjust=False).mean().iloc[-1] current_price = prices.iloc[-1] # Calculate Delta (Percentage spread between EMAs) ema_delta = (ema_fast - ema_slow) / ema_slow metrics['ema_delta'] = ema_delta metrics['ema_fast'] = ema_fast metrics['ema_slow'] = ema_slow # 2. INSTANT VOLATILITY TRIGGER (The "Panic Button") # Instead of waiting for a long-term trend change, check immediate RSI-like stress returns = prices.pct_change() daily_vol = returns.std() recent_vol = returns.tail(5).std() # Look at just the last 5 days metrics['volatility_ratio'] = recent_vol / daily_vol if daily_vol > 0 else 1.0 # 3. LOGIC GATES # A. TREND GATES (EMA Cross) if ema_fast > ema_slow: tags.add("bull_trend") tags.add("momentum") else: tags.add("bear_trend") tags.add("defensive") # This triggers the "Cash" force earlier # B. CRASH GATE (Price vs EMA) # If Price is significantly below the Fast EMA, it's a "Free Fall" if current_price < (ema_fast * 0.95): # 5% drop below fast average tags.add("crash") tags.add("high_vol") tags.discard("momentum") # Kill momentum immediately # C. VOLATILITY GATE # If the last 5 days are 2x more volatile than usual -> PANIC if recent_vol > (daily_vol * 2.0): tags.add("high_vol") tags.add("aggressive_risk") # Or "risk_off" depending on your strategy setup return {"tags": tags, "metrics": metrics}