forex-predictive-model / features.py
AcyLa's picture
Upload features.py with huggingface_hub
7e1249a verified
Raw History Blame Contribute Delete
9.09 kB
"""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]