File size: 1,872 Bytes
cadf729 | 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 | """
Label Generation — multi-horizon regression, classification, triple-barrier.
All labels are forward-looking; they must NEVER leak into features.
"""
import pandas as pd
import numpy as np
from config import cfg
def add_regression_labels(df):
close = df['Close']
for h in cfg.horizons:
df[f'Target_Return_{h}d'] = close.shift(-h) / close - 1
return df
def add_classification_labels(df):
close = df['Close']
for h in cfg.horizons:
future_ret = close.shift(-h) / close - 1
label = np.where(future_ret > cfg.classification_threshold, 1,
np.where(future_ret < -cfg.classification_threshold, -1, 0))
df[f'Target_Dir_{h}d'] = label
return df
def add_triple_barrier_labels(df, upper=0.03, lower=0.03, max_holding=14):
close = df['Close'].values; high = df['High'].values; low = df['Low'].values
n = len(close); labels = np.full(n, np.nan)
for i in range(n - max_holding):
entry = close[i]; upper_bar = entry * (1 + upper); lower_bar = entry * (1 - lower)
for j in range(1, max_holding + 1):
if i + j >= n: break
if high[i + j] >= upper_bar: labels[i] = 1; break
elif low[i + j] <= lower_bar: labels[i] = -1; break
else:
labels[i] = 0
df['Target_TB'] = labels
return df
def add_volatility_adjusted_labels(df):
close = df['Close']; vol = close.pct_change().rolling(20).std()
for h in cfg.horizons:
future_ret = close.shift(-h) / close - 1
df[f'Target_VolAdj_{h}d'] = future_ret / vol
return df
def add_all_labels(df):
df = add_regression_labels(df)
df = add_classification_labels(df)
df = add_volatility_adjusted_labels(df)
df = add_triple_barrier_labels(df)
return df
def get_label_columns(df):
return [c for c in df.columns if c.startswith('Target_')]
|