| """
|
| 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.")
|
|
|
|
|
| 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("==================================================")
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
| 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']
|
|
|
| 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
|
|
|
|
|
| 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}")
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
| 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'
|
| })
|
|
|
|
|
| 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
|
|
|
| print(f" -> Lobbying loaded successfully. Shape: {df_lobbying.shape}")
|
|
|
|
|
|
|
|
|
| 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',
|
| time_col_cf: 'time',
|
| 'weight': 'Fin_Amt'
|
| })
|
| df_camp_fin['event_type'] = 2
|
|
|
| print(f" -> Campaign Finance loaded successfully. Shape: {df_camp_fin.shape}")
|
|
|
|
|
|
|
|
|
| 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',
|
| 'release_date': 'time'
|
| })
|
|
|
|
|
| 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}")
|
|
|
|
|
|
|
|
|
| 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("==================================================")
|
|
|
|
|
| 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)
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
| 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)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
|
|
|
|
|
|
|
|
| df['__last_seen'] = df['time']
|
| agg = {c: 'sum' for c in amount_cols if c in df.columns}
|
| agg['time'] = 'min'
|
| agg['__last_seen'] = 'max'
|
| agg['__count'] = 'sum'
|
| df['__count'] = 1.0
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
|
|
|
|
|
|
| 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'])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)}")
|
|
|
|
|
|
|
|
|
|
|
| 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):
|
|
|
| for col in all_msg_cols:
|
| if col not in df.columns:
|
| df[col] = np.float32(0.0)
|
| elif df[col].dtype != 'float32':
|
|
|
| df[col] = df[col].astype('float32')
|
| return df
|
|
|
| print("Aligning D=24 schemas and downcasting to float32...")
|
| df_trades = align_schema(df_trades)
|
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
| 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']
|
|
|
|
|
|
|
| if 'last_seen' not in df_trades.columns:
|
| df_trades['last_seen'] = df_trades['time']
|
|
|
|
|
| datasets = [
|
| ("trades", df_trades),
|
| ("lobbying", df_lobbying),
|
| ("camp_fin", df_camp_fin),
|
| ("geo", df_geo)
|
| ]
|
|
|
|
|
| del df_trades, df_lobbying, df_camp_fin, df_geo
|
| gc.collect()
|
|
|
|
|
| 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
|
|
|
|
|
| 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()
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
| 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')
|
|
|
|
|
| df_chunk = df_chunk[base_cols + all_msg_cols]
|
|
|
|
|
| table = pa.Table.from_pandas(df_chunk)
|
| if writer is None:
|
|
|
| writer = pq.ParquetWriter(out_path, table.schema)
|
| writer.write_table(table)
|
|
|
|
|
| del df_chunk
|
| gc.collect()
|
|
|
| if writer:
|
| writer.close()
|
|
|
| print(f" -> Saved {name} ({len(df_full)} rows) to {out_path}")
|
|
|
|
|
| datasets[i] = None
|
| del df_full
|
| gc.collect()
|
|
|
| print(" -> Master Edge Parquet chunks successfully written.")
|
| print("==================================================\n")
|
|
|
| return output_dir, all_msg_cols
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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("==================================================")
|
|
|
|
|
| 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]) + "]"
|
|
|
|
|
| print(f"Extracting global distinct Node IDs for events >= {start_date}...")
|
| out_dir = "data/processed/pyg_graph"
|
| os.makedirs(out_dir, exist_ok=True)
|
|
|
|
|
| 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)}
|
|
|
|
|
| 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()
|
|
|
|
|
| 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 = []
|
|
|
|
|
| for year in active_years:
|
| print(f"\n--- Processing Shard: {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
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
|
|
|
|
| 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
|
|
|
|
|
| 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
|
|
|
|
|
| is_sorted = torch.all(t_tensor[1:] >= t_tensor[:-1]).item()
|
| assert is_sorted, f"[{year}] Temporal leak detected: Events are not strictly chronological!"
|
|
|
|
|
| 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}")
|
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
| 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)")
|
|
|
|
|
| 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")
|
|
|
| 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()
|
|
|
|
|
| EDGE_DIR = "data/processed/master_edges_parquet"
|
| REQUIRED_EDGES = [
|
| "edges_trades.parquet", "edges_lobbying.parquet",
|
| "edges_camp_fin.parquet", "edges_geo.parquet"
|
| ]
|
|
|
|
|
| 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)
|
|
|
|
|
|
|
|
|
| shard_paths = generate_hillstreet_dataset(
|
| edge_dir=EDGE_DIR,
|
| start_date=args.start_date,
|
| include_structural_edges=args.include_structural_edges
|
| )
|
|
|
|
|
| if args.skip_node_features:
|
| print("\n -> Skipping Phase 3 node-feature generation (--skip_node_features).")
|
| else:
|
|
|
|
|
|
|
| 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") |