Spaces:
Sleeping
Sleeping
File size: 2,527 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 |
# 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
|