# file: agent_system/perception.py import numpy as np import pandas as pd class RegimeClassifier: def __init__(self, short_window=50, long_window=200, vol_window=20): self.short_w = short_window self.long_w = long_window self.vol_w = vol_window def get_current_regime(self, prices_history: pd.DataFrame) -> set: """ Analyzes the last N candles to determine the current market 'Field'. :param prices_history: DataFrame containing ['close'] :return: A set of strings (e.g., {'bull_trend', 'high_vol'}) """ tags = set() # Ensure we have enough data if len(prices_history) < self.long_w: return {"calculating..."} # 1. CALCULATE INDICATORS # Trend prices = prices_history['close'] sma_short = prices.rolling(window=self.short_w).mean().iloc[-1] sma_long = prices.rolling(window=self.long_w).mean().iloc[-1] current_price = prices.iloc[-1] # Volatility (Standard Deviation of log returns) returns = prices.pct_change() current_vol = returns.rolling(window=self.vol_w).std().iloc[-1] mean_vol = returns.rolling(window=self.long_w).std().iloc[-1] # Shock (Z-Score of today's return) last_return = returns.iloc[-1] z_score = (last_return - returns.rolling(window=self.vol_w).mean().iloc[-1]) / \ (current_vol + 1e-6) # Avoid division by zero # 2. CLASSIFY REGIMES (The "Logic Gates") # --- TREND GATES --- if current_price > sma_short > sma_long: tags.add("bull_trend") tags.add("momentum") elif current_price < sma_short < sma_long: tags.add("bear_trend") tags.add("defensive") else: tags.add("chop") tags.add("mean_reversion") # --- VOLATILITY GATES --- # If current volatility is 1.5x the long-term average if current_vol > (mean_vol * 1.5): tags.add("high_vol") tags.add("aggressive_risk") elif current_vol < (mean_vol * 0.8): tags.add("low_vol") else: tags.add("mid_vol") # --- BLACK SWAN GATE --- # If today's move is a 3-Sigma event (3 Standard Deviations) if z_score < -3.0: tags.add("black_swan") tags.add("crash") elif z_score > 3.0: tags.add("euphoria") # Extreme upside panic return tags