Architect a time-series feature engineering lab implementing holiday effects, anomaly…
- User
Architect a time-series feature engineering lab implementing holiday effects, anomaly tags, and leakage tests.
Assistant
Architect a time-series feature engineering lab implementing holiday effects, anomaly tags, and leakage tests.
The user wants a "Time-Series Feature Engineering Lab" that implements specific features:
I need to structure this as an architectural design and implementation guide.
Key Components of the Architecture:
holidays or custom logic to create binary flags or windowing effects (pre/post holiday).Drafting the Class Structure:
TimeSeriesFeatureEngineer:
add_holiday_features(country='US')add_lag_features(lags=[1, 7])add_rolling_features(window=7)AnomalyTagger:
detect_anomalies_zscore(threshold=3)detect_anomalies_stl()LeakageTester:
check_temporal_integrity() (Basic check: ensure indices are sorted).analyze_feature_target_correlation() (Check correlation with future target vs current target? Or simply ensuring rolling windows are trailing not center).Refining the Implementation Details:
holidays (essential for holiday effects).Step-by-Step Implementation Plan:
holidays library. Create an is_holiday column. Advanced: Add "days to nearest holiday".is_anomaly.shift(1) so today's value isn't included in today's feature if we are predicting today.shift(1) in feature creation logic + a visualization of Train/Test split.Let's refine the "Leakage Test" logic. The most practical "test" in a lab is a function that iterates through features and checks if feature[t] depends on target[t+k]. Since we are engineering features, we simply enforce strictly past data.
However, to make it a "Leakage Test", I will implement a function detect_leakage that correlates features with the future target. If corr(feature_t, target_{t+1}) is high, it's fine. If corr(feature_t, target_{t-1}) (predicting the past) is high, it might be leaking if the feature calculation was retrospective.
Actually, a better leakage test is:
Revised Plan:
TimeSeriesLab Class: Main orchestrator.is_holiday, days_to_holiday.rolling_mean, rolling_std (Strictly trailing).anomaly_score, is_anomaly.Code Structure:
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
import holidays
class TimeSeriesLab:
def __init__(self, data):
self.df = data
self.leakage_report = []
def engineer_holiday_effects(self):
# Logic for holidays
pass
def tag_anomalies(self):
# Isolation forest
pass
def validate_leakage(self):
# Check rolling params, temporal splits
pass
Let's make it more comprehensive. I will provide a complete script that the user can run.
holidays lib.min_periods in rolling windows allows leakage (rare but possible).Final Polish: The prompt asks to "Architect". I should provide a class-based architecture diagram/explanation followed by the code.
Modules:
DataSimulator: Generates messy TS data.HolidayFeaturizer: Handles calendar logic.AnomalyDetector: Tags outliers.LeakageValidator: The safety guard.I will write the code to be modular and robust.
Self-Correction during drafting:
Make sure to handle the datetime index correctly. It's the backbone of TS.
The "Leakage Test" should also verify Train/Test split overlap.
Let's write the solution. I'll use Python with Pandas, NumPy, Scikit-Learn, and holidays.
Feature 1: Holiday Effects
is_holiday: Binary.days_until_holiday: Continuous (requires expensive lookups if done naively, optimized with searchsorted).Feature 2: Anomaly Tags
IsolationForest on numeric columns.Feature 3: Leakage Tests
center=False.I will combine these into a cohesive "Lab" script. This architecture defines a modular, class-based system for processing time-series data. It focuses on three critical pillars of production-grade ML systems: Contextual Awareness (Holidays), Data Integrity (Leakage Tests), and Noise Reduction (Anomaly Tagging).
The lab is structured into four main components:
TimeSeriesLab: The orchestrator class that manages the dataframe and the processing pipeline.HolidayFeaturizer: Context-aware feature generation (National holidays, long weekends, bridge days).AnomalyTagger: Statistical identification of outliers for labeling or exclusion.LeakageValidator: A suite of tests to ensure temporal purity and target independence.import pandas as pd
import numpy as np
from datetime import date
import holidays
from sklearn.ensemble import IsolationForest
from scipy.stats import ks_2samp
import matplotlib.pyplot as plt
class HolidayFeaturizer:
"""
Module: Contextual Feature Engineering
Generates features for holidays, bridge days, and windows.
"""
def __init__(self, country='US', years=None):
self.country = country
self.years = years
self.holiday_cache = self._load_holidays()
def _load_holidays(self):
# Cache holidays for efficiency
if not self.years:
# Default to a range if not provided
self.years = range(2020, 2030)
return holidays.CountryHoliday(self.country, years=self.years)
def transform(self, df, date_col='date'):
df = df.copy()
# Ensure datetime
ds = pd.to_datetime(df[date_col]).dt.date
# 1. Binary IsHoliday
df['is_holiday'] = ds.apply(lambda x: x in self.holiday_cache).astype(int)
# 2. Proximity Windows (e.g., days until next holiday)
# Efficient calculation using searchsorted on sorted unique dates
unique_dates = ds.unique()
holiday_dates = sorted([d for d in self.holiday_cache.keys() if d >= min(unique_dates)])
# Map date -> days_to_holiday
# Note: This is a look-ahead. In production, this should be calculated
# purely historically or allow a specific lookahead constant.
date_to_next_hol = {}
for d in unique_dates:
# Find next holiday >= d
future_hols = [h for h in holiday_dates if h >= d]
if future_hols:
date_to_next_hol[d] = (future_hols[0] - d).days
else:
date_to_next_hol[d] = np.nan
df['days_to_holiday'] = ds.map(date_to_next_hol).fillna(-1).astype(int)
return df
class AnomalyTagger:
"""
Module: Noise Reduction / Labeling
Uses Isolation Forest to tag statistical anomalies.
"""
def __init__(self, contamination=0.01, random_state=42):
self.contamination = contamination
self.model = IsolationForest(contamination=contamination, random_state=random_state)
def transform(self, df, feature_cols):
"""
Adds 'anomaly_score' and 'is_anomaly' columns.
"""
df = df.copy()
# Handle NaNs for the purpose of anomaly detection
data = df[feature_cols].fillna(0)
# Fit and predict (-1 is anomaly, 1 is normal)
df['anomaly_label'] = self.model.fit_predict(data)
df['is_anomaly'] = (df['anomaly_label'] == -1).astype(int)
# Scores (lower = more anomalous)
df['anomaly_score'] = self.model.decision_function(data)
# Clean up temp label
df.drop(columns=['anomaly_label'], inplace=True)
return df
class LeakageValidator:
"""
Module: Integrity Assurance
Runs tests to detect data leakage before modeling.
"""
def __init__(self, threshold=0.05):
self.threshold = threshold # Significance level for statistical tests
self.report = {}
def check_temporal_purity(self, df, date_col, train_split_date):
"""
Test: Ensures no future data exists in the past (Shuffle Leak).
"""
train = df[df[date_col] < train_split_date]
test = df[df[date_col] >= train_split_date]
if train.empty or test.empty:
return False, "Train or Test set is empty."
# Check for overlapping timestamps
overlap = set(train[date_col]).intersection(set(test[date_col]))
if len(overlap) > 0:
return False, f"Timestamp leakage detected: {len(overlap)} overlaps."
return True, "Temporal split is pure."
def check_feature_distribution(self, df, feature_cols, date_col, train_split_date):
"""
Test: Kolmogorov-Smirnov test on feature distributions.
If Train and Test distributions are wildly different, it implies
non-stationarity or a leakage in feature engineering (e.g., scaling done globally).
"""
train = df[df[date_col] < train_split_date]
test = df[df[date_col] >= train_split_date]
drift_report = {}
for col in feature_cols:
stat, p_value = ks_2samp(train[col], test[col])
drift_report[col] = {'statistic': stat, 'p_value': p_value}
if p_value < self.threshold:
print(f"Warning: Distribution shift detected in '{col}' (p={p_value:.4f}). Potential leakage or drift.")
return drift_report
def check_target_leakage(self, df, feature_cols, target_col, lag=1):
"""
Test: Correlation of features with FUTURE target.
If a feature predicts the target perfectly without a time shift,
it might be computed using the target (e.g., "Is_Today_High_Revenue").
"""
leakage_suspects = []
# Shift target backwards (looking at future target)
future_target = df[target_col].shift(-lag)
for col in feature_cols:
# We only check if the feature is not the target itself
if col == target_col: continue
corr = df[col].corr(future_target)
# Arbitrary high correlation threshold (e.g., > 0.9)
if abs(corr) > 0.95:
leakage_suspects.append({'feature': col, 'corr_with_future': corr})
return leakage_suspects
class TimeSeriesFeatureLab:
"""
Orchestrator: Manages the data pipeline.
"""
def __init__(self, df, date_col, target_col):
self.raw_df = df.copy()
self.df = df.copy()
self.date_col = date_col
self.target_col = target_col
self.feature_cols = []
def run_pipeline(self, country='US', split_date=None):
print("--- Initializing Feature Engineering Lab ---")
# 1. Sort by time (Mandatory first step)
self.df = self.df.sort_values(self.date_col).reset_index(drop=True)
# 2. Holiday Features
print("Step 1: Engineering Holiday Effects...")
hf = HolidayFeaturizer(country=country)
self.df = hf.transform(self.df, self.date_col)
self.feature_cols.extend(['is_holiday', 'days_to_holiday'])
# 3. Create some standard Lag Features (to test leakage against)
print("Step 2: Creating Lag Features...")
self.df['lag_1'] = self.df[self.target_col].shift(1)
self.df['rolling_mean_7'] = self.df[self.target_col].shift(1).rolling(7).mean()
self.feature_cols.extend(['lag_1', 'rolling_mean_7'])
# 4. Anomaly Tagging
print("Step 3: Tagging Anomalies...")
at = AnomalyTagger(contamination=0.02)
# Use numeric columns for anomaly detection
numeric_cols = self.df.select_dtypes(include=np.number).columns.tolist()
self.df = at.transform(self.df, numeric_cols)
# 5. Leakage Tests
print("Step 4: Running Leakage Validation...")
validator = LeakageValidator()
# 5a. Temporal Purity
valid, msg = validator.check_temporal_purity(self.df, self.date_col, split_date)
print(f" [Temporal Check]: {msg}")
# 5b. Distribution Check (Drift)
# Dropping NaNs created by lags for the test
clean_df = self.df.dropna()
report = validator.check_feature_distribution(clean_df, self.feature_cols, self.date_col, split_date)
# 5c. Target Leakage Check
suspects = validator.check_target_leakage(clean_df, self.feature_cols, self.target_col)
if suspects:
print(f" [Target Leakage Check]: WARNING - High correlation found: {suspects}")
else:
print(" [Target Leakage Check]: Pass.")
return self.df
# ==========================================
# EXECUTION SCRIPT
# ==========================================
def generate_mock_data():
# Create a date range
dates = pd.date_range(start='2023-01-01', end='2023-12-31', freq='D')
# Create synthetic value (trend + seasonality + noise)
trend = np.linspace(0, 50, len(dates))
seasonality = 10 * np.sin(np.linspace(0, 3.14*12, len(dates))) # Yearly cycle
noise = np.random.normal(0, 2, len(dates))
# Add an Anomaly
values = 100 + trend + seasonality + noise
values[150:155] = values[150:155] + 50 # Inject anomaly spike
df = pd.DataFrame({'date': dates, 'value': values})
return df
if __name__ == "__main__":
# 1. Setup Data
data = generate_mock_data()
split_dt = '2023-10-01'
# 2. Initialize Lab
lab = TimeSeriesFeatureLab(data, date_col='date', target_col='value')
# 3. Run Pipeline
processed_df = lab.run_pipeline(country='US', split_date=split_dt)
# 4. Display Results
print("\n--- Lab Output Sample ---")
print(processed_df[['date', 'value', 'is_holiday', 'days_to_holiday', 'is_anomaly', 'lag_1']].tail())
# Show Anomalies
print(f"\nAnomalies detected: {processed_df['is_anomaly'].sum()}")
# Visual check
anomalies = processed_df[processed_df['is_anomaly'] == 1]
plt.figure(figsize=(10, 5))
plt.plot(processed_df['date'], processed_df['value'], label='Value')
plt.scatter(anomalies['date'], anomalies['value'], color='red', label='Anomaly')
plt.title("Time Series Lab Output: Anomalies & Features")
plt.legend()
plt.show()
HolidayFeaturizer)We move beyond simple binary flags. While is_holiday captures the day-of effect, real-world demand often shifts around holidays.
is_holiday: Standard binary feature.days_to_holiday: A continuous feature capturing the "run-up" to an event. This allows models to learn increasing demand before a specific date.AnomalyTagger)We use Isolation Forest rather than simple standard deviation (Z-score) methods.
anomaly_score (continuous measure of "strangeness") and is_anomaly (binary tag).LeakageValidator)This is the safety layer.
Feature_A correlates 0.99 with Target_Next_Week, Feature_A is likely a proxy for the target itself (e.g., "Future Price") and must be removed.TimeSeriesFeatureLab)The orchestrator enforces Strict Temporal Sorting at the start. In tabular ML, shuffling is standard; in Time Series, shuffling destroys the signal and causes leakage. The lab ensures data is always handled in time order.