Update src/temporal_data.py
Browse filesRefactor temporal_data: CLI-driven runs, edge collapsing, and aligned node features
Replace the hardcoded CONFIG panel with an argparse CLI and rework the
structural-edge and node-feature handling.
Interface & config
- Drop the top-of-file CONFIG dict in favor of argparse:
--start_date (default 2014-01-01), --include_structural_edges /
--no_structural_edges, --skip_node_features, --trades_csv
(default data/processed/ml_dataset_continuous.csv), --snapshot_date.
- Fix the boolean-flag bug: the old "--include_structural_edges False"
evaluated truthy (any non-empty string); now a proper store_true/
store_false pair.
- Restore trade edges as the primary supervised edge type (event_type 0);
structural edges (lobbying/campaign/geo) are on by default and gated by
the flag pair rather than a per-file CONFIG toggle.
Input paths
- Read trades from data/processed/ml_dataset_continuous.csv and crosswalks/
company_sic from data/raw/ (was data/cropped/ across the board).
Structural-edge collapsing (new)
- Add collapse_structural: dedupe repeated (src, dst) structural edges into
one weighted edge per type, summing amount columns, adding edge_count,
keeping the earliest event as `time` (relationship start) and the most
recent as `last_seen` (recency).
- Thread last_seen through base_cols, the Phase-4 tensors, and the saved
TemporalData object so days-since/recency features can be computed at
load time. Trades are intentionally left un-collapsed.
Node features
- Replace the inline process_node_features (committee/SEC/SIC/CBP -> three
parquets) with delegation to src.data_prep.node_features.build_node_features,
which aligns the node tensors to the Phase-4 src_id_map/dst_id_map and saves
node_features_static.pt (+ meta json).
- Run Phase 3 AFTER Phase 4 so it can align to the node-id maps that Phase 4
writes.
- Adds dependencies on node_features.py and feature_lookups.py.
Cleanup
- Remove the duplicated SEC_FACTS / map_sic_to_division / process_node_features
blocks, the double lobbying read, and the hardcoded CBP_RELEASE_DATES /
STATE_ABBREV tables. Drops the "_CB_esurvey.csv" path (the survey-year files
are handled in build_geographical_edges.py).
- src/temporal_data.py +222 -418
|
@@ -16,37 +16,6 @@ try:
|
|
| 16 |
except ImportError:
|
| 17 |
print("[WARNING] torch_geometric not found. Phase 4 will fail without PyG installed.")
|
| 18 |
|
| 19 |
-
# --- CONFIGURATION PANEL ---
|
| 20 |
-
CONFIG = {
|
| 21 |
-
# 1. Base Directories
|
| 22 |
-
"DATA_DIR": "data",
|
| 23 |
-
"PROCESSED_DIR": "data/processed",
|
| 24 |
-
"EDGE_OUT_DIR": "data/processed/master_edges_parquet",
|
| 25 |
-
"PYG_OUT_DIR": "data/processed/pyg_graph",
|
| 26 |
-
|
| 27 |
-
# 2. Input File Paths (Relative to DATA_DIR)
|
| 28 |
-
"FILES": {
|
| 29 |
-
"trades": "cropped/ml_dataset_continuous.csv",
|
| 30 |
-
"lobbying": "processed/events_lobbying.csv",
|
| 31 |
-
"camp_fin": "processed/events_campaign_finance.csv",
|
| 32 |
-
"geo": "processed/events_geographical_industry.csv",
|
| 33 |
-
"company_sic": "cropped/company_sic_data.csv",
|
| 34 |
-
"committee": "cropped/committee_assignments.csv",
|
| 35 |
-
"sec_financials": "cropped/sec_quarterly_financials.csv"
|
| 36 |
-
},
|
| 37 |
-
|
| 38 |
-
# 3. Graph Assembly Toggles
|
| 39 |
-
"INCLUDE_EDGES": {
|
| 40 |
-
"trades": False,
|
| 41 |
-
"lobbying": True,
|
| 42 |
-
"camp_fin": True,
|
| 43 |
-
"geo": True
|
| 44 |
-
},
|
| 45 |
-
|
| 46 |
-
"START_DATE": "2021-01-01"
|
| 47 |
-
}
|
| 48 |
-
# ---------------------------
|
| 49 |
-
|
| 50 |
# --- Helper for Strict Schema Validation ---
|
| 51 |
def validate_columns(df: pd.DataFrame, required_columns: list, dataset_name: str):
|
| 52 |
"""Raises a clear ValueError if expected columns are missing."""
|
|
@@ -67,7 +36,7 @@ def load_and_standardize_events(data_dir="data"):
|
|
| 67 |
# ---------------------------------------------------------
|
| 68 |
# 1.1 TARGET EDGES (Trades)
|
| 69 |
# ---------------------------------------------------------
|
| 70 |
-
path_trades = os.path.join(
|
| 71 |
print(f"Loading Trades from: {path_trades}")
|
| 72 |
df_trades = pd.read_csv(path_trades)
|
| 73 |
|
|
@@ -102,92 +71,76 @@ def load_and_standardize_events(data_dir="data"):
|
|
| 102 |
# ---------------------------------------------------------
|
| 103 |
# 1.2 LOBBYING EVENTS
|
| 104 |
# ---------------------------------------------------------
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
# Depending on how it was saved, the time column might be 'estimated_filing_date' or 'date'
|
| 114 |
-
time_col_lobby = 'estimated_filing_date' if 'estimated_filing_date' in df_lobbying.columns else 'date'
|
| 115 |
-
|
| 116 |
-
validate_columns(df_lobbying, ['bioguide_id', 'ticker', time_col_lobby, 'event_type'], "Lobbying")
|
| 117 |
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
# Extract structural flags
|
| 125 |
-
df_lobbying['is_sponsorship'] = (df_lobbying['event_type'] == 'LOBBY_STRONG').astype(float)
|
| 126 |
-
df_lobbying['voted_yea'] = (df_lobbying['event_type'] == 'LOBBY_WEAK').astype(float)
|
| 127 |
-
df_lobbying['event_type'] = 1 # Override with integer event code
|
| 128 |
-
|
| 129 |
-
print(f" -> Lobbying loaded successfully. Shape: {df_lobbying.shape}")
|
| 130 |
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
# ---------------------------------------------------------
|
| 136 |
# 1.3 CAMPAIGN FINANCE EVENTS
|
| 137 |
# ---------------------------------------------------------
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
print(f" -> Campaign Finance loaded successfully. Shape: {df_camp_fin.shape}")
|
| 155 |
-
|
| 156 |
-
else:
|
| 157 |
-
print(" -> [CONFIG] Skipping Campaign Finance edges...")
|
| 158 |
-
df_camp_fin = pd.DataFrame()
|
| 159 |
|
| 160 |
-
# 1.4 GEO-INDUSTRIAL EDGES
|
| 161 |
# ---------------------------------------------------------
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
df_geo = df_geo.rename(columns={
|
| 169 |
-
'bioguide_id': 'src',
|
| 170 |
-
'sic_code': 'dst_temp', # Needs broadcasting
|
| 171 |
-
'release_date': 'time'
|
| 172 |
-
})
|
| 173 |
-
|
| 174 |
-
# Normalizing economic weight (log-scaling as per Appendix B.2.3)
|
| 175 |
-
df_geo['Geo_Weight'] = np.log1p(df_geo['employment'].fillna(0))
|
| 176 |
-
df_geo['event_type'] = 3
|
| 177 |
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
|
| 180 |
-
|
| 181 |
-
print(" -> [CONFIG] Skipping Geo-Industrial edges...")
|
| 182 |
-
df_geo = pd.DataFrame()
|
| 183 |
|
| 184 |
# ---------------------------------------------------------
|
| 185 |
# 1.5 LOAD DICTIONARIES FOR BROADCASTING (Phase 2 Prep)
|
| 186 |
# ---------------------------------------------------------
|
| 187 |
print("Loading Crosswalk Dictionaries...")
|
| 188 |
-
path_cw_2012 = os.path.join(data_dir, "
|
| 189 |
-
path_cw_2017 = os.path.join(data_dir, "
|
| 190 |
-
path_cw_cat = os.path.join(data_dir, "
|
| 191 |
|
| 192 |
cw_2012 = pd.read_csv(path_cw_2012)
|
| 193 |
cw_2017 = pd.read_csv(path_cw_2017)
|
|
@@ -208,7 +161,7 @@ def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat,
|
|
| 208 |
print("==================================================")
|
| 209 |
|
| 210 |
# 1. Load and Clean Company SIC Master List
|
| 211 |
-
path_company_sic = os.path.join(data_dir, "
|
| 212 |
df_comp_sic = pd.read_csv(path_company_sic)
|
| 213 |
df_comp_sic = df_comp_sic.drop_duplicates(subset=['ticker', 'sic'])
|
| 214 |
df_comp_sic['sic'] = df_comp_sic['sic'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
|
|
@@ -233,7 +186,87 @@ def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat,
|
|
| 233 |
left_on='SICcode', right_on='sic', how='inner')
|
| 234 |
df_camp_fin = df_camp_fin.rename(columns={'ticker': 'dst'}).drop(columns=['dst_temp', 'OpenSecretsCatcode', 'SICcode', 'sic'])
|
| 235 |
|
| 236 |
-
print(f" -> Geo edges: {len(df_geo)} | Fin edges: {len(df_camp_fin)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
# ---------------------------------------------------------
|
| 239 |
# 2.2 UNIFIED EDGE ATTRIBUTE TENSOR (msg)
|
|
@@ -300,11 +333,16 @@ def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat,
|
|
| 300 |
import pyarrow as pa
|
| 301 |
import pyarrow.parquet as pq
|
| 302 |
|
| 303 |
-
output_dir =
|
| 304 |
os.makedirs(output_dir, exist_ok=True)
|
| 305 |
print(f"Writing chunks directly to Parquet at: {output_dir}")
|
| 306 |
|
| 307 |
-
base_cols = ['src', 'dst', 'time', 'event_type', 'y']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 308 |
|
| 309 |
# Load unpadded, "skinny" dataframes into the queue
|
| 310 |
datasets = [
|
|
@@ -335,6 +373,7 @@ def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat,
|
|
| 335 |
# --- MOVED INSIDE THE CHUNK LOOP ---
|
| 336 |
# Convert to datetime and sort LOCALLY in this 5M row chunk
|
| 337 |
df_chunk['time'] = pd.to_datetime(df_chunk['time'])
|
|
|
|
| 338 |
df_chunk = df_chunk.sort_values(by='time').reset_index(drop=True)
|
| 339 |
# -----------------------------------
|
| 340 |
|
|
@@ -378,282 +417,10 @@ def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat,
|
|
| 378 |
# PHASE 3: NODE FEATURE EXTRACTION
|
| 379 |
# ==========================================
|
| 380 |
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
"CashAndCashEquivalentsAtCarryingValue", "WeightedAverageNumberOfSharesOutstandingBasic",
|
| 385 |
-
"OperatingIncomeLoss", "WeightedAverageNumberOfDilutedSharesOutstanding",
|
| 386 |
-
"Assets", "LiabilitiesAndStockholdersEquity", "InterestExpense",
|
| 387 |
-
"RetainedEarningsAccumulatedDeficit", "NetCashProvidedByUsedInOperatingActivities",
|
| 388 |
-
"NetCashProvidedByUsedInFinancingActivities", "NetCashProvidedByUsedInInvestingActivities",
|
| 389 |
-
"Liabilities", "CommonStockValue", "AccumulatedOtherComprehensiveIncomeLossNetOfTax",
|
| 390 |
-
"PropertyPlantAndEquipmentNet", "Revenues", "AssetsCurrent",
|
| 391 |
-
"LiabilitiesCurrent", "OperatingExpenses", "GrossProfit",
|
| 392 |
-
"PaymentsToAcquirePropertyPlantAndEquipment", "Goodwill",
|
| 393 |
-
"AmortizationOfIntangibleAssets", "SellingGeneralAndAdministrativeExpense",
|
| 394 |
-
"AccountsPayableCurrent", "CommonStockDividendsPerShareDeclared",
|
| 395 |
-
"NonoperatingIncomeExpense", "OtherAssetsNoncurrent",
|
| 396 |
-
"AdditionalPaidInCapital", "AccountsReceivableNetCurrent",
|
| 397 |
-
"ResearchAndDevelopmentExpense"
|
| 398 |
-
]
|
| 399 |
-
|
| 400 |
-
def map_sic_to_division(sic_code):
|
| 401 |
-
"""Maps a 4-digit SIC code to its 10 parent divisions (0-9)."""
|
| 402 |
-
try:
|
| 403 |
-
sic = int(sic_code)
|
| 404 |
-
if sic < 1000: return 0 # Agriculture
|
| 405 |
-
elif sic < 1500: return 1 # Mining
|
| 406 |
-
elif sic < 1800: return 2 # Construction
|
| 407 |
-
elif sic < 4000: return 3 # Manufacturing
|
| 408 |
-
elif sic < 5000: return 4 # Transportation/Utilities
|
| 409 |
-
elif sic < 5200: return 5 # Wholesale Trade
|
| 410 |
-
elif sic < 6000: return 6 # Retail Trade
|
| 411 |
-
elif sic < 6800: return 7 # Finance, Insurance, RE
|
| 412 |
-
elif sic < 9000: return 8 # Services
|
| 413 |
-
else: return 9 # Public Admin
|
| 414 |
-
except:
|
| 415 |
-
return 9
|
| 416 |
-
|
| 417 |
-
def process_node_features(data_dir="data/", processed_dir="data/processed/"):
|
| 418 |
-
"""
|
| 419 |
-
Phase 3: Generate and save temporally aligned node features for politicians and companies.
|
| 420 |
-
"""
|
| 421 |
-
pol_parquet_path = os.path.join(processed_dir, "politician_features.parquet")
|
| 422 |
-
comp_parquet_path = os.path.join(processed_dir, "company_features.parquet")
|
| 423 |
|
| 424 |
-
if os.path.exists(pol_parquet_path) and os.path.exists(comp_parquet_path):
|
| 425 |
-
print(" -> Found existing node feature parquets. Skipping Phase 3 generation...")
|
| 426 |
-
return pol_parquet_path, comp_parquet_path
|
| 427 |
-
|
| 428 |
-
print("==================================================")
|
| 429 |
-
print("PHASE 3: NODE FEATURE EXTRACTION")
|
| 430 |
-
print("==================================================")
|
| 431 |
-
|
| 432 |
-
# --- Politician Snapshots (x_src) ---
|
| 433 |
-
print(" -> Processing Politician Features...")
|
| 434 |
-
df_com = pd.read_csv(os.path.join(data_dir, "cropped/committee_assignments.csv"))
|
| 435 |
-
df_com['Committees'] = df_com['Committees'].fillna('').astype(str).str.split(r';\s*')
|
| 436 |
-
|
| 437 |
-
mlb = MultiLabelBinarizer()
|
| 438 |
-
encoded_com = mlb.fit_transform(df_com['Committees'])
|
| 439 |
-
df_com_encoded = pd.DataFrame(encoded_com, columns=[f"Com_{c}" for c in mlb.classes_])
|
| 440 |
-
df_pol = pd.concat([df_com.drop('Committees', axis=1), df_com_encoded], axis=1)
|
| 441 |
-
|
| 442 |
-
# --- Company Snapshots (x_dst) ---
|
| 443 |
-
print(" -> Processing Company Features (SEC & SIC)...")
|
| 444 |
-
df_sec = pd.read_csv(os.path.join(data_dir, "cropped/sec_quarterly_financials.csv"))
|
| 445 |
-
df_sec['FiledDate'] = pd.to_datetime(df_sec['FiledDate'])
|
| 446 |
-
|
| 447 |
-
df_sec = df_sec[df_sec['Fact'].isin(SEC_FACTS)]
|
| 448 |
-
df_sec = df_sec.drop_duplicates(subset=['Ticker', 'FiledDate', 'Fact'], keep='last')
|
| 449 |
-
|
| 450 |
-
df_comp = df_sec.pivot(index=['Ticker', 'FiledDate'], columns='Fact', values='Value').reset_index()
|
| 451 |
-
for fact in SEC_FACTS:
|
| 452 |
-
if fact not in df_comp.columns:
|
| 453 |
-
df_comp[fact] = np.nan
|
| 454 |
-
|
| 455 |
-
df_comp = df_comp[['Ticker', 'FiledDate'] + SEC_FACTS].sort_values(['Ticker', 'FiledDate'])
|
| 456 |
-
df_comp = df_comp.groupby('Ticker').ffill().fillna(0.0)
|
| 457 |
-
|
| 458 |
-
for col in SEC_FACTS:
|
| 459 |
-
df_comp[col] = np.sign(df_comp[col]) * np.log1p(np.abs(df_comp[col]))
|
| 460 |
-
|
| 461 |
-
df_sic = pd.read_csv(os.path.join(data_dir, "cropped/company_sic_data.csv"))
|
| 462 |
-
df_sic['sic_division'] = df_sic['sic'].apply(map_sic_to_division)
|
| 463 |
-
sic_dummies = pd.get_dummies(df_sic['sic_division'], prefix='SIC_Div')
|
| 464 |
-
|
| 465 |
-
for i in range(10):
|
| 466 |
-
if f'SIC_Div_{i}' not in sic_dummies.columns:
|
| 467 |
-
sic_dummies[f'SIC_Div_{i}'] = 0
|
| 468 |
-
|
| 469 |
-
df_sic = pd.concat([df_sic[['ticker']], sic_dummies[[f'SIC_Div_{i}' for i in range(10)]].astype(np.float32)], axis=1)
|
| 470 |
-
df_sic = df_sic.rename(columns={'ticker': 'Ticker'})
|
| 471 |
-
|
| 472 |
-
df_comp = df_comp.merge(df_sic, on='Ticker', how='left')
|
| 473 |
-
sic_cols = [f'SIC_Div_{i}' for i in range(10)]
|
| 474 |
-
df_comp[sic_cols] = df_comp[sic_cols].fillna(0.0)
|
| 475 |
-
|
| 476 |
-
print(" -> Saving Phase 3 Parquets...")
|
| 477 |
-
df_pol.to_parquet(pol_parquet_path)
|
| 478 |
-
df_comp.to_parquet(comp_parquet_path)
|
| 479 |
-
|
| 480 |
-
return pol_parquet_path, comp_parquet_path
|
| 481 |
-
|
| 482 |
-
# ==========================================
|
| 483 |
-
# PHASE 3: NODE FEATURE EXTRACTION
|
| 484 |
-
# ==========================================
|
| 485 |
-
|
| 486 |
-
SEC_FACTS = [
|
| 487 |
-
"NetIncomeLoss", "StockholdersEquity", "EarningsPerShareBasic",
|
| 488 |
-
"EarningsPerShareDiluted", "IncomeTaxExpenseBenefit",
|
| 489 |
-
"CashAndCashEquivalentsAtCarryingValue", "WeightedAverageNumberOfSharesOutstandingBasic",
|
| 490 |
-
"OperatingIncomeLoss", "WeightedAverageNumberOfDilutedSharesOutstanding",
|
| 491 |
-
"Assets", "LiabilitiesAndStockholdersEquity", "InterestExpense",
|
| 492 |
-
"RetainedEarningsAccumulatedDeficit", "NetCashProvidedByUsedInOperatingActivities",
|
| 493 |
-
"NetCashProvidedByUsedInFinancingActivities", "NetCashProvidedByUsedInInvestingActivities",
|
| 494 |
-
"Liabilities", "CommonStockValue", "AccumulatedOtherComprehensiveIncomeLossNetOfTax",
|
| 495 |
-
"PropertyPlantAndEquipmentNet", "Revenues", "AssetsCurrent",
|
| 496 |
-
"LiabilitiesCurrent", "OperatingExpenses", "GrossProfit",
|
| 497 |
-
"PaymentsToAcquirePropertyPlantAndEquipment", "Goodwill",
|
| 498 |
-
"AmortizationOfIntangibleAssets", "SellingGeneralAndAdministrativeExpense",
|
| 499 |
-
"AccountsPayableCurrent", "CommonStockDividendsPerShareDeclared",
|
| 500 |
-
"NonoperatingIncomeExpense", "OtherAssetsNoncurrent",
|
| 501 |
-
"AdditionalPaidInCapital", "AccountsReceivableNetCurrent",
|
| 502 |
-
"ResearchAndDevelopmentExpense"
|
| 503 |
-
]
|
| 504 |
-
|
| 505 |
-
def map_sic_to_division(sic_code):
|
| 506 |
-
"""Maps a 4-digit SIC code to its 10 parent divisions (0-9)."""
|
| 507 |
-
try:
|
| 508 |
-
sic = int(sic_code)
|
| 509 |
-
if sic < 1000: return 0 # Agriculture
|
| 510 |
-
elif sic < 1500: return 1 # Mining
|
| 511 |
-
elif sic < 1800: return 2 # Construction
|
| 512 |
-
elif sic < 4000: return 3 # Manufacturing
|
| 513 |
-
elif sic < 5000: return 4 # Transportation/Utilities
|
| 514 |
-
elif sic < 5200: return 5 # Wholesale Trade
|
| 515 |
-
elif sic < 6000: return 6 # Retail Trade
|
| 516 |
-
elif sic < 6800: return 7 # Finance, Insurance, RE
|
| 517 |
-
elif sic < 9000: return 8 # Services
|
| 518 |
-
else: return 9 # Public Admin
|
| 519 |
-
except:
|
| 520 |
-
return 9
|
| 521 |
-
|
| 522 |
-
# --- Constants & Configurations ---
|
| 523 |
-
CBP_RELEASE_DATES = {
|
| 524 |
-
2023: "2025-06-26", 2022: "2024-06-27", 2021: "2023-04-20",
|
| 525 |
-
2020: "2022-04-28", 2019: "2021-04-22", 2018: "2020-06-25",
|
| 526 |
-
2017: "2019-11-21", 2016: "2018-04-19", 2015: "2017-04-20",
|
| 527 |
-
2014: "2016-04-24", 2013: "2015-04-23", 2012: "2014-05-29",
|
| 528 |
-
2011: "2013-04-30", 2010: "2012-06-26"
|
| 529 |
-
}
|
| 530 |
-
|
| 531 |
-
STATE_ABBREV = {
|
| 532 |
-
'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA',
|
| 533 |
-
'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA',
|
| 534 |
-
'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA',
|
| 535 |
-
'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD',
|
| 536 |
-
'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
|
| 537 |
-
'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH',
|
| 538 |
-
'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC',
|
| 539 |
-
'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA',
|
| 540 |
-
'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN',
|
| 541 |
-
'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA',
|
| 542 |
-
'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY', 'District of Columbia': 'DC'
|
| 543 |
-
}
|
| 544 |
-
|
| 545 |
-
# (Keep SEC_FACTS list and map_sic_to_division helper exactly as you had them)
|
| 546 |
-
|
| 547 |
-
def process_node_features(data_dir="data/", processed_dir="data/processed/"):
|
| 548 |
-
"""Phase 3: Generate and save standardized node features."""
|
| 549 |
-
import re
|
| 550 |
-
pol_path = os.path.join(processed_dir, "politician_features.parquet")
|
| 551 |
-
comp_path = os.path.join(processed_dir, "company_features.parquet")
|
| 552 |
-
cbp_out_path = os.path.join(processed_dir, "district_economics_cbp.parquet")
|
| 553 |
-
|
| 554 |
-
if all(os.path.exists(p) for p in [pol_path, comp_path, cbp_out_path]):
|
| 555 |
-
print(" -> Found all node feature parquets. Skipping Phase 3...")
|
| 556 |
-
return pol_path, comp_path
|
| 557 |
-
|
| 558 |
-
print("==================================================")
|
| 559 |
-
print("PHASE 3: NODE FEATURE EXTRACTION")
|
| 560 |
-
print("==================================================")
|
| 561 |
-
|
| 562 |
-
# --- 1. POLITICIAN STATIC (Committees & Party) ---
|
| 563 |
-
print(" -> Processing Politician Static Features...")
|
| 564 |
-
df_com = pd.read_csv(os.path.join(data_dir, "cropped/committee_assignments.csv"))
|
| 565 |
-
df_com['Committees'] = df_com['Committees'].fillna('').astype(str).str.split(r';\s*')
|
| 566 |
-
mlb = MultiLabelBinarizer()
|
| 567 |
-
encoded_com = mlb.fit_transform(df_com['Committees'])
|
| 568 |
-
df_pol_static = pd.concat([df_com.drop('Committees', axis=1),
|
| 569 |
-
pd.DataFrame(encoded_com, columns=[f"Com_{c}" for c in mlb.classes_])], axis=1)
|
| 570 |
-
df_pol_static['District_Num'] = df_pol_static['District'].astype(str).str.extract(r'(\d+)').fillna('0')
|
| 571 |
-
|
| 572 |
-
# --- 2. DISTRICT ECONOMICS (NAICS Schema-Agnostic) ---
|
| 573 |
-
print(" -> Processing CBP District Economics (Handling 2012/2017 NAICS Schema)...")
|
| 574 |
-
cbp_dir = os.path.join(data_dir, "cropped/district_industries")
|
| 575 |
-
cbp_dfs = []
|
| 576 |
-
|
| 577 |
-
# Nested helper to parse "Congressional District 1 (119th Congress), Alabama"
|
| 578 |
-
def _parse_geo(name):
|
| 579 |
-
try:
|
| 580 |
-
match = re.search(r'(?:District\s|at Large)(\d+)?.*?,\s*(.*)', str(name))
|
| 581 |
-
if match:
|
| 582 |
-
dist = match.group(1) if match.group(1) else '0'
|
| 583 |
-
state = STATE_ABBREV.get(match.group(2).strip(), 'XX')
|
| 584 |
-
return state, str(int(dist))
|
| 585 |
-
except: pass
|
| 586 |
-
return "XX", "-1"
|
| 587 |
-
|
| 588 |
-
for year, release_date in CBP_RELEASE_DATES.items():
|
| 589 |
-
file_name = f"{year}_CB_estimates.csv" if year <= 2012 else f"{year}_CB_esurvey.csv"
|
| 590 |
-
file_path = os.path.join(cbp_dir, file_name)
|
| 591 |
-
if not os.path.exists(file_path): continue
|
| 592 |
-
|
| 593 |
-
df_year = pd.read_csv(file_path, low_memory=False)
|
| 594 |
-
df_year.columns = [c.split('(')[-1].replace(')', '').strip() if '(' in c else c for c in df_year.columns]
|
| 595 |
-
|
| 596 |
-
# Dynamically grabs NAICS2012 or NAICS2017
|
| 597 |
-
naics_col = next((c for c in df_year.columns if 'NAICS' in c), None)
|
| 598 |
-
if not naics_col: continue
|
| 599 |
-
|
| 600 |
-
df_year = df_year[['NAME', naics_col, 'EMP']].copy()
|
| 601 |
-
df_year.rename(columns={naics_col: 'Sector_Raw'}, inplace=True)
|
| 602 |
-
df_year['EMP'] = pd.to_numeric(df_year['EMP'], errors='coerce').fillna(0)
|
| 603 |
-
df_year['ReleaseDate'] = pd.to_datetime(release_date)
|
| 604 |
-
|
| 605 |
-
# Explicitly call the nested _parse_geo function
|
| 606 |
-
df_year[['State', 'District']] = pd.DataFrame(df_year['NAME'].apply(_parse_geo).tolist(), index=df_year.index)
|
| 607 |
-
df_year['Sector'] = df_year['Sector_Raw'].astype(str).str[:2]
|
| 608 |
-
cbp_dfs.append(df_year)
|
| 609 |
-
|
| 610 |
-
if cbp_dfs:
|
| 611 |
-
df_cbp = pd.concat(cbp_dfs, ignore_index=True)
|
| 612 |
-
df_cbp_pivot = df_cbp.pivot_table(index=['State', 'District', 'ReleaseDate'],
|
| 613 |
-
columns='Sector', values='EMP', aggfunc='sum').reset_index()
|
| 614 |
-
|
| 615 |
-
# Forward fill 24-dim economics vector
|
| 616 |
-
df_cbp_pivot = df_cbp_pivot.sort_values(['State', 'District', 'ReleaseDate'])
|
| 617 |
-
sector_cols = [c for c in df_cbp_pivot.columns if c not in ['State', 'District', 'ReleaseDate']]
|
| 618 |
-
|
| 619 |
-
# Prefix the NAICS columns for clarity
|
| 620 |
-
df_cbp_pivot.rename(columns={c: f"NAICS_EMP_{c}" for c in sector_cols}, inplace=True)
|
| 621 |
-
naics_prefixed = [f"NAICS_EMP_{c}" for c in sector_cols]
|
| 622 |
-
|
| 623 |
-
df_cbp_pivot[naics_prefixed] = df_cbp_pivot.groupby(['State', 'District'])[naics_prefixed].ffill().fillna(0.0)
|
| 624 |
-
|
| 625 |
-
df_cbp_pivot.to_parquet(cbp_out_path)
|
| 626 |
-
print(f" -> Saved District Economics (Dims: {len(naics_prefixed)})")
|
| 627 |
-
|
| 628 |
-
# --- 3. COMPANY SNAPSHOTS (SEC & SIC) ---
|
| 629 |
-
print(" -> Processing Company Features (SEC & SIC)...")
|
| 630 |
-
df_sec = pd.read_csv(os.path.join(data_dir, "cropped/sec_quarterly_financials.csv"))
|
| 631 |
-
df_sec['FiledDate'] = pd.to_datetime(df_sec['FiledDate'])
|
| 632 |
-
df_sec = df_sec[df_sec['Fact'].isin(SEC_FACTS)].drop_duplicates(subset=['Ticker', 'FiledDate', 'Fact'], keep='last')
|
| 633 |
-
|
| 634 |
-
df_comp = df_sec.pivot(index=['Ticker', 'FiledDate'], columns='Fact', values='Value').reset_index()
|
| 635 |
-
for fact in SEC_FACTS:
|
| 636 |
-
if fact not in df_comp.columns: df_comp[fact] = np.nan
|
| 637 |
-
df_comp = df_comp[['Ticker', 'FiledDate'] + SEC_FACTS].sort_values(['Ticker', 'FiledDate'])
|
| 638 |
-
|
| 639 |
-
df_comp[SEC_FACTS] = df_comp.groupby('Ticker')[SEC_FACTS].ffill().fillna(0.0)
|
| 640 |
-
for col in SEC_FACTS:
|
| 641 |
-
df_comp[col] = np.sign(df_comp[col]) * np.log1p(np.abs(df_comp[col]))
|
| 642 |
-
|
| 643 |
-
df_sic = pd.read_csv(os.path.join(data_dir, "cropped/company_sic_data.csv"))
|
| 644 |
-
df_sic['sic_division'] = df_sic['sic'].apply(map_sic_to_division)
|
| 645 |
-
sic_dummies = pd.get_dummies(df_sic['sic_division'], prefix='SIC_Div')
|
| 646 |
-
for i in range(10):
|
| 647 |
-
if f'SIC_Div_{i}' not in sic_dummies.columns: sic_dummies[f'SIC_Div_{i}'] = 0
|
| 648 |
-
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'})
|
| 649 |
-
df_comp = df_comp.merge(df_sic_proc, on='Ticker', how='left').fillna(0.0)
|
| 650 |
-
|
| 651 |
-
# SAVE ALL
|
| 652 |
-
print(" -> Saving Phase 3 Parquets...")
|
| 653 |
-
df_pol_static.to_parquet(pol_path)
|
| 654 |
-
df_comp.to_parquet(comp_path)
|
| 655 |
-
|
| 656 |
-
return pol_path, comp_path
|
| 657 |
|
| 658 |
# ==========================================
|
| 659 |
# PHASE 4: ASSEMBLY & PYG VALIDATION
|
|
@@ -685,27 +452,14 @@ def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet",
|
|
| 685 |
]
|
| 686 |
|
| 687 |
valid_files = []
|
| 688 |
-
# Map filenames to their config keys
|
| 689 |
-
edge_map = {
|
| 690 |
-
"edges_trades.parquet": "trades",
|
| 691 |
-
"edges_lobbying.parquet": "lobbying",
|
| 692 |
-
"edges_camp_fin.parquet": "camp_fin",
|
| 693 |
-
"edges_geo.parquet": "geo"
|
| 694 |
-
}
|
| 695 |
-
|
| 696 |
for file in edge_files:
|
| 697 |
-
config_key = edge_map[file]
|
| 698 |
-
|
| 699 |
-
# Check the toggle in CONFIG
|
| 700 |
-
if not CONFIG["INCLUDE_EDGES"].get(config_key, True):
|
| 701 |
-
print(f" -> Skipping '{config_key}' edge file per config.")
|
| 702 |
-
continue
|
| 703 |
-
|
| 704 |
file_path = os.path.join(edge_dir, file)
|
| 705 |
if not os.path.exists(file_path):
|
| 706 |
print(f" -> [WARNING] Expected edge chunk not found: {file}")
|
| 707 |
continue
|
| 708 |
-
|
|
|
|
|
|
|
| 709 |
valid_files.append(file_path)
|
| 710 |
|
| 711 |
files_sql = "[" + ", ".join([f"'{f}'" for f in valid_files]) + "]"
|
|
@@ -787,8 +541,15 @@ def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet",
|
|
| 787 |
time_array = master_table['time'].to_numpy().astype('datetime64[s]').astype(np.int64)
|
| 788 |
t_tensor = torch.from_numpy(time_array).to(torch.long)
|
| 789 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 790 |
# Message Attribute Tensor (D=24)
|
| 791 |
-
base_cols = ['src', 'dst', 'time', 'y', 'event_type']
|
| 792 |
msg_cols = [c for c in master_table.column_names if c not in base_cols]
|
| 793 |
|
| 794 |
msg_tensor = torch.empty((num_rows, len(msg_cols)), dtype=torch.float)
|
|
@@ -806,6 +567,7 @@ def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet",
|
|
| 806 |
y=y_tensor
|
| 807 |
)
|
| 808 |
data.event_type = event_type_tensor
|
|
|
|
| 809 |
|
| 810 |
# Audit
|
| 811 |
is_sorted = torch.all(t_tensor[1:] >= t_tensor[:-1]).item()
|
|
@@ -818,7 +580,7 @@ def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet",
|
|
| 818 |
print(f" -> Shard saved successfully: {shard_path}")
|
| 819 |
|
| 820 |
# Memory Cleanup
|
| 821 |
-
del master_table, src_tensor, dst_tensor, y_tensor, event_type_tensor, t_tensor, msg_tensor, data
|
| 822 |
gc.collect()
|
| 823 |
|
| 824 |
print("\n==================================================")
|
|
@@ -831,19 +593,36 @@ def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet",
|
|
| 831 |
# ==========================================
|
| 832 |
|
| 833 |
if __name__ == "__main__":
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 844 |
|
| 845 |
# 2. Check for Phase 1 & 2 Persistence
|
| 846 |
-
phase2_done = all(os.path.exists(os.path.join(EDGE_DIR, f)) for f in REQUIRED_EDGES)
|
| 847 |
|
| 848 |
if phase2_done:
|
| 849 |
print(f" -> Found existing edge parquets in {EDGE_DIR}. Skipping Phases 1 & 2.")
|
|
@@ -854,12 +633,37 @@ if __name__ == "__main__":
|
|
| 854 |
df_trades, df_lobbying, df_camp_fin, df_geo, cw_2012, cw_2017, cw_cat = load_and_standardize_events()
|
| 855 |
EDGE_DIR, all_msg_cols = broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat)
|
| 856 |
|
| 857 |
-
# 3.
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
start_date=
|
|
|
|
| 863 |
)
|
| 864 |
-
|
| 865 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
except ImportError:
|
| 17 |
print("[WARNING] torch_geometric not found. Phase 4 will fail without PyG installed.")
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# --- Helper for Strict Schema Validation ---
|
| 20 |
def validate_columns(df: pd.DataFrame, required_columns: list, dataset_name: str):
|
| 21 |
"""Raises a clear ValueError if expected columns are missing."""
|
|
|
|
| 36 |
# ---------------------------------------------------------
|
| 37 |
# 1.1 TARGET EDGES (Trades)
|
| 38 |
# ---------------------------------------------------------
|
| 39 |
+
path_trades = os.path.join(data_dir, "processed", "ml_dataset_continuous.csv")
|
| 40 |
print(f"Loading Trades from: {path_trades}")
|
| 41 |
df_trades = pd.read_csv(path_trades)
|
| 42 |
|
|
|
|
| 71 |
# ---------------------------------------------------------
|
| 72 |
# 1.2 LOBBYING EVENTS
|
| 73 |
# ---------------------------------------------------------
|
| 74 |
+
path_lobbying = os.path.join(data_dir, "processed", "events_lobbying.csv")
|
| 75 |
+
print(f"Loading Lobbying from: {path_lobbying}")
|
| 76 |
+
df_lobbying = pd.read_csv(path_lobbying)
|
| 77 |
+
|
| 78 |
+
# Depending on how it was saved, the time column might be 'estimated_filing_date' or 'date'
|
| 79 |
+
time_col_lobby = 'estimated_filing_date' if 'estimated_filing_date' in df_lobbying.columns else 'date'
|
| 80 |
+
|
| 81 |
+
validate_columns(df_lobbying, ['bioguide_id', 'ticker', time_col_lobby, 'event_type'], "Lobbying")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
df_lobbying = df_lobbying.rename(columns={
|
| 84 |
+
'bioguide_id': 'src',
|
| 85 |
+
'ticker': 'dst',
|
| 86 |
+
time_col_lobby: 'time'
|
| 87 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
# Extract structural flags
|
| 90 |
+
df_lobbying['is_sponsorship'] = (df_lobbying['event_type'] == 'LOBBY_STRONG').astype(float)
|
| 91 |
+
df_lobbying['voted_yea'] = (df_lobbying['event_type'] == 'LOBBY_WEAK').astype(float)
|
| 92 |
+
df_lobbying['event_type'] = 1 # Override with integer event code
|
| 93 |
+
|
| 94 |
+
print(f" -> Lobbying loaded successfully. Shape: {df_lobbying.shape}")
|
| 95 |
|
| 96 |
# ---------------------------------------------------------
|
| 97 |
# 1.3 CAMPAIGN FINANCE EVENTS
|
| 98 |
# ---------------------------------------------------------
|
| 99 |
+
path_camp_fin = os.path.join(data_dir, "processed", "events_campaign_finance.csv")
|
| 100 |
+
print(f"Loading Campaign Finance from: {path_camp_fin}")
|
| 101 |
+
df_camp_fin = pd.read_csv(path_camp_fin)
|
| 102 |
+
|
| 103 |
+
time_col_cf = 'estimated_filing_date' if 'estimated_filing_date' in df_camp_fin.columns else 'date'
|
| 104 |
+
validate_columns(df_camp_fin, ['bioguide_id', 'industry_code', time_col_cf, 'weight'], "Campaign Finance")
|
| 105 |
+
|
| 106 |
+
df_camp_fin = df_camp_fin.rename(columns={
|
| 107 |
+
'bioguide_id': 'src',
|
| 108 |
+
'industry_code': 'dst_temp', # Needs broadcasting
|
| 109 |
+
time_col_cf: 'time',
|
| 110 |
+
'weight': 'Fin_Amt' # Assuming donation amount
|
| 111 |
+
})
|
| 112 |
+
df_camp_fin['event_type'] = 2
|
| 113 |
+
|
| 114 |
+
print(f" -> Campaign Finance loaded successfully. Shape: {df_camp_fin.shape}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
|
|
|
| 116 |
# ---------------------------------------------------------
|
| 117 |
+
# 1.4 GEO-INDUSTRIAL EVENTS
|
| 118 |
+
# ---------------------------------------------------------
|
| 119 |
+
path_geo = os.path.join(data_dir, "processed", "events_geographical_industry.csv")
|
| 120 |
+
print(f"Loading Geo-Industrial from: {path_geo}")
|
| 121 |
+
df_geo = pd.read_csv(path_geo)
|
| 122 |
|
| 123 |
+
validate_columns(df_geo, ['bioguide_id', 'sic_code', 'release_date', 'establishments', 'employment', 'annual_payroll'], "Geo-Industrial")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
df_geo = df_geo.rename(columns={
|
| 126 |
+
'bioguide_id': 'src',
|
| 127 |
+
'sic_code': 'dst_temp', # Needs broadcasting
|
| 128 |
+
'release_date': 'time'
|
| 129 |
+
})
|
| 130 |
+
|
| 131 |
+
# Normalizing raw economic weight (log-scaling as per Appendix B.2.3)
|
| 132 |
+
df_geo['Geo_Weight'] = np.log1p(df_geo['employment'].fillna(0))
|
| 133 |
+
df_geo['event_type'] = 3
|
| 134 |
|
| 135 |
+
print(f" -> Geo-Industrial loaded successfully. Shape: {df_geo.shape}")
|
|
|
|
|
|
|
| 136 |
|
| 137 |
# ---------------------------------------------------------
|
| 138 |
# 1.5 LOAD DICTIONARIES FOR BROADCASTING (Phase 2 Prep)
|
| 139 |
# ---------------------------------------------------------
|
| 140 |
print("Loading Crosswalk Dictionaries...")
|
| 141 |
+
path_cw_2012 = os.path.join(data_dir, "raw", "industry_codes_NAICS", "2012-NAICS-to-SIC-crosswalk.csv")
|
| 142 |
+
path_cw_2017 = os.path.join(data_dir, "raw", "industry_codes_NAICS", "2017-NAICS-to-SIC-crosswalk.csv")
|
| 143 |
+
path_cw_cat = os.path.join(data_dir, "raw", "industry_codes_NAICS", "2013-CAT_to_SIC_to_NAICS_mappings.csv")
|
| 144 |
|
| 145 |
cw_2012 = pd.read_csv(path_cw_2012)
|
| 146 |
cw_2017 = pd.read_csv(path_cw_2017)
|
|
|
|
| 161 |
print("==================================================")
|
| 162 |
|
| 163 |
# 1. Load and Clean Company SIC Master List
|
| 164 |
+
path_company_sic = os.path.join(data_dir, "raw", "company_sic_data.csv")
|
| 165 |
df_comp_sic = pd.read_csv(path_company_sic)
|
| 166 |
df_comp_sic = df_comp_sic.drop_duplicates(subset=['ticker', 'sic'])
|
| 167 |
df_comp_sic['sic'] = df_comp_sic['sic'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
|
|
|
|
| 186 |
left_on='SICcode', right_on='sic', how='inner')
|
| 187 |
df_camp_fin = df_camp_fin.rename(columns={'ticker': 'dst'}).drop(columns=['dst_temp', 'OpenSecretsCatcode', 'SICcode', 'sic'])
|
| 188 |
|
| 189 |
+
print(f" -> Geo edges (pre-dedup): {len(df_geo)} | Fin edges (pre-dedup): {len(df_camp_fin)}")
|
| 190 |
+
|
| 191 |
+
# ---------------------------------------------------------
|
| 192 |
+
# 2.1b COLLAPSE REPEATED STRUCTURAL EDGES INTO ONE WEIGHTED EDGE
|
| 193 |
+
# ---------------------------------------------------------
|
| 194 |
+
# Broadcasting (and the raw event streams themselves) emit many duplicate
|
| 195 |
+
# (politician, company) pairs of the same type -- e.g. the same company
|
| 196 |
+
# lobbying on several of a legislator's bills, or one industry signal fanned
|
| 197 |
+
# across every ticker in that industry. Rather than carry each as its own
|
| 198 |
+
# edge (which is what blows the edge count into the tens of millions), we keep
|
| 199 |
+
# ONE edge per (src, dst, event_type) and accumulate weight onto it:
|
| 200 |
+
#
|
| 201 |
+
# weight = number of collapsed events (interaction count / intensity)
|
| 202 |
+
# <amount cols> = summed across the collapsed events
|
| 203 |
+
# time = EARLIEST event (when the relationship began; this is also
|
| 204 |
+
# what the chronological sort + shard `t` tensor key on)
|
| 205 |
+
# last_seen = MOST RECENT event (carried separately so recency features
|
| 206 |
+
# like days-since can be computed independently of edge age)
|
| 207 |
+
#
|
| 208 |
+
# Trades are intentionally NOT touched here -- each trade is a distinct
|
| 209 |
+
# supervised event with its own label and market features.
|
| 210 |
+
def collapse_structural(df, name, amount_cols):
|
| 211 |
+
"""Dedup to one edge per (src, dst), summing amount_cols, keeping BOTH the
|
| 212 |
+
earliest event (as 'time') and the most recent (as 'last_seen').
|
| 213 |
+
Adds an 'edge_count' column recording how many events were merged."""
|
| 214 |
+
if df.empty:
|
| 215 |
+
df['edge_count'] = pd.Series(dtype='float32')
|
| 216 |
+
df['last_seen'] = pd.Series(dtype='object')
|
| 217 |
+
return df
|
| 218 |
+
|
| 219 |
+
before = len(df)
|
| 220 |
+
df = df.dropna(subset=['src', 'dst', 'time']).copy()
|
| 221 |
+
|
| 222 |
+
# Earliest -> time, latest -> last_seen. 'time' is min so the downstream
|
| 223 |
+
# chronological sort anchors the edge to the start of the relationship;
|
| 224 |
+
# 'last_seen' preserves recency for days-since at load time.
|
| 225 |
+
df['__last_seen'] = df['time']
|
| 226 |
+
agg = {c: 'sum' for c in amount_cols if c in df.columns}
|
| 227 |
+
agg['time'] = 'min' # earliest event in the pair
|
| 228 |
+
agg['__last_seen'] = 'max' # most recent event in the pair
|
| 229 |
+
agg['__count'] = 'sum' # how many events collapsed into this edge
|
| 230 |
+
df['__count'] = 1.0
|
| 231 |
+
|
| 232 |
+
# Carry through any remaining base/identity columns (event_type, y, ...) that
|
| 233 |
+
# we are NOT explicitly aggregating. These are constant within a stream
|
| 234 |
+
# (event_type is set per-stream in Phase 1; y is -1 on all structural edges),
|
| 235 |
+
# so 'first' is exact. Without this, groupby.agg silently drops them and the
|
| 236 |
+
# later df_chunk[base_cols + all_msg_cols] selection raises KeyError.
|
| 237 |
+
carry_cols = [c for c in ('event_type', 'y')
|
| 238 |
+
if c in df.columns and c not in agg]
|
| 239 |
+
for c in carry_cols:
|
| 240 |
+
agg[c] = 'first'
|
| 241 |
+
|
| 242 |
+
merged = df.groupby(['src', 'dst'], sort=False, as_index=False).agg(agg)
|
| 243 |
+
merged = merged.rename(columns={'__count': 'edge_count', '__last_seen': 'last_seen'})
|
| 244 |
+
|
| 245 |
+
after = len(merged)
|
| 246 |
+
print(f" -> {name}: collapsed {before:,} broadcast edges -> {after:,} "
|
| 247 |
+
f"unique (src, dst) edges ({before / max(after, 1):.1f}x reduction).")
|
| 248 |
+
return merged
|
| 249 |
+
|
| 250 |
+
# Each stream's "amount" columns are the numeric msg fields it actually carries.
|
| 251 |
+
# Anything not listed is left to the schema-alignment step to zero-fill.
|
| 252 |
+
df_lobbying = collapse_structural(
|
| 253 |
+
df_lobbying, "Lobbying", amount_cols=['is_sponsorship', 'voted_yea'])
|
| 254 |
+
df_camp_fin = collapse_structural(
|
| 255 |
+
df_camp_fin, "Campaign Finance", amount_cols=['Fin_Amt'])
|
| 256 |
+
df_geo = collapse_structural(
|
| 257 |
+
df_geo, "Geo-Industrial", amount_cols=['Geo_Weight'])
|
| 258 |
+
|
| 259 |
+
# Surface the collapsed-event tally to the model as a weight feature. We fold it
|
| 260 |
+
# into Fin_Amt for campaign (already an amount) and leave it as the standalone
|
| 261 |
+
# 'edge_count' for the others; node_features.aggregate_pair_edges recomputes its
|
| 262 |
+
# own per-pair counts at load time, so this is primarily for inspection/QA, but
|
| 263 |
+
# it also means an un-aggregated downstream consumer still sees the intensity.
|
| 264 |
+
for _df in (df_lobbying, df_camp_fin, df_geo):
|
| 265 |
+
if 'edge_count' not in _df.columns:
|
| 266 |
+
_df['edge_count'] = 1.0
|
| 267 |
+
|
| 268 |
+
print(f" -> Geo edges (post-dedup): {len(df_geo)} | Fin edges (post-dedup): {len(df_camp_fin)} "
|
| 269 |
+
f"| Lobbying edges (post-dedup): {len(df_lobbying)}")
|
| 270 |
|
| 271 |
# ---------------------------------------------------------
|
| 272 |
# 2.2 UNIFIED EDGE ATTRIBUTE TENSOR (msg)
|
|
|
|
| 333 |
import pyarrow as pa
|
| 334 |
import pyarrow.parquet as pq
|
| 335 |
|
| 336 |
+
output_dir = os.path.join(data_dir, "processed", "master_edges_parquet")
|
| 337 |
os.makedirs(output_dir, exist_ok=True)
|
| 338 |
print(f"Writing chunks directly to Parquet at: {output_dir}")
|
| 339 |
|
| 340 |
+
base_cols = ['src', 'dst', 'time', 'last_seen', 'event_type', 'y']
|
| 341 |
+
|
| 342 |
+
# Trades are not deduped, so they have no 'last_seen'. For an un-collapsed edge
|
| 343 |
+
# the relationship's first and last touch are the same instant, so last_seen == time.
|
| 344 |
+
if 'last_seen' not in df_trades.columns:
|
| 345 |
+
df_trades['last_seen'] = df_trades['time']
|
| 346 |
|
| 347 |
# Load unpadded, "skinny" dataframes into the queue
|
| 348 |
datasets = [
|
|
|
|
| 373 |
# --- MOVED INSIDE THE CHUNK LOOP ---
|
| 374 |
# Convert to datetime and sort LOCALLY in this 5M row chunk
|
| 375 |
df_chunk['time'] = pd.to_datetime(df_chunk['time'])
|
| 376 |
+
df_chunk['last_seen'] = pd.to_datetime(df_chunk['last_seen'])
|
| 377 |
df_chunk = df_chunk.sort_values(by='time').reset_index(drop=True)
|
| 378 |
# -----------------------------------
|
| 379 |
|
|
|
|
| 417 |
# PHASE 3: NODE FEATURE EXTRACTION
|
| 418 |
# ==========================================
|
| 419 |
|
| 420 |
+
# Phase 3 lives in src/data_prep/node_features.py (build_node_features), which
|
| 421 |
+
# replicates the deprecated graph_builder composition and aligns the node tensors
|
| 422 |
+
# to the Phase-4 node-id maps. It is invoked from __main__ after Phase 4 below.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 423 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
# ==========================================
|
| 426 |
# PHASE 4: ASSEMBLY & PYG VALIDATION
|
|
|
|
| 452 |
]
|
| 453 |
|
| 454 |
valid_files = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
for file in edge_files:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 456 |
file_path = os.path.join(edge_dir, file)
|
| 457 |
if not os.path.exists(file_path):
|
| 458 |
print(f" -> [WARNING] Expected edge chunk not found: {file}")
|
| 459 |
continue
|
| 460 |
+
if not include_structural_edges and "trades" not in file:
|
| 461 |
+
print(f" -> Skipping structural edge file per config: {file}")
|
| 462 |
+
continue
|
| 463 |
valid_files.append(file_path)
|
| 464 |
|
| 465 |
files_sql = "[" + ", ".join([f"'{f}'" for f in valid_files]) + "]"
|
|
|
|
| 541 |
time_array = master_table['time'].to_numpy().astype('datetime64[s]').astype(np.int64)
|
| 542 |
t_tensor = torch.from_numpy(time_array).to(torch.long)
|
| 543 |
|
| 544 |
+
# Recency endpoint: epoch-seconds of the most recent event in each (collapsed)
|
| 545 |
+
# edge. For trades and any un-deduped edge this equals `t`. Kept as its own
|
| 546 |
+
# tensor (NOT in msg) so the load path can compute days-since from recency
|
| 547 |
+
# while `t` continues to anchor the edge to the start of the relationship.
|
| 548 |
+
last_seen_array = master_table['last_seen'].to_numpy().astype('datetime64[s]').astype(np.int64)
|
| 549 |
+
last_seen_tensor = torch.from_numpy(last_seen_array).to(torch.long)
|
| 550 |
+
|
| 551 |
# Message Attribute Tensor (D=24)
|
| 552 |
+
base_cols = ['src', 'dst', 'time', 'last_seen', 'y', 'event_type']
|
| 553 |
msg_cols = [c for c in master_table.column_names if c not in base_cols]
|
| 554 |
|
| 555 |
msg_tensor = torch.empty((num_rows, len(msg_cols)), dtype=torch.float)
|
|
|
|
| 567 |
y=y_tensor
|
| 568 |
)
|
| 569 |
data.event_type = event_type_tensor
|
| 570 |
+
data.last_seen = last_seen_tensor
|
| 571 |
|
| 572 |
# Audit
|
| 573 |
is_sorted = torch.all(t_tensor[1:] >= t_tensor[:-1]).item()
|
|
|
|
| 580 |
print(f" -> Shard saved successfully: {shard_path}")
|
| 581 |
|
| 582 |
# Memory Cleanup
|
| 583 |
+
del master_table, src_tensor, dst_tensor, y_tensor, event_type_tensor, t_tensor, last_seen_tensor, msg_tensor, data
|
| 584 |
gc.collect()
|
| 585 |
|
| 586 |
print("\n==================================================")
|
|
|
|
| 593 |
# ==========================================
|
| 594 |
|
| 595 |
if __name__ == "__main__":
|
| 596 |
+
parser = argparse.ArgumentParser(description="HillStreet Graph Generation Pipeline")
|
| 597 |
+
parser.add_argument("--start_date", type=str, default="2014-01-01", help="Date to start graph inclusion (YYYY-MM-DD)")
|
| 598 |
+
# NOTE: previously type=bool, which made "--include_structural_edges False" evaluate
|
| 599 |
+
# to True (any non-empty string is truthy). Use a proper boolean flag pair instead.
|
| 600 |
+
parser.add_argument("--include_structural_edges", dest="include_structural_edges",
|
| 601 |
+
action="store_true", default=True,
|
| 602 |
+
help="Include Lobbying, PACs, Geo-Economics (default: on)")
|
| 603 |
+
parser.add_argument("--no_structural_edges", dest="include_structural_edges",
|
| 604 |
+
action="store_false",
|
| 605 |
+
help="Exclude structural edges; keep only trade edges")
|
| 606 |
+
# --- Phase 3 node-feature options ---
|
| 607 |
+
parser.add_argument("--skip_node_features", action="store_true",
|
| 608 |
+
help="Skip Phase 3 node-feature generation (edges/shards only)")
|
| 609 |
+
parser.add_argument("--trades_csv", type=str,
|
| 610 |
+
default="data/processed/ml_dataset_continuous.csv",
|
| 611 |
+
help="Transactions CSV used for performance stats & categorical embeddings")
|
| 612 |
+
parser.add_argument("--snapshot_date", type=str, default=None,
|
| 613 |
+
help="As-of date for time-varying node features (YYYY-MM-DD). "
|
| 614 |
+
"Defaults to the latest event date in the transactions CSV.")
|
| 615 |
+
args = parser.parse_args()
|
| 616 |
+
|
| 617 |
+
# 1. Setup Directories
|
| 618 |
+
EDGE_DIR = "data/processed/master_edges_parquet"
|
| 619 |
+
REQUIRED_EDGES = [
|
| 620 |
+
"edges_trades.parquet", "edges_lobbying.parquet",
|
| 621 |
+
"edges_camp_fin.parquet", "edges_geo.parquet"
|
| 622 |
+
]
|
| 623 |
|
| 624 |
# 2. Check for Phase 1 & 2 Persistence
|
| 625 |
+
phase2_done = all(os.path.exists(os.path.join(EDGE_DIR, f)) for f in REQUIRED_EDGES)
|
| 626 |
|
| 627 |
if phase2_done:
|
| 628 |
print(f" -> Found existing edge parquets in {EDGE_DIR}. Skipping Phases 1 & 2.")
|
|
|
|
| 633 |
df_trades, df_lobbying, df_camp_fin, df_geo, cw_2012, cw_2017, cw_cat = load_and_standardize_events()
|
| 634 |
EDGE_DIR, all_msg_cols = broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat)
|
| 635 |
|
| 636 |
+
# 3. Assembly & PyG Sharding (Phase 4)
|
| 637 |
+
# Must run before node features: build_node_features aligns to the node-id maps
|
| 638 |
+
# (src_id_map.npy / dst_id_map.npy) that this step writes.
|
| 639 |
+
shard_paths = generate_hillstreet_dataset(
|
| 640 |
+
edge_dir=EDGE_DIR,
|
| 641 |
+
start_date=args.start_date,
|
| 642 |
+
include_structural_edges=args.include_structural_edges
|
| 643 |
)
|
| 644 |
+
|
| 645 |
+
# 4. Phase 3: Static node features aligned to the Phase-4 maps
|
| 646 |
+
if args.skip_node_features:
|
| 647 |
+
print("\n -> Skipping Phase 3 node-feature generation (--skip_node_features).")
|
| 648 |
+
else:
|
| 649 |
+
# Ensure the project root is on sys.path regardless of how this script was
|
| 650 |
+
# launched (python src/temporal_data.py vs python -m src.temporal_data).
|
| 651 |
+
# __file__ is .../src/temporal_data.py, so two .parent calls reach the root.
|
| 652 |
+
import sys
|
| 653 |
+
from pathlib import Path as _Path
|
| 654 |
+
_project_root = str(_Path(__file__).resolve().parent.parent)
|
| 655 |
+
if _project_root not in sys.path:
|
| 656 |
+
sys.path.insert(0, _project_root)
|
| 657 |
+
from src.data_prep.node_features import build_node_features
|
| 658 |
+
build_node_features(
|
| 659 |
+
map_dir="data/processed/pyg_graph",
|
| 660 |
+
trades_csv=args.trades_csv,
|
| 661 |
+
processed_dir="data/processed",
|
| 662 |
+
snapshot_date=args.snapshot_date,
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
print(f"\nSUCCESS: HillStreet Generation Pipeline Fully Complete.")
|
| 666 |
+
print(f" -> Graph timeline starts: {args.start_date}")
|
| 667 |
+
print(f" -> Shards: {len(shard_paths)} files saved to data/processed/pyg_graph/")
|
| 668 |
+
if not args.skip_node_features:
|
| 669 |
+
print(f" -> Node features: data/processed/node_features_static.pt")
|