HillStreetSample / src /temporal_data.py
benroodman's picture
Update src/temporal_data.py
45cedf4 verified
Raw
History Blame Contribute Delete
31.4 kB
"""
src/temporal_data.py
Phase 1: Data Ingestion and Standardization
"""
import pandas as pd
import numpy as np
import os
from sklearn.preprocessing import MultiLabelBinarizer
import pyarrow.parquet as pq
import argparse
import torch
import duckdb
import gc
try:
from torch_geometric.data import TemporalData
except ImportError:
print("[WARNING] torch_geometric not found. Phase 4 will fail without PyG installed.")
# --- Helper for Strict Schema Validation ---
def validate_columns(df: pd.DataFrame, required_columns: list, dataset_name: str):
"""Raises a clear ValueError if expected columns are missing."""
missing = [col for col in required_columns if col not in df.columns]
if missing:
raise ValueError(f"[{dataset_name}] Missing required columns: {missing}\n"
f"Available columns: {list(df.columns)}")
def load_and_standardize_events(data_dir="data"):
"""
PHASE 1: Load the four primary data sources and map them to a unified schema.
Returns standardized pandas DataFrames for each event type.
"""
print("==================================================")
print("PHASE 1: DATA INGESTION & STANDARDIZATION")
print("==================================================")
# ---------------------------------------------------------
# 1.1 TARGET EDGES (Trades)
# ---------------------------------------------------------
path_trades = os.path.join(data_dir, "processed", "ml_dataset_continuous.csv")
print(f"Loading Trades from: {path_trades}")
df_trades = pd.read_csv(path_trades)
# 17 market features + 3 trade mechanics
market_features = [
'vol_20d', 'vol_60d', 'vol_120d', 'vol_252d', 'vol_of_vol_60d', 'vol_trend', 'idio_vol_60d',
'mom_60d', 'mom_252d', 'reversal_21d',
'beta_20d', 'beta_60d', 'downside_beta', 'excess_vol', 'max_dd_60d', 'skew_60d', 'sharpe_60d'
]
trade_features = ['Trade_Size_USD', 'Filing_Gap', 'Transaction'] # Transaction = Buy/Sell Ratio or is_buy
req_trade_cols = ['BioGuideID', 'Matched_Ticker', 'Filed'] + trade_features + market_features
validate_columns(df_trades, req_trade_cols, "Trades")
df_trades = df_trades.rename(columns={
'BioGuideID': 'src',
'Matched_Ticker': 'dst',
'Filed': 'time'
})
df_trades['event_type'] = 0
# Calculate Label: e.g., Top 25% 6M Excess Return = 1.
if 'Excess_Return_6M' in df_trades.columns:
threshold = df_trades['Excess_Return_6M'].quantile(0.75)
df_trades['y'] = (df_trades['Excess_Return_6M'] >= threshold).astype(int)
else:
print("[WARNING] 'Excess_Return_6M' not found. Setting dummy target 'y' = 0")
df_trades['y'] = 0
print(f" -> Trades loaded successfully. Shape: {df_trades.shape}")
# ---------------------------------------------------------
# 1.2 LOBBYING EVENTS
# ---------------------------------------------------------
path_lobbying = os.path.join(data_dir, "processed", "events_lobbying.csv")
print(f"Loading Lobbying from: {path_lobbying}")
df_lobbying = pd.read_csv(path_lobbying)
# Depending on how it was saved, the time column might be 'estimated_filing_date' or 'date'
time_col_lobby = 'estimated_filing_date' if 'estimated_filing_date' in df_lobbying.columns else 'date'
validate_columns(df_lobbying, ['bioguide_id', 'ticker', time_col_lobby, 'event_type'], "Lobbying")
df_lobbying = df_lobbying.rename(columns={
'bioguide_id': 'src',
'ticker': 'dst',
time_col_lobby: 'time'
})
# Extract structural flags
df_lobbying['is_sponsorship'] = (df_lobbying['event_type'] == 'LOBBY_STRONG').astype(float)
df_lobbying['voted_yea'] = (df_lobbying['event_type'] == 'LOBBY_WEAK').astype(float)
df_lobbying['event_type'] = 1 # Override with integer event code
print(f" -> Lobbying loaded successfully. Shape: {df_lobbying.shape}")
# ---------------------------------------------------------
# 1.3 CAMPAIGN FINANCE EVENTS
# ---------------------------------------------------------
path_camp_fin = os.path.join(data_dir, "processed", "events_campaign_finance.csv")
print(f"Loading Campaign Finance from: {path_camp_fin}")
df_camp_fin = pd.read_csv(path_camp_fin)
time_col_cf = 'estimated_filing_date' if 'estimated_filing_date' in df_camp_fin.columns else 'date'
validate_columns(df_camp_fin, ['bioguide_id', 'industry_code', time_col_cf, 'weight'], "Campaign Finance")
df_camp_fin = df_camp_fin.rename(columns={
'bioguide_id': 'src',
'industry_code': 'dst_temp', # Needs broadcasting
time_col_cf: 'time',
'weight': 'Fin_Amt' # Assuming donation amount
})
df_camp_fin['event_type'] = 2
print(f" -> Campaign Finance loaded successfully. Shape: {df_camp_fin.shape}")
# ---------------------------------------------------------
# 1.4 GEO-INDUSTRIAL EVENTS
# ---------------------------------------------------------
path_geo = os.path.join(data_dir, "processed", "events_geographical_industry.csv")
print(f"Loading Geo-Industrial from: {path_geo}")
df_geo = pd.read_csv(path_geo)
validate_columns(df_geo, ['bioguide_id', 'sic_code', 'release_date', 'establishments', 'employment', 'annual_payroll'], "Geo-Industrial")
df_geo = df_geo.rename(columns={
'bioguide_id': 'src',
'sic_code': 'dst_temp', # Needs broadcasting
'release_date': 'time'
})
# Normalizing raw economic weight (log-scaling as per Appendix B.2.3)
df_geo['Geo_Weight'] = np.log1p(df_geo['employment'].fillna(0))
df_geo['event_type'] = 3
print(f" -> Geo-Industrial loaded successfully. Shape: {df_geo.shape}")
# ---------------------------------------------------------
# 1.5 LOAD DICTIONARIES FOR BROADCASTING (Phase 2 Prep)
# ---------------------------------------------------------
print("Loading Crosswalk Dictionaries...")
path_cw_2012 = os.path.join(data_dir, "raw", "industry_codes_NAICS", "2012-NAICS-to-SIC-crosswalk.csv")
path_cw_2017 = os.path.join(data_dir, "raw", "industry_codes_NAICS", "2017-NAICS-to-SIC-crosswalk.csv")
path_cw_cat = os.path.join(data_dir, "raw", "industry_codes_NAICS", "2013-CAT_to_SIC_to_NAICS_mappings.csv")
cw_2012 = pd.read_csv(path_cw_2012)
cw_2017 = pd.read_csv(path_cw_2017)
cw_cat = pd.read_csv(path_cw_cat)
validate_columns(cw_cat, ['OpenSecretsCatcode', 'SICcode'], "CAT to SIC Crosswalk")
print(" -> All Data and Crosswalks successfully ingested.")
print("==================================================\n")
return df_trades, df_lobbying, df_camp_fin, df_geo, cw_2012, cw_2017, cw_cat
def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat, data_dir="data"):
"""
PHASE 2: Memory-Optimized Sector Broadcasting & Tensor Alignment
"""
print("==================================================")
print("PHASE 2: OPTIMIZED BROADCASTING & ALIGNMENT")
print("==================================================")
# 1. Load and Clean Company SIC Master List
path_company_sic = os.path.join(data_dir, "raw", "company_sic_data.csv")
df_comp_sic = pd.read_csv(path_company_sic)
df_comp_sic = df_comp_sic.drop_duplicates(subset=['ticker', 'sic'])
df_comp_sic['sic'] = df_comp_sic['sic'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
# 2. Fix Campaign Finance Mapping (Clean CAT/SIC strings)
df_camp_fin['dst_temp'] = df_camp_fin['dst_temp'].astype(str).str.strip().str.upper()
cw_cat['OpenSecretsCatcode'] = cw_cat['OpenSecretsCatcode'].astype(str).str.strip().str.upper()
cw_cat['SICcode'] = cw_cat['SICcode'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
# ---------------------------------------------------------
# 2.1 THE "BROADCAST" MECHANISM
# ---------------------------------------------------------
print("Broadcasting Geo-Industrial edges...")
df_geo['dst_temp'] = df_geo['dst_temp'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
df_geo = df_geo.merge(df_comp_sic[['sic', 'ticker']], left_on='dst_temp', right_on='sic', how='inner')
df_geo = df_geo.rename(columns={'ticker': 'dst'}).drop(columns=['dst_temp', 'sic'])
print("Broadcasting Campaign Finance edges...")
df_camp_fin = df_camp_fin.merge(cw_cat[['OpenSecretsCatcode', 'SICcode']],
left_on='dst_temp', right_on='OpenSecretsCatcode', how='inner')
df_camp_fin = df_camp_fin.merge(df_comp_sic[['sic', 'ticker']],
left_on='SICcode', right_on='sic', how='inner')
df_camp_fin = df_camp_fin.rename(columns={'ticker': 'dst'}).drop(columns=['dst_temp', 'OpenSecretsCatcode', 'SICcode', 'sic'])
print(f" -> Geo edges (pre-dedup): {len(df_geo)} | Fin edges (pre-dedup): {len(df_camp_fin)}")
# ---------------------------------------------------------
# 2.1b COLLAPSE REPEATED STRUCTURAL EDGES INTO ONE WEIGHTED EDGE
# ---------------------------------------------------------
# Broadcasting (and the raw event streams themselves) emit many duplicate
# (politician, company) pairs of the same type -- e.g. the same company
# lobbying on several of a legislator's bills, or one industry signal fanned
# across every ticker in that industry. Rather than carry each as its own
# edge (which is what blows the edge count into the tens of millions), we keep
# ONE edge per (src, dst, event_type) and accumulate weight onto it:
#
# weight = number of collapsed events (interaction count / intensity)
# <amount cols> = summed across the collapsed events
# time = EARLIEST event (when the relationship began; this is also
# what the chronological sort + shard `t` tensor key on)
# last_seen = MOST RECENT event (carried separately so recency features
# like days-since can be computed independently of edge age)
#
# Trades are intentionally NOT touched here -- each trade is a distinct
# supervised event with its own label and market features.
def collapse_structural(df, name, amount_cols):
"""Dedup to one edge per (src, dst), summing amount_cols, keeping BOTH the
earliest event (as 'time') and the most recent (as 'last_seen').
Adds an 'edge_count' column recording how many events were merged."""
if df.empty:
df['edge_count'] = pd.Series(dtype='float32')
df['last_seen'] = pd.Series(dtype='object')
return df
before = len(df)
df = df.dropna(subset=['src', 'dst', 'time']).copy()
# Earliest -> time, latest -> last_seen. 'time' is min so the downstream
# chronological sort anchors the edge to the start of the relationship;
# 'last_seen' preserves recency for days-since at load time.
df['__last_seen'] = df['time']
agg = {c: 'sum' for c in amount_cols if c in df.columns}
agg['time'] = 'min' # earliest event in the pair
agg['__last_seen'] = 'max' # most recent event in the pair
agg['__count'] = 'sum' # how many events collapsed into this edge
df['__count'] = 1.0
# Carry through any remaining base/identity columns (event_type, y, ...) that
# we are NOT explicitly aggregating. These are constant within a stream
# (event_type is set per-stream in Phase 1; y is -1 on all structural edges),
# so 'first' is exact. Without this, groupby.agg silently drops them and the
# later df_chunk[base_cols + all_msg_cols] selection raises KeyError.
carry_cols = [c for c in ('event_type', 'y')
if c in df.columns and c not in agg]
for c in carry_cols:
agg[c] = 'first'
merged = df.groupby(['src', 'dst'], sort=False, as_index=False).agg(agg)
merged = merged.rename(columns={'__count': 'edge_count', '__last_seen': 'last_seen'})
after = len(merged)
print(f" -> {name}: collapsed {before:,} broadcast edges -> {after:,} "
f"unique (src, dst) edges ({before / max(after, 1):.1f}x reduction).")
return merged
# Each stream's "amount" columns are the numeric msg fields it actually carries.
# Anything not listed is left to the schema-alignment step to zero-fill.
df_lobbying = collapse_structural(
df_lobbying, "Lobbying", amount_cols=['is_sponsorship', 'voted_yea'])
df_camp_fin = collapse_structural(
df_camp_fin, "Campaign Finance", amount_cols=['Fin_Amt'])
df_geo = collapse_structural(
df_geo, "Geo-Industrial", amount_cols=['Geo_Weight'])
# Surface the collapsed-event tally to the model as a weight feature. We fold it
# into Fin_Amt for campaign (already an amount) and leave it as the standalone
# 'edge_count' for the others; node_features.aggregate_pair_edges recomputes its
# own per-pair counts at load time, so this is primarily for inspection/QA, but
# it also means an un-aggregated downstream consumer still sees the intensity.
for _df in (df_lobbying, df_camp_fin, df_geo):
if 'edge_count' not in _df.columns:
_df['edge_count'] = 1.0
print(f" -> Geo edges (post-dedup): {len(df_geo)} | Fin edges (post-dedup): {len(df_camp_fin)} "
f"| Lobbying edges (post-dedup): {len(df_lobbying)}")
# ---------------------------------------------------------
# 2.2 UNIFIED EDGE ATTRIBUTE TENSOR (msg)
# ---------------------------------------------------------
# RESTORED: Map categorical Trade variables to numeric BEFORE downcasting
print("Mapping categorical Trade variables to numeric...")
if df_trades['Transaction'].dtype == object:
df_trades['Transaction'] = df_trades['Transaction'].astype(str).str.lower().apply(
lambda x: 1.0 if 'purchase' in x or 'buy' in x else 0.0
)
size_map = {
'$1,001 - $15,000': 1.0,
'$15,001 - $50,000': 2.0,
'$50,001 - $100,000': 3.0,
'$100,001 - $250,000': 4.0,
'$250,001 - $500,000': 5.0,
'$500,001 - $1,000,000': 6.0,
'$1,000,001 - $5,000,000': 7.0,
'$5,000,001 - $25,000,000': 8.0,
'$25,000,001 - $50,000,000': 9.0,
'Over $50,000,000': 10.0
}
if df_trades['Trade_Size_USD'].dtype == object:
df_trades['Trade_Size_USD'] = df_trades['Trade_Size_USD'].map(size_map).fillna(0.0)
market_features = [
'vol_20d', 'vol_60d', 'vol_120d', 'vol_252d', 'vol_of_vol_60d', 'vol_trend', 'idio_vol_60d',
'mom_60d', 'mom_252d', 'reversal_21d',
'beta_20d', 'beta_60d', 'downside_beta', 'excess_vol', 'max_dd_60d', 'skew_60d', 'sharpe_60d'
]
all_msg_cols = ['Trade_Size_USD', 'Filing_Gap', 'Transaction', 'is_sponsorship', 'voted_yea', 'Fin_Amt', 'Geo_Weight'] + market_features
def align_schema(df):
# Broadcast scalar directly to bypass pandas array-copying overhead
for col in all_msg_cols:
if col not in df.columns:
df[col] = np.float32(0.0)
elif df[col].dtype != 'float32':
# Convert existing columns to float32
df[col] = df[col].astype('float32')
return df
print("Aligning D=24 schemas and downcasting to float32...")
df_trades = align_schema(df_trades)
# 2. Fix the missing target label ('y') for structural edges
df_lobbying['y'] = -1
df_camp_fin['y'] = -1
df_geo['y'] = -1
if 'y' not in df_trades.columns:
df_trades['y'] = -1
df_lobbying['y'] = -1
df_camp_fin['y'] = -1
df_geo['y'] = -1
if 'y' not in df_trades.columns:
df_trades['y'] = -1
# ---------------------------------------------------------
# 3. OUT-OF-CORE ALIGNMENT & PARQUET WRITING
# ---------------------------------------------------------
import gc
import pyarrow as pa
import pyarrow.parquet as pq
output_dir = os.path.join(data_dir, "processed", "master_edges_parquet")
os.makedirs(output_dir, exist_ok=True)
print(f"Writing chunks directly to Parquet at: {output_dir}")
base_cols = ['src', 'dst', 'time', 'last_seen', 'event_type', 'y']
# Trades are not deduped, so they have no 'last_seen'. For an un-collapsed edge
# the relationship's first and last touch are the same instant, so last_seen == time.
if 'last_seen' not in df_trades.columns:
df_trades['last_seen'] = df_trades['time']
# Load unpadded, "skinny" dataframes into the queue
datasets = [
("trades", df_trades),
("lobbying", df_lobbying),
("camp_fin", df_camp_fin),
("geo", df_geo)
]
# Destroy the loose global references immediately
del df_trades, df_lobbying, df_camp_fin, df_geo
gc.collect()
# Process 5 million rows at a time (~480 MB per chunk, extremely safe for RAM)
chunk_size = 5_000_000
for i in range(len(datasets)):
name, df_full = datasets[i]
out_path = os.path.join(output_dir, f"edges_{name}.parquet")
writer = None
# 1. Slice, format, pad, and append in chunks
for start in range(0, len(df_full), chunk_size):
end = min(start + chunk_size, len(df_full))
df_chunk = df_full.iloc[start:end].copy()
# --- MOVED INSIDE THE CHUNK LOOP ---
# Convert to datetime and sort LOCALLY in this 5M row chunk
df_chunk['time'] = pd.to_datetime(df_chunk['time'])
df_chunk['last_seen'] = pd.to_datetime(df_chunk['last_seen'])
df_chunk = df_chunk.sort_values(by='time').reset_index(drop=True)
# -----------------------------------
# Apply schema alignment locally to this small chunk
for col in all_msg_cols:
if col not in df_chunk.columns:
df_chunk[col] = np.float32(0.0)
else:
df_chunk[col] = df_chunk[col].astype('float32')
# Filter down to base + msg cols
df_chunk = df_chunk[base_cols + all_msg_cols]
# Append to Parquet file
table = pa.Table.from_pandas(df_chunk)
if writer is None:
# Initialize the writer with the schema of the first padded chunk
writer = pq.ParquetWriter(out_path, table.schema)
writer.write_table(table)
# Destroy the padded chunk to free RAM
del df_chunk
gc.collect()
if writer:
writer.close()
print(f" -> Saved {name} ({len(df_full)} rows) to {out_path}")
# 2. Destroy the reference to the full dataset before loading the next one
datasets[i] = None
del df_full
gc.collect()
print(" -> Master Edge Parquet chunks successfully written.")
print("==================================================\n")
return output_dir, all_msg_cols
# ==========================================
# PHASE 3: NODE FEATURE EXTRACTION
# ==========================================
# Phase 3 lives in src/data_prep/node_features.py (build_node_features), which
# replicates the deprecated graph_builder composition and aligns the node tensors
# to the Phase-4 node-id maps. It is invoked from __main__ after Phase 4 below.
# ==========================================
# PHASE 4: ASSEMBLY & PYG VALIDATION
# ==========================================
# ==========================================
# PHASE 4: ASSEMBLY & PYG VALIDATION (OUT-OF-CORE)
# ==========================================
# ==========================================
# PHASE 4: OUT-OF-CORE TEMPORAL SHARDING
# ==========================================
def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet", start_date="2012-07-01", include_structural_edges=True):
"""
PHASE 4: Sharded conversion to PyTorch Geometric TemporalData.
Anchored to the true STOCK Act start date: July 2012.
"""
print("==================================================")
print("PHASE 4: OUT-OF-CORE TEMPORAL SHARDING")
print("==================================================")
# 4.1 VALIDATE FILES
edge_files = [
"edges_trades.parquet",
"edges_lobbying.parquet",
"edges_camp_fin.parquet",
"edges_geo.parquet"
]
valid_files = []
for file in edge_files:
file_path = os.path.join(edge_dir, file)
if not os.path.exists(file_path):
print(f" -> [WARNING] Expected edge chunk not found: {file}")
continue
if not include_structural_edges and "trades" not in file:
print(f" -> Skipping structural edge file per config: {file}")
continue
valid_files.append(file_path)
files_sql = "[" + ", ".join([f"'{f}'" for f in valid_files]) + "]"
# 4.2 BUILD GLOBAL NODE ID DICTIONARIES
print(f"Extracting global distinct Node IDs for events >= {start_date}...")
out_dir = "data/processed/pyg_graph"
os.makedirs(out_dir, exist_ok=True)
# Use .df() for DuckDB to avoid the AttributeError
df_src = duckdb.query(f"""
SELECT DISTINCT src FROM read_parquet({files_sql})
WHERE src IS NOT NULL AND time >= '{start_date}'
""").df()
unique_src = df_src['src'].values
src_map = {val: i for i, val in enumerate(unique_src)}
df_dst = duckdb.query(f"""
SELECT DISTINCT dst FROM read_parquet({files_sql})
WHERE dst IS NOT NULL AND time >= '{start_date}'
""").df()
unique_dst = df_dst['dst'].values
dst_start_idx = len(unique_src)
dst_map = {val: i + dst_start_idx for i, val in enumerate(unique_dst)}
# Save mapping for inference/analysis
np.save(os.path.join(out_dir, "src_id_map.npy"), src_map)
np.save(os.path.join(out_dir, "dst_id_map.npy"), dst_map)
print(f" -> Global mapping established: {len(src_map)} Politicians | {len(dst_map)} Companies")
del df_src, df_dst
gc.collect()
# 4.3 DETERMINE ACTIVE YEARS
print("Identifying active years...")
years_df = duckdb.query(f"""
SELECT DISTINCT extract(year from time) as yr
FROM read_parquet({files_sql})
WHERE time >= '{start_date}'
ORDER BY yr
""").df()
active_years = years_df['yr'].dropna().astype(int).tolist()
saved_shards = []
# 4.4 GENERATE YEARLY SHARDS
for year in active_years:
print(f"\n--- Processing Shard: {year} ---")
# Filter for the year, but respect the July 2012 start month for that specific year
query = f"""
SELECT * FROM read_parquet({files_sql})
WHERE extract(year from time) = {year}
AND time >= '{start_date}'
ORDER BY time ASC
"""
master_table = duckdb.query(query).arrow()
if hasattr(master_table, 'read_all'):
master_table = master_table.read_all()
num_rows = master_table.num_rows
if num_rows == 0:
print(f" -> No valid events found for {year} after {start_date}. Skipping.")
continue
print(f" -> Mapping {num_rows:,} events...")
df_ids = master_table.select(['src', 'dst']).to_pandas()
src_idx_array = df_ids['src'].map(src_map).values
dst_idx_array = df_ids['dst'].map(dst_map).values
del df_ids
# Base Tensors (Using long/int64 for standard PyG compatibility)
src_tensor = torch.from_numpy(src_idx_array).to(torch.long)
dst_tensor = torch.from_numpy(dst_idx_array).to(torch.long)
y_tensor = torch.from_numpy(master_table['y'].to_numpy()).to(torch.long)
event_type_tensor = torch.from_numpy(master_table['event_type'].to_numpy()).to(torch.long)
time_array = master_table['time'].to_numpy().astype('datetime64[s]').astype(np.int64)
t_tensor = torch.from_numpy(time_array).to(torch.long)
# Recency endpoint: epoch-seconds of the most recent event in each (collapsed)
# edge. For trades and any un-deduped edge this equals `t`. Kept as its own
# tensor (NOT in msg) so the load path can compute days-since from recency
# while `t` continues to anchor the edge to the start of the relationship.
last_seen_array = master_table['last_seen'].to_numpy().astype('datetime64[s]').astype(np.int64)
last_seen_tensor = torch.from_numpy(last_seen_array).to(torch.long)
# Message Attribute Tensor (D=24)
base_cols = ['src', 'dst', 'time', 'last_seen', 'y', 'event_type']
msg_cols = [c for c in master_table.column_names if c not in base_cols]
msg_tensor = torch.empty((num_rows, len(msg_cols)), dtype=torch.float)
for i, col in enumerate(msg_cols):
arr = master_table[col].combine_chunks().to_numpy(zero_copy_only=False)
msg_tensor[:, i] = torch.from_numpy(arr)
del arr
# Assemble Object
data = TemporalData(
src=src_tensor,
dst=dst_tensor,
t=t_tensor,
msg=msg_tensor,
y=y_tensor
)
data.event_type = event_type_tensor
data.last_seen = last_seen_tensor
# Audit
is_sorted = torch.all(t_tensor[1:] >= t_tensor[:-1]).item()
assert is_sorted, f"[{year}] Temporal leak detected: Events are not strictly chronological!"
# Save Shard
shard_path = os.path.join(out_dir, f"hillstreet_temporal_graph_{year}.pt")
torch.save(data, shard_path)
saved_shards.append(shard_path)
print(f" -> Shard saved successfully: {shard_path}")
# Memory Cleanup
del master_table, src_tensor, dst_tensor, y_tensor, event_type_tensor, t_tensor, last_seen_tensor, msg_tensor, data
gc.collect()
print("\n==================================================")
print(f"PHASE 4 COMPLETE: Generated {len(saved_shards)} annual shards.")
print("==================================================\n")
return saved_shards
# ==========================================
# MAIN ORCHESTRATION & CLI
# ==========================================
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="HillStreet Graph Generation Pipeline")
parser.add_argument("--start_date", type=str, default="2014-01-01", help="Date to start graph inclusion (YYYY-MM-DD)")
# NOTE: previously type=bool, which made "--include_structural_edges False" evaluate
# to True (any non-empty string is truthy). Use a proper boolean flag pair instead.
parser.add_argument("--include_structural_edges", dest="include_structural_edges",
action="store_true", default=True,
help="Include Lobbying, PACs, Geo-Economics (default: on)")
parser.add_argument("--no_structural_edges", dest="include_structural_edges",
action="store_false",
help="Exclude structural edges; keep only trade edges")
# --- Phase 3 node-feature options ---
parser.add_argument("--skip_node_features", action="store_true",
help="Skip Phase 3 node-feature generation (edges/shards only)")
parser.add_argument("--trades_csv", type=str,
default="data/processed/ml_dataset_continuous.csv",
help="Transactions CSV used for performance stats & categorical embeddings")
parser.add_argument("--snapshot_date", type=str, default=None,
help="As-of date for time-varying node features (YYYY-MM-DD). "
"Defaults to the latest event date in the transactions CSV.")
args = parser.parse_args()
# 1. Setup Directories
EDGE_DIR = "data/processed/master_edges_parquet"
REQUIRED_EDGES = [
"edges_trades.parquet", "edges_lobbying.parquet",
"edges_camp_fin.parquet", "edges_geo.parquet"
]
# 2. Check for Phase 1 & 2 Persistence
phase2_done = all(os.path.exists(os.path.join(EDGE_DIR, f)) for f in REQUIRED_EDGES)
if phase2_done:
print(f" -> Found existing edge parquets in {EDGE_DIR}. Skipping Phases 1 & 2.")
schema = pq.read_schema(os.path.join(EDGE_DIR, REQUIRED_EDGES[0]))
base_cols = ['src', 'dst', 'time', 'y', 'event_type']
all_msg_cols = [c for c in schema.names if c not in base_cols]
else:
df_trades, df_lobbying, df_camp_fin, df_geo, cw_2012, cw_2017, cw_cat = load_and_standardize_events()
EDGE_DIR, all_msg_cols = broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat)
# 3. Assembly & PyG Sharding (Phase 4)
# Must run before node features: build_node_features aligns to the node-id maps
# (src_id_map.npy / dst_id_map.npy) that this step writes.
shard_paths = generate_hillstreet_dataset(
edge_dir=EDGE_DIR,
start_date=args.start_date,
include_structural_edges=args.include_structural_edges
)
# 4. Phase 3: Static node features aligned to the Phase-4 maps
if args.skip_node_features:
print("\n -> Skipping Phase 3 node-feature generation (--skip_node_features).")
else:
# Ensure the project root is on sys.path regardless of how this script was
# launched (python src/temporal_data.py vs python -m src.temporal_data).
# __file__ is .../src/temporal_data.py, so two .parent calls reach the root.
import sys
from pathlib import Path as _Path
_project_root = str(_Path(__file__).resolve().parent.parent)
if _project_root not in sys.path:
sys.path.insert(0, _project_root)
from src.data_prep.node_features import build_node_features
build_node_features(
map_dir="data/processed/pyg_graph",
trades_csv=args.trades_csv,
processed_dir="data/processed",
snapshot_date=args.snapshot_date,
)
print(f"\nSUCCESS: HillStreet Generation Pipeline Fully Complete.")
print(f" -> Graph timeline starts: {args.start_date}")
print(f" -> Shards: {len(shard_paths)} files saved to data/processed/pyg_graph/")
if not args.skip_node_features:
print(f" -> Node features: data/processed/node_features_static.pt")