File size: 9,963 Bytes
db6a439
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""High-Volatility Feature Engineering — 200+ features."""
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()
    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 with VIXY (vol), QQQ (tech), and BTC-USD if available."""
    if all_data is None:
        return df
    asset_ret = df['Close'].pct_change()
    benchmarks = []
    for b in ['QQQ', 'VIXY', 'GLD']:
        if b != ticker and b in all_data:
            benchmarks.append(b)
    for benchmark in benchmarks:
        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)
        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
        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'}
    return [c for c in df.columns if c not in exclude and not c.startswith('Target_')]