Download features.py from AcyLa/multi-asset-predictive-model: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/AcyLa/multi-asset-predictive-model/resolve/main/features.py
- Command line
-
hf download hf://AcyLa/multi-asset-predictive-model/features.py
-
curl -L -o features.py https://huggingface.co/AcyLa/multi-asset-predictive-model/resolve/main/features.py
10.1 kB
| """ | |
| Multi-Asset Feature Engineering — 180+ features. | |
| Categories: Nadaraya-Watson, Bollinger (multi-window), Trend, Momentum, | |
| Volatility, Volume, Price Structure, Calendar, Cross-asset correlation. | |
| """ | |
| import pandas as pd, numpy as np, warnings | |
| from ta.trend import SMAIndicator, EMAIndicator, MACD, ADXIndicator, CCIIndicator, IchimokuIndicator | |
| from ta.momentum import RSIIndicator, StochasticOscillator, WilliamsRIndicator, ROCIndicator, AwesomeOscillatorIndicator | |
| from ta.volatility import BollingerBands, AverageTrueRange, KeltnerChannel, DonchianChannel | |
| from ta.volume import OnBalanceVolumeIndicator, MFIIndicator, ChaikinMoneyFlowIndicator | |
| from config import cfg | |
| from nadaraya_watson import add_nadaraya_watson_features | |
| warnings.filterwarnings('ignore') | |
| def add_bollinger_features(df): | |
| close = df['Close'] | |
| for w in cfg.bb_windows: | |
| for mult in cfg.bb_std_mult: | |
| bb = BollingerBands(close=close, window=w, window_dev=mult) | |
| df[f'BB_{w}_{mult}_upper'] = bb.bollinger_hband() | |
| df[f'BB_{w}_{mult}_lower'] = bb.bollinger_lband() | |
| df[f'BB_{w}_{mult}_mid'] = bb.bollinger_mavg() | |
| bb_std = BollingerBands(close=close, window=w, window_dev=2.0) | |
| df[f'BB_{w}_width'] = bb_std.bollinger_wband() | |
| df[f'BB_{w}_pct'] = bb_std.bollinger_pband() | |
| df[f'BB_{w}_squeeze'] = (df[f'BB_{w}_width'] < df[f'BB_{w}_width'].rolling(w*6).min()).astype(int) | |
| df[f'BB_{w}_pctB'] = bb_std.bollinger_pband() / 100 | |
| upper = bb_std.bollinger_hband(); lower = bb_std.bollinger_lband() | |
| df[f'BB_{w}_upper_walk'] = (close >= upper * 0.999).astype(int) | |
| df[f'BB_{w}_lower_walk'] = (close <= lower * 1.001).astype(int) | |
| return df | |
| def add_trend_features(df): | |
| close, high, low = df['Close'], df['High'], df['Low'] | |
| for w in cfg.ema_windows: | |
| df[f'EMA_{w}'] = EMAIndicator(close=close, window=w).ema_indicator() | |
| df[f'Close_vs_EMA_{w}'] = (close - df[f'EMA_{w}']) / df[f'EMA_{w}'] | |
| for w in cfg.sma_windows: | |
| df[f'SMA_{w}'] = SMAIndicator(close=close, window=w).sma_indicator() | |
| df[f'Close_vs_SMA_{w}'] = (close - df[f'SMA_{w}']) / df[f'SMA_{w}'] | |
| ema_cols = [f'EMA_{w}' for w in cfg.ema_windows] | |
| df['EMA_bull_stack'] = 1; df['EMA_bear_stack'] = 1 | |
| for i in range(len(ema_cols)-1): | |
| df['EMA_bull_stack'] &= (df[ema_cols[i]] > df[ema_cols[i+1]]).astype(int) | |
| df['EMA_bear_stack'] &= (df[ema_cols[i]] < df[ema_cols[i+1]]).astype(int) | |
| macd = MACD(close=close, window_fast=cfg.macd_fast, window_slow=cfg.macd_slow, window_sign=cfg.macd_signal) | |
| df['MACD'] = macd.macd(); df['MACD_signal'] = macd.macd_signal(); df['MACD_hist'] = macd.macd_diff() | |
| adx = ADXIndicator(high=high, low=low, close=close, window=14) | |
| df['ADX'] = adx.adx(); df['ADX_plus'] = adx.adx_pos(); df['ADX_minus'] = adx.adx_neg() | |
| df['ADX_trend_strong'] = (df['ADX'] > 25).astype(int) | |
| ich = IchimokuIndicator(high=high, low=low) | |
| df['Ichimoku_a'] = ich.ichimoku_a(); df['Ichimoku_b'] = ich.ichimoku_b() | |
| df['Ichimoku_base'] = ich.ichimoku_base_line(); df['Ichimoku_conv'] = ich.ichimoku_conversion_line() | |
| cloud_top = df[['Ichimoku_a','Ichimoku_b']].max(axis=1); cloud_bot = df[['Ichimoku_a','Ichimoku_b']].min(axis=1) | |
| df['Above_cloud'] = (close > cloud_top).astype(int); df['Below_cloud'] = (close < cloud_bot).astype(int) | |
| return df | |
| def add_momentum_features(df): | |
| close, high, low = df['Close'], df['High'], df['Low'] | |
| for w in cfg.rsi_windows: | |
| df[f'RSI_{w}'] = RSIIndicator(close=close, window=w).rsi() | |
| df[f'RSI_{w}_overbought'] = (df[f'RSI_{w}'] > 70).astype(int) | |
| df[f'RSI_{w}_oversold'] = (df[f'RSI_{w}'] < 30).astype(int) | |
| for w in cfg.stoch_windows: | |
| stoch = StochasticOscillator(high=high, low=low, close=close, window=w) | |
| df[f'Stoch_{w}'] = stoch.stoch(); df[f'Stoch_{w}_signal'] = stoch.stoch_signal() | |
| df['Williams_R_14'] = WilliamsRIndicator(high=high, low=low, close=close, lbp=14).williams_r() | |
| df['ROC_10'] = ROCIndicator(close=close, window=10).roc() | |
| df['ROC_20'] = ROCIndicator(close=close, window=20).roc() | |
| df['CCI_20'] = CCIIndicator(high=high, low=low, close=close, window=20).cci() | |
| 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.atr_windows: | |
| atr = AverageTrueRange(high=high, low=low, close=close, window=w) | |
| df[f'ATR_{w}'] = atr.average_true_range(); df[f'ATR_{w}_pct'] = df[f'ATR_{w}'] / close | |
| kc = KeltnerChannel(high=high, low=low, close=close) | |
| df['KC_upper'] = kc.keltner_channel_hband(); df['KC_lower'] = kc.keltner_channel_lband() | |
| for w in [20, 50]: | |
| dc = DonchianChannel(high=high, low=low, close=close, window=w) | |
| df[f'DC_{w}_upper'] = dc.donchian_channel_hband(); df[f'DC_{w}_lower'] = dc.donchian_channel_lband() | |
| df[f'DC_{w}_width'] = dc.donchian_channel_wband() | |
| rets = close.pct_change() | |
| for w in [10, 20, 60, 120]: | |
| df[f'HistVol_{w}'] = rets.rolling(w).std() | |
| df[f'HistVol_ann_{w}'] = df[f'HistVol_{w}'] * np.sqrt(252) | |
| df['Vol_regime'] = df['HistVol_10'] / df['HistVol_120'] | |
| 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'] = df['OBV'].ewm(span=20).mean() | |
| df['MFI_14'] = MFIIndicator(high=high, low=low, close=close, volume=volume, window=14).money_flow_index() | |
| df['CMF_20'] = ChaikinMoneyFlowIndicator(high=high, low=low, close=close, volume=volume).chaikin_money_flow() | |
| for w in [10, 20, 50]: | |
| 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['Vol_SMA_20'] = volume.rolling(20).mean(); df['Vol_ratio'] = volume / df['Vol_SMA_20'] | |
| 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, 10, 21, 63, 126, 252]: | |
| df[f'Return_{h}'] = close.pct_change(h) | |
| df['LogRet_1'] = np.log(close / close.shift(1)) | |
| body = close - open_; rng = high - low | |
| df['Body_Ratio'] = body / rng.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'] / rng.replace(0, np.nan) | |
| df['Lower_Shadow_Ratio'] = df['Lower_Shadow'] / rng.replace(0, np.nan) | |
| df['HL_Spread'] = (high - low) / close | |
| df['Close_Position'] = (close - low) / (high - low).replace(0, np.nan) | |
| df['Gap'] = (open_ - close.shift(1)) / close.shift(1) | |
| for w in [20, 50, 100, 200]: | |
| df[f'Roll_High_{w}'] = high.rolling(w).max(); df[f'Roll_Low_{w}'] = low.rolling(w).min() | |
| df[f'Dist_High_{w}'] = (close - df[f'Roll_High_{w}']) / df[f'Roll_High_{w}'] | |
| df[f'Dist_Low_{w}'] = (close - df[f'Roll_Low_{w}']) / df[f'Roll_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) | |
| df['Drawdown'] = (close - close.cummax()) / close.cummax() | |
| # Regime | |
| 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'] | |
| return df | |
| def add_calendar_features(df): | |
| if isinstance(df.index, pd.DatetimeIndex): | |
| dow = df.index.dayofweek; month = df.index.month | |
| df['Day_of_Week'] = dow; df['Month'] = month | |
| df['Is_Monday'] = (dow == 0).astype(int); df['Is_Friday'] = (dow == 4).astype(int) | |
| 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 * dow / 5); df['DoW_cos'] = np.cos(2 * np.pi * dow / 5) | |
| df['Month_sin'] = np.sin(2 * np.pi * month / 12); df['Month_cos'] = np.cos(2 * np.pi * month / 12) | |
| return df | |
| def add_cross_asset_features(df, ticker, all_data=None): | |
| """Cross-asset correlations: SPY and GLD as market/gold benchmarks.""" | |
| if all_data is None: | |
| return df | |
| asset_ret = df['Close'].pct_change() | |
| for benchmark in ['SPY', 'GLD']: | |
| if benchmark == ticker or benchmark not in all_data: | |
| continue | |
| bench_ret = all_data[benchmark]['Close'].pct_change().reindex(df.index) | |
| for w in [20, 60, 120]: | |
| df[f'Corr_{benchmark}_{w}'] = asset_ret.rolling(w).corr(bench_ret) | |
| # Beta | |
| for w in [60, 120]: | |
| cov = asset_ret.rolling(w).cov(bench_ret) | |
| var = bench_ret.rolling(w).var() | |
| df[f'Beta_{benchmark}_{w}'] = cov / var | |
| # Benchmark return as feature | |
| for w in [5, 21, 63]: | |
| bench_close = all_data[benchmark]['Close'].reindex(df.index) | |
| df[f'{benchmark}_Return_{w}'] = bench_close.pct_change(w) | |
| return df | |
| def build_all_features(df, ticker=None, all_data=None): | |
| print(f" Building features for {len(df)} bars...") | |
| df = df.copy() | |
| df = add_nadaraya_watson_features(df) | |
| df = add_bollinger_features(df) | |
| 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_calendar_features(df) | |
| if all_data: | |
| df = add_cross_asset_features(df, ticker or cfg.primary_ticker, all_data) | |
| 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) | |
| print(f" Features: {df.shape[1] - 5} engineered columns ({df.shape[1]} total)") | |
| return df | |
| def get_feature_columns(df): | |
| exclude = {'Open', 'High', 'Low', 'Close', 'Volume'} | |
| features = [c for c in df.columns if c not in exclude and not c.startswith('Target_')] | |
| return features | |