-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfeature_engineering.py
More file actions
36 lines (28 loc) · 1.3 KB
/
Copy pathfeature_engineering.py
File metadata and controls
36 lines (28 loc) · 1.3 KB
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
# feature_engineering.py
import sqlite3
import pandas as pd
def extract_and_engineer_features():
conn = sqlite3.connect('store_data.db')
query = "SELECT date, sku, units_sold FROM sales_history ORDER BY date ASC"
df = pd.read_sql_query(query, conn)
conn.close()
# Ensure explicit chronological datetime ordering
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)
# Calendar features
df['day_of_week'] = df['date'].dt.weekday
df['month'] = df['date'].dt.month
df['is_weekend'] = df['day_of_week'].isin([5, 6]).astype(int)
# Lag Features (What did we sell x days ago?)
df['sales_lag_7'] = df['units_sold'].shift(7)
df['sales_lag_14'] = df['units_sold'].shift(14)
# Rolling Statistics (Moving windows)
df['rolling_mean_7'] = df['units_sold'].shift(1).rolling(window=7).mean()
df['rolling_mean_14'] = df['units_sold'].shift(1).rolling(window=14).mean()
# Drop rows containing NaN values generated from chronological shifting steps
df = df.dropna().reset_index(drop=True)
return df
if __name__ == '__main__':
data = extract_and_engineer_features()
print("✅ Phase 2 Complete: Features engineered.")
print(data[['date', 'units_sold', 'rolling_mean_7', 'sales_lag_7']].tail())