""" Feature Engineering Module — 207 causal technical indicators. All features use only data from time t and before (no look-ahead bias). """ import pandas as pd import numpy as np from ta.trend import ( SMAIndicator, EMAIndicator, MACD, ADXIndicator, CCIIndicator, IchimokuIndicator, TRIXIndicator ) from ta.momentum import ( RSIIndicator, StochasticOscillator, WilliamsRIndicator, ROCIndicator, AwesomeOscillatorIndicator, KAMAIndicator ) from ta.volatility import ( BollingerBands, AverageTrueRange, KeltnerChannel, DonchianChannel ) from ta.volume import ( OnBalanceVolumeIndicator, MFIIndicator, VolumeWeightedAveragePrice, AccDistIndexIndicator, ChaikinMoneyFlowIndicator ) from config import cfg import warnings warnings.filterwarnings('ignore') def add_trend_features(df): close, high, low = df['Close'], df['High'], df['Low'] for w in cfg.trend_windows: sma = SMAIndicator(close=close, window=w) ema = EMAIndicator(close=close, window=w) df[f'SMA_{w}'] = sma.sma_indicator() df[f'EMA_{w}'] = ema.ema_indicator() df[f'Close_vs_SMA_{w}'] = (close - df[f'SMA_{w}']) / df[f'SMA_{w}'] df[f'Close_vs_EMA_{w}'] = (close - df[f'EMA_{w}']) / df[f'EMA_{w}'] df[f'SMA_{w}_slope'] = df[f'SMA_{w}'].diff(5) / df[f'SMA_{w}'] macd = MACD(close=close) df['MACD'] = macd.macd(); df['MACD_signal'] = macd.macd_signal() df['MACD_diff'] = macd.macd_diff(); df['MACD_hist'] = macd.macd_diff() adx = ADXIndicator(high=high, low=low, close=close, window=14) df['ADX'] = adx.adx(); df['ADX_pos'] = adx.adx_pos(); df['ADX_neg'] = adx.adx_neg() cci = CCIIndicator(high=high, low=low, close=close, window=20) df['CCI_20'] = cci.cci() ich = IchimokuIndicator(high=high, low=low) df['Ichimoku_a'] = ich.ichimoku_a(); df['Ichimoku_b'] = ich.ichimoku_b() trix = TRIXIndicator(close=close) df['TRIX'] = trix.trix(); df['TRIX_signal'] = df['TRIX'].rolling(9).mean() kama = KAMAIndicator(close=close) df['KAMA'] = kama.kama() return df def add_momentum_features(df): close, high, low = df['Close'], df['High'], df['Low'] for w in cfg.momentum_windows: df[f'RSI_{w}'] = RSIIndicator(close=close, window=w).rsi() stoch = StochasticOscillator(high=high, low=low, close=close, window=w) df[f'Stoch_{w}'] = stoch.stoch(); df[f'Stoch_signal_{w}'] = stoch.stoch_signal() df[f'ROC_{w}'] = ROCIndicator(close=close, window=w).roc() df[f'Williams_R_{w}'] = WilliamsRIndicator(high=high, low=low, close=close, lbp=w).williams_r() df['AO'] = AwesomeOscillatorIndicator(high=high, low=low).awesome_oscillator() return df def add_volatility_features(df): close, high, low = df['Close'], df['High'], df['Low'] for w in cfg.volatility_windows: bb = BollingerBands(close=close, window=w, window_dev=2) df[f'BB_upper_{w}'] = bb.bollinger_hband() df[f'BB_lower_{w}'] = bb.bollinger_lband() df[f'BB_mid_{w}'] = bb.bollinger_mavg() df[f'BB_width_{w}'] = bb.bollinger_wband() df[f'BB_pct_{w}'] = bb.bollinger_pband() atr = AverageTrueRange(high=high, low=low, close=close, window=w) df[f'ATR_{w}'] = atr.average_true_range() df[f'ATR_pct_{w}'] = df[f'ATR_{w}'] / close rets = close.pct_change() df[f'Volatility_{w}'] = rets.rolling(w).std() df[f'Volatility_ann_{w}'] = df[f'Volatility_{w}'] * np.sqrt(365) dc = DonchianChannel(high=high, low=low, close=close, window=w) df[f'DC_upper_{w}'] = dc.donchian_channel_hband() df[f'DC_lower_{w}'] = dc.donchian_channel_lband() df[f'DC_width_{w}'] = dc.donchian_channel_wband() kc = KeltnerChannel(high=high, low=low, close=close) df['KC_upper'] = kc.keltner_channel_hband() df['KC_lower'] = kc.keltner_channel_lband() return df def add_volume_features(df): close, high, low, volume = df['Close'], df['High'], df['Low'], df['Volume'] df['OBV'] = OnBalanceVolumeIndicator(close=close, volume=volume).on_balance_volume() df['OBV_EMA_20'] = df['OBV'].ewm(span=20).mean() for w in [14, 28]: df[f'MFI_{w}'] = MFIIndicator(high=high, low=low, close=close, volume=volume, window=w).money_flow_index() for w in cfg.volume_windows: tp = (high + low + close) / 3 df[f'VWAP_{w}'] = (tp * volume).rolling(w).sum() / volume.rolling(w).sum() df[f'Close_vs_VWAP_{w}'] = (close - df[f'VWAP_{w}']) / df[f'VWAP_{w}'] df[f'Volume_SMA_{w}'] = volume.rolling(w).mean() df[f'Volume_ratio_{w}'] = volume / df[f'Volume_SMA_{w}'] df[f'Volume_std_{w}'] = volume.rolling(w).std() df['AD_line'] = AccDistIndexIndicator(high=high, low=low, close=close, volume=volume).acc_dist_index() df['CMF_20'] = ChaikinMoneyFlowIndicator(high=high, low=low, close=close, volume=volume).chaikin_money_flow() return df def add_price_structure_features(df): close, high, low, open_ = df['Close'], df['High'], df['Low'], df['Open'] for h in [1, 2, 3, 5, 7, 10, 14, 21, 30, 60, 90, 180]: df[f'Return_{h}d'] = close.pct_change(h) df['LogReturn_1d'] = np.log(close / close.shift(1)) for w in [20, 50, 100, 200]: df[f'Rolling_High_{w}'] = high.rolling(w).max() df[f'Rolling_Low_{w}'] = low.rolling(w).min() df[f'Dist_from_High_{w}'] = (close - df[f'Rolling_High_{w}']) / df[f'Rolling_High_{w}'] df[f'Dist_from_Low_{w}'] = (close - df[f'Rolling_Low_{w}']) / df[f'Rolling_Low_{w}'] df['HH_5'] = (high > high.shift(1).rolling(5).max()).astype(int) df['LL_5'] = (low < low.shift(1).rolling(5).min()).astype(int) body = close - open_ range_ = high - low df['Body_Ratio'] = body / range_.replace(0, np.nan) df['Upper_Shadow'] = high - np.maximum(close, open_) df['Lower_Shadow'] = np.minimum(close, open_) - low df['Upper_Shadow_Ratio'] = df['Upper_Shadow'] / range_.replace(0, np.nan) df['Lower_Shadow_Ratio'] = df['Lower_Shadow'] / range_.replace(0, np.nan) df['Gap'] = (open_ - close.shift(1)) / close.shift(1) df['HL_Spread'] = (high - low) / close df['Close_Position'] = (close - low) / (high - low).replace(0, np.nan) return df def add_regime_features(df): close = df['Close'] if 'SMA_50' in df and 'SMA_200' in df: df['Trend_Regime'] = np.where(df['SMA_50'] > df['SMA_200'], 1, -1) df['Trend_Strength'] = (df['SMA_50'] - df['SMA_200']) / df['SMA_200'] short_vol = close.pct_change().rolling(10).std() long_vol = close.pct_change().rolling(100).std() df['Vol_Regime'] = short_vol / long_vol df['Return_Regime_20'] = close.pct_change().rolling(20).mean() df['Return_Regime_50'] = close.pct_change().rolling(50).mean() rolling_max = close.cummax() df['Drawdown'] = (close - rolling_max) / rolling_max df['Drawdown_50d'] = df['Drawdown'].rolling(50).min() return df def add_calendar_features(df): if isinstance(df.index, pd.DatetimeIndex): df['Day_of_Week'] = df.index.dayofweek df['Month'] = df.index.month df['Quarter'] = df.index.quarter df['Is_Month_End'] = df.index.is_month_end.astype(int) df['Is_Quarter_End'] = df.index.is_quarter_end.astype(int) df['DoW_sin'] = np.sin(2 * np.pi * df['Day_of_Week'] / 7) df['DoW_cos'] = np.cos(2 * np.pi * df['Day_of_Week'] / 7) df['Month_sin'] = np.sin(2 * np.pi * df['Month'] / 12) df['Month_cos'] = np.cos(2 * np.pi * df['Month'] / 12) return df def build_all_features(df, btc_data=None): print(f" Building features for {len(df)} rows...") df = df.copy() df = add_trend_features(df) df = add_momentum_features(df) df = add_volatility_features(df) df = add_volume_features(df) df = add_price_structure_features(df) df = add_regime_features(df) df = add_calendar_features(df) df = df.replace([np.inf, -np.inf], np.nan) all_nan = df.columns[df.isna().all()].tolist() if all_nan: df = df.drop(columns=all_nan) n_features = df.shape[1] - 5 print(f" Features: {n_features} engineered columns ({df.shape[1]} total)") return df def get_feature_columns(df): exclude = {'Open', 'High', 'Low', 'Close', 'Volume'} return [c for c in df.columns if c not in exclude]