HillStreetSample / src /temporal_data.py
benroodman's picture
Upload 5 files
3609368 verified
raw
history blame
39.5 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.")
# --- CONFIGURATION PANEL ---
CONFIG = {
# 1. Base Directories
"DATA_DIR": "data",
"PROCESSED_DIR": "data/processed",
"EDGE_OUT_DIR": "data/processed/master_edges_parquet",
"PYG_OUT_DIR": "data/processed/pyg_graph",
# 2. Input File Paths (Relative to DATA_DIR)
"FILES": {
"trades": "cropped/ml_dataset_continuous.csv",
"lobbying": "processed/events_lobbying.csv",
"camp_fin": "processed/events_campaign_finance.csv",
"geo": "processed/events_geographical_industry.csv",
"company_sic": "cropped/company_sic_data.csv",
"committee": "cropped/committee_assignments.csv",
"sec_financials": "cropped/sec_quarterly_financials.csv"
},
# 3. Graph Assembly Toggles
"INCLUDE_EDGES": {
"trades": False,
"lobbying": True,
"camp_fin": True,
"geo": True
},
"START_DATE": "2021-01-01"
}
# ---------------------------
# --- 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(CONFIG["DATA_DIR"], CONFIG["FILES"]["trades"])
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
# ---------------------------------------------------------
if CONFIG["INCLUDE_EDGES"].get("lobbying", True):
path_lobbying = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["lobbying"])
df_lobbying = pd.read_csv(path_lobbying)
path_lobbying = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["lobbying"])
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}")
else:
print(" -> [CONFIG] Skipping Lobbying edges...")
df_lobbying = pd.DataFrame()
# ---------------------------------------------------------
# 1.3 CAMPAIGN FINANCE EVENTS
# ---------------------------------------------------------
# ---------------------------------------------------------
if CONFIG["INCLUDE_EDGES"].get("camp_fin", True):
path_camp_fin = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["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}")
else:
print(" -> [CONFIG] Skipping Campaign Finance edges...")
df_camp_fin = pd.DataFrame()
# 1.4 GEO-INDUSTRIAL EDGES
# ---------------------------------------------------------
if CONFIG["INCLUDE_EDGES"].get("geo", True):
path_geo = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["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 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}")
else:
print(" -> [CONFIG] Skipping Geo-Industrial edges...")
df_geo = pd.DataFrame()
# ---------------------------------------------------------
# 1.5 LOAD DICTIONARIES FOR BROADCASTING (Phase 2 Prep)
# ---------------------------------------------------------
print("Loading Crosswalk Dictionaries...")
path_cw_2012 = os.path.join(data_dir, "cropped", "industry_codes_NAICS", "2012-NAICS-to-SIC-crosswalk.csv")
path_cw_2017 = os.path.join(data_dir, "cropped", "industry_codes_NAICS", "2017-NAICS-to-SIC-crosswalk.csv")
path_cw_cat = os.path.join(data_dir, "cropped", "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, "cropped", "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: {len(df_geo)} | Fin edges: {len(df_camp_fin)}")
# ---------------------------------------------------------
# 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 = CONFIG["EDGE_OUT_DIR"]
os.makedirs(output_dir, exist_ok=True)
print(f"Writing chunks directly to Parquet at: {output_dir}")
base_cols = ['src', 'dst', 'time', 'event_type', 'y']
# 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 = 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
# ==========================================
SEC_FACTS = [
"NetIncomeLoss", "StockholdersEquity", "EarningsPerShareBasic",
"EarningsPerShareDiluted", "IncomeTaxExpenseBenefit",
"CashAndCashEquivalentsAtCarryingValue", "WeightedAverageNumberOfSharesOutstandingBasic",
"OperatingIncomeLoss", "WeightedAverageNumberOfDilutedSharesOutstanding",
"Assets", "LiabilitiesAndStockholdersEquity", "InterestExpense",
"RetainedEarningsAccumulatedDeficit", "NetCashProvidedByUsedInOperatingActivities",
"NetCashProvidedByUsedInFinancingActivities", "NetCashProvidedByUsedInInvestingActivities",
"Liabilities", "CommonStockValue", "AccumulatedOtherComprehensiveIncomeLossNetOfTax",
"PropertyPlantAndEquipmentNet", "Revenues", "AssetsCurrent",
"LiabilitiesCurrent", "OperatingExpenses", "GrossProfit",
"PaymentsToAcquirePropertyPlantAndEquipment", "Goodwill",
"AmortizationOfIntangibleAssets", "SellingGeneralAndAdministrativeExpense",
"AccountsPayableCurrent", "CommonStockDividendsPerShareDeclared",
"NonoperatingIncomeExpense", "OtherAssetsNoncurrent",
"AdditionalPaidInCapital", "AccountsReceivableNetCurrent",
"ResearchAndDevelopmentExpense"
]
def map_sic_to_division(sic_code):
"""Maps a 4-digit SIC code to its 10 parent divisions (0-9)."""
try:
sic = int(sic_code)
if sic < 1000: return 0 # Agriculture
elif sic < 1500: return 1 # Mining
elif sic < 1800: return 2 # Construction
elif sic < 4000: return 3 # Manufacturing
elif sic < 5000: return 4 # Transportation/Utilities
elif sic < 5200: return 5 # Wholesale Trade
elif sic < 6000: return 6 # Retail Trade
elif sic < 6800: return 7 # Finance, Insurance, RE
elif sic < 9000: return 8 # Services
else: return 9 # Public Admin
except:
return 9
def process_node_features(data_dir="data/", processed_dir="data/processed/"):
"""
Phase 3: Generate and save temporally aligned node features for politicians and companies.
"""
pol_parquet_path = os.path.join(processed_dir, "politician_features.parquet")
comp_parquet_path = os.path.join(processed_dir, "company_features.parquet")
if os.path.exists(pol_parquet_path) and os.path.exists(comp_parquet_path):
print(" -> Found existing node feature parquets. Skipping Phase 3 generation...")
return pol_parquet_path, comp_parquet_path
print("==================================================")
print("PHASE 3: NODE FEATURE EXTRACTION")
print("==================================================")
# --- Politician Snapshots (x_src) ---
print(" -> Processing Politician Features...")
df_com = pd.read_csv(os.path.join(data_dir, "cropped/committee_assignments.csv"))
df_com['Committees'] = df_com['Committees'].fillna('').astype(str).str.split(r';\s*')
mlb = MultiLabelBinarizer()
encoded_com = mlb.fit_transform(df_com['Committees'])
df_com_encoded = pd.DataFrame(encoded_com, columns=[f"Com_{c}" for c in mlb.classes_])
df_pol = pd.concat([df_com.drop('Committees', axis=1), df_com_encoded], axis=1)
# --- Company Snapshots (x_dst) ---
print(" -> Processing Company Features (SEC & SIC)...")
df_sec = pd.read_csv(os.path.join(data_dir, "cropped/sec_quarterly_financials.csv"))
df_sec['FiledDate'] = pd.to_datetime(df_sec['FiledDate'])
df_sec = df_sec[df_sec['Fact'].isin(SEC_FACTS)]
df_sec = df_sec.drop_duplicates(subset=['Ticker', 'FiledDate', 'Fact'], keep='last')
df_comp = df_sec.pivot(index=['Ticker', 'FiledDate'], columns='Fact', values='Value').reset_index()
for fact in SEC_FACTS:
if fact not in df_comp.columns:
df_comp[fact] = np.nan
df_comp = df_comp[['Ticker', 'FiledDate'] + SEC_FACTS].sort_values(['Ticker', 'FiledDate'])
df_comp = df_comp.groupby('Ticker').ffill().fillna(0.0)
for col in SEC_FACTS:
df_comp[col] = np.sign(df_comp[col]) * np.log1p(np.abs(df_comp[col]))
df_sic = pd.read_csv(os.path.join(data_dir, "cropped/company_sic_data.csv"))
df_sic['sic_division'] = df_sic['sic'].apply(map_sic_to_division)
sic_dummies = pd.get_dummies(df_sic['sic_division'], prefix='SIC_Div')
for i in range(10):
if f'SIC_Div_{i}' not in sic_dummies.columns:
sic_dummies[f'SIC_Div_{i}'] = 0
df_sic = pd.concat([df_sic[['ticker']], sic_dummies[[f'SIC_Div_{i}' for i in range(10)]].astype(np.float32)], axis=1)
df_sic = df_sic.rename(columns={'ticker': 'Ticker'})
df_comp = df_comp.merge(df_sic, on='Ticker', how='left')
sic_cols = [f'SIC_Div_{i}' for i in range(10)]
df_comp[sic_cols] = df_comp[sic_cols].fillna(0.0)
print(" -> Saving Phase 3 Parquets...")
df_pol.to_parquet(pol_parquet_path)
df_comp.to_parquet(comp_parquet_path)
return pol_parquet_path, comp_parquet_path
# ==========================================
# PHASE 3: NODE FEATURE EXTRACTION
# ==========================================
SEC_FACTS = [
"NetIncomeLoss", "StockholdersEquity", "EarningsPerShareBasic",
"EarningsPerShareDiluted", "IncomeTaxExpenseBenefit",
"CashAndCashEquivalentsAtCarryingValue", "WeightedAverageNumberOfSharesOutstandingBasic",
"OperatingIncomeLoss", "WeightedAverageNumberOfDilutedSharesOutstanding",
"Assets", "LiabilitiesAndStockholdersEquity", "InterestExpense",
"RetainedEarningsAccumulatedDeficit", "NetCashProvidedByUsedInOperatingActivities",
"NetCashProvidedByUsedInFinancingActivities", "NetCashProvidedByUsedInInvestingActivities",
"Liabilities", "CommonStockValue", "AccumulatedOtherComprehensiveIncomeLossNetOfTax",
"PropertyPlantAndEquipmentNet", "Revenues", "AssetsCurrent",
"LiabilitiesCurrent", "OperatingExpenses", "GrossProfit",
"PaymentsToAcquirePropertyPlantAndEquipment", "Goodwill",
"AmortizationOfIntangibleAssets", "SellingGeneralAndAdministrativeExpense",
"AccountsPayableCurrent", "CommonStockDividendsPerShareDeclared",
"NonoperatingIncomeExpense", "OtherAssetsNoncurrent",
"AdditionalPaidInCapital", "AccountsReceivableNetCurrent",
"ResearchAndDevelopmentExpense"
]
def map_sic_to_division(sic_code):
"""Maps a 4-digit SIC code to its 10 parent divisions (0-9)."""
try:
sic = int(sic_code)
if sic < 1000: return 0 # Agriculture
elif sic < 1500: return 1 # Mining
elif sic < 1800: return 2 # Construction
elif sic < 4000: return 3 # Manufacturing
elif sic < 5000: return 4 # Transportation/Utilities
elif sic < 5200: return 5 # Wholesale Trade
elif sic < 6000: return 6 # Retail Trade
elif sic < 6800: return 7 # Finance, Insurance, RE
elif sic < 9000: return 8 # Services
else: return 9 # Public Admin
except:
return 9
# --- Constants & Configurations ---
CBP_RELEASE_DATES = {
2023: "2025-06-26", 2022: "2024-06-27", 2021: "2023-04-20",
2020: "2022-04-28", 2019: "2021-04-22", 2018: "2020-06-25",
2017: "2019-11-21", 2016: "2018-04-19", 2015: "2017-04-20",
2014: "2016-04-24", 2013: "2015-04-23", 2012: "2014-05-29",
2011: "2013-04-30", 2010: "2012-06-26"
}
STATE_ABBREV = {
'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA',
'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA',
'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA',
'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD',
'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH',
'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC',
'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA',
'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN',
'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA',
'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY', 'District of Columbia': 'DC'
}
# (Keep SEC_FACTS list and map_sic_to_division helper exactly as you had them)
def process_node_features(data_dir="data/", processed_dir="data/processed/"):
"""Phase 3: Generate and save standardized node features."""
import re
pol_path = os.path.join(processed_dir, "politician_features.parquet")
comp_path = os.path.join(processed_dir, "company_features.parquet")
cbp_out_path = os.path.join(processed_dir, "district_economics_cbp.parquet")
if all(os.path.exists(p) for p in [pol_path, comp_path, cbp_out_path]):
print(" -> Found all node feature parquets. Skipping Phase 3...")
return pol_path, comp_path
print("==================================================")
print("PHASE 3: NODE FEATURE EXTRACTION")
print("==================================================")
# --- 1. POLITICIAN STATIC (Committees & Party) ---
print(" -> Processing Politician Static Features...")
df_com = pd.read_csv(os.path.join(data_dir, "cropped/committee_assignments.csv"))
df_com['Committees'] = df_com['Committees'].fillna('').astype(str).str.split(r';\s*')
mlb = MultiLabelBinarizer()
encoded_com = mlb.fit_transform(df_com['Committees'])
df_pol_static = pd.concat([df_com.drop('Committees', axis=1),
pd.DataFrame(encoded_com, columns=[f"Com_{c}" for c in mlb.classes_])], axis=1)
df_pol_static['District_Num'] = df_pol_static['District'].astype(str).str.extract(r'(\d+)').fillna('0')
# --- 2. DISTRICT ECONOMICS (NAICS Schema-Agnostic) ---
print(" -> Processing CBP District Economics (Handling 2012/2017 NAICS Schema)...")
cbp_dir = os.path.join(data_dir, "cropped/district_industries")
cbp_dfs = []
# Nested helper to parse "Congressional District 1 (119th Congress), Alabama"
def _parse_geo(name):
try:
match = re.search(r'(?:District\s|at Large)(\d+)?.*?,\s*(.*)', str(name))
if match:
dist = match.group(1) if match.group(1) else '0'
state = STATE_ABBREV.get(match.group(2).strip(), 'XX')
return state, str(int(dist))
except: pass
return "XX", "-1"
for year, release_date in CBP_RELEASE_DATES.items():
file_name = f"{year}_CB_estimates.csv" if year <= 2012 else f"{year}_CB_esurvey.csv"
file_path = os.path.join(cbp_dir, file_name)
if not os.path.exists(file_path): continue
df_year = pd.read_csv(file_path, low_memory=False)
df_year.columns = [c.split('(')[-1].replace(')', '').strip() if '(' in c else c for c in df_year.columns]
# Dynamically grabs NAICS2012 or NAICS2017
naics_col = next((c for c in df_year.columns if 'NAICS' in c), None)
if not naics_col: continue
df_year = df_year[['NAME', naics_col, 'EMP']].copy()
df_year.rename(columns={naics_col: 'Sector_Raw'}, inplace=True)
df_year['EMP'] = pd.to_numeric(df_year['EMP'], errors='coerce').fillna(0)
df_year['ReleaseDate'] = pd.to_datetime(release_date)
# Explicitly call the nested _parse_geo function
df_year[['State', 'District']] = pd.DataFrame(df_year['NAME'].apply(_parse_geo).tolist(), index=df_year.index)
df_year['Sector'] = df_year['Sector_Raw'].astype(str).str[:2]
cbp_dfs.append(df_year)
if cbp_dfs:
df_cbp = pd.concat(cbp_dfs, ignore_index=True)
df_cbp_pivot = df_cbp.pivot_table(index=['State', 'District', 'ReleaseDate'],
columns='Sector', values='EMP', aggfunc='sum').reset_index()
# Forward fill 24-dim economics vector
df_cbp_pivot = df_cbp_pivot.sort_values(['State', 'District', 'ReleaseDate'])
sector_cols = [c for c in df_cbp_pivot.columns if c not in ['State', 'District', 'ReleaseDate']]
# Prefix the NAICS columns for clarity
df_cbp_pivot.rename(columns={c: f"NAICS_EMP_{c}" for c in sector_cols}, inplace=True)
naics_prefixed = [f"NAICS_EMP_{c}" for c in sector_cols]
df_cbp_pivot[naics_prefixed] = df_cbp_pivot.groupby(['State', 'District'])[naics_prefixed].ffill().fillna(0.0)
df_cbp_pivot.to_parquet(cbp_out_path)
print(f" -> Saved District Economics (Dims: {len(naics_prefixed)})")
# --- 3. COMPANY SNAPSHOTS (SEC & SIC) ---
print(" -> Processing Company Features (SEC & SIC)...")
df_sec = pd.read_csv(os.path.join(data_dir, "cropped/sec_quarterly_financials.csv"))
df_sec['FiledDate'] = pd.to_datetime(df_sec['FiledDate'])
df_sec = df_sec[df_sec['Fact'].isin(SEC_FACTS)].drop_duplicates(subset=['Ticker', 'FiledDate', 'Fact'], keep='last')
df_comp = df_sec.pivot(index=['Ticker', 'FiledDate'], columns='Fact', values='Value').reset_index()
for fact in SEC_FACTS:
if fact not in df_comp.columns: df_comp[fact] = np.nan
df_comp = df_comp[['Ticker', 'FiledDate'] + SEC_FACTS].sort_values(['Ticker', 'FiledDate'])
df_comp[SEC_FACTS] = df_comp.groupby('Ticker')[SEC_FACTS].ffill().fillna(0.0)
for col in SEC_FACTS:
df_comp[col] = np.sign(df_comp[col]) * np.log1p(np.abs(df_comp[col]))
df_sic = pd.read_csv(os.path.join(data_dir, "cropped/company_sic_data.csv"))
df_sic['sic_division'] = df_sic['sic'].apply(map_sic_to_division)
sic_dummies = pd.get_dummies(df_sic['sic_division'], prefix='SIC_Div')
for i in range(10):
if f'SIC_Div_{i}' not in sic_dummies.columns: sic_dummies[f'SIC_Div_{i}'] = 0
df_sic_proc = pd.concat([df_sic[['ticker']], sic_dummies[[f'SIC_Div_{i}' for i in range(10)]]], axis=1).rename(columns={'ticker': 'Ticker'})
df_comp = df_comp.merge(df_sic_proc, on='Ticker', how='left').fillna(0.0)
# SAVE ALL
print(" -> Saving Phase 3 Parquets...")
df_pol_static.to_parquet(pol_path)
df_comp.to_parquet(comp_path)
return pol_path, comp_path
# ==========================================
# 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 = []
# Map filenames to their config keys
edge_map = {
"edges_trades.parquet": "trades",
"edges_lobbying.parquet": "lobbying",
"edges_camp_fin.parquet": "camp_fin",
"edges_geo.parquet": "geo"
}
for file in edge_files:
config_key = edge_map[file]
# Check the toggle in CONFIG
if not CONFIG["INCLUDE_EDGES"].get(config_key, True):
print(f" -> Skipping '{config_key}' edge file per config.")
continue
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
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)
# Message Attribute Tensor (D=24)
base_cols = ['src', 'dst', 'time', '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
# 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, 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__":
# 1. Setup Directories from CONFIG
EDGE_DIR = CONFIG["EDGE_OUT_DIR"]
os.makedirs(EDGE_DIR, exist_ok=True)
# Check which edges are required based on the toggle panel
REQUIRED_EDGES = []
if CONFIG["INCLUDE_EDGES"].get("trades", True): REQUIRED_EDGES.append("edges_trades.parquet")
if CONFIG["INCLUDE_EDGES"].get("lobbying", True): REQUIRED_EDGES.append("edges_lobbying.parquet")
if CONFIG["INCLUDE_EDGES"].get("camp_fin", True): REQUIRED_EDGES.append("edges_camp_fin.parquet")
if CONFIG["INCLUDE_EDGES"].get("geo", True): REQUIRED_EDGES.append("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) and len(REQUIRED_EDGES) > 0
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. Process Node Features
pol_feat_path, comp_feat_path = process_node_features()
# 4. Generate Final PyG Dataset using the START_DATE from CONFIG
shards_generated = generate_hillstreet_dataset(
start_date=CONFIG["START_DATE"],
)
print(f"Successfully generated the following shards:\n{shards_generated}")