File size: 9,088 Bytes
7e1249a | 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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | """Forex Feature Engineering — 180+ features for intraday FX prediction."""
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 [12, 24, 48, 96]:
df[f'HistVol_{w}'] = rets.rolling(w).std()
df[f'HistVol_ann_{w}'] = df[f'HistVol_{w}'] * np.sqrt(252*24)
df['Vol_regime'] = df['HistVol_12'] / df['HistVol_96']
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 [24, 48]:
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, 4, 8, 12, 24, 48, 96]: 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 [24, 48, 96, 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()
return df
def add_session_features(df):
if isinstance(df.index, pd.DatetimeIndex):
hour = df.index.hour; dow = df.index.dayofweek
df['Tokyo_session'] = ((hour >= 0) & (hour < 9)).astype(int)
df['London_session'] = ((hour >= 8) & (hour < 17)).astype(int)
df['NY_session'] = ((hour >= 13) & (hour < 22)).astype(int)
df['London_NY_overlap'] = ((hour >= 13) & (hour < 17)).astype(int)
df['Tokyo_London_overlap'] = ((hour >= 8) & (hour < 9)).astype(int)
df['London_open'] = (hour == 8).astype(int); df['NY_open'] = (hour == 13).astype(int)
df['London_close'] = (hour == 16).astype(int)
df['Day_of_Week'] = dow; df['Is_Monday'] = (dow == 0).astype(int); df['Is_Friday'] = (dow == 4).astype(int)
df['DoW_sin'] = np.sin(2 * np.pi * dow / 5); df['DoW_cos'] = np.cos(2 * np.pi * dow / 5)
df['Hour_sin'] = np.sin(2 * np.pi * hour / 24); df['Hour_cos'] = np.cos(2 * np.pi * hour / 24)
df['Week_open'] = ((dow == 0) & (hour < 2)).astype(int)
return df
def build_all_features(df, ticker=None, other_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_session_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)
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'}
return [c for c in df.columns if c not in exclude]
|