benroodman commited on
Commit
3609368
·
verified ·
1 Parent(s): 6b1a972

Upload 5 files

Browse files
src/build_campaign_events.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import glob
3
+ import os
4
+ from tqdm import tqdm
5
+ import sys
6
+
7
+ # Get the absolute path to the project root (two directories up from data_prep)
8
+ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
9
+ if project_root not in sys.path:
10
+ sys.path.append(project_root)
11
+ import config
12
+
13
+ def load_legislator_map():
14
+ if os.path.exists(config.LEGISLATORS_CROSSWALK_PATH):
15
+ # Added low_memory=False to suppress DtypeWarnings
16
+ df = pd.read_csv(config.LEGISLATORS_CROSSWALK_PATH, low_memory=False)
17
+ if 'id_opensecrets' in df.columns and 'id_bioguide' in df.columns:
18
+ # Drop duplicates to prevent InvalidIndexError during mapping
19
+ mapping_df = df[['id_opensecrets', 'id_bioguide']].dropna().drop_duplicates(subset=['id_opensecrets'])
20
+ return mapping_df.set_index('id_opensecrets')['id_bioguide'].to_dict()
21
+ print(f"WARNING: Legislator crosswalk not found at {config.LEGISLATORS_CROSSWALK_PATH}.")
22
+ return {}
23
+
24
+ def build_campaign_events():
25
+ print("Building Campaign Finance Event Stream (Using Filing Dates)...")
26
+
27
+ cid_to_bioguide = load_legislator_map()
28
+ all_events = []
29
+
30
+ # --- Step 1: Corporate PACs ---
31
+ pac_files = glob.glob(str(config.CAMPAIGN_FINANCE_DIR / config.CAMPAIGN_PACS_PATTERN))
32
+
33
+ print(f"Found {len(pac_files)} PAC files.")
34
+ for f in tqdm(pac_files, desc="Processing PAC Files"):
35
+ df = pd.read_csv(f, on_bad_lines='skip', low_memory=False)
36
+
37
+ if 'estimated_filing_date' not in df.columns:
38
+ continue
39
+
40
+ df = df.dropna(subset=['CID', 'RealCode', 'estimated_filing_date'])
41
+
42
+ # Safely map to BioGuide IDs using the deduplicated dictionary
43
+ df['bioguide_id'] = df['CID'].map(cid_to_bioguide)
44
+ df = df.dropna(subset=['bioguide_id'])
45
+
46
+ df = df[['estimated_filing_date', 'RealCode', 'bioguide_id', 'Amount']].copy()
47
+ all_events.append(df)
48
+
49
+ # --- Step 2: 527 Expenditures ---
50
+ if os.path.exists(config.DATA_527_EXPENDITURES_PATH):
51
+ print("\nProcessing 527 Expenditures...")
52
+ exp_df = pd.read_csv(config.DATA_527_EXPENDITURES_PATH, on_bad_lines='skip', low_memory=False)
53
+ cmtes_df = pd.read_csv(config.DATA_527_COMMITTEES_PATH, on_bad_lines='skip', low_memory=False)
54
+
55
+ if 'estimated_filing_date' in exp_df.columns:
56
+ ein_to_industry = cmtes_df.set_index('EIN')['PrimCode'].to_dict()
57
+
58
+ exp_df['bioguide_id'] = exp_df['RecipID'].map(cid_to_bioguide)
59
+ exp_df['RealCode'] = exp_df['EIN'].map(ein_to_industry)
60
+
61
+ exp_df = exp_df.dropna(subset=['bioguide_id', 'RealCode', 'estimated_filing_date'])
62
+ exp_df = exp_df[['estimated_filing_date', 'RealCode', 'bioguide_id', 'Amount']].copy()
63
+ all_events.append(exp_df)
64
+ else:
65
+ print("Skipping 527 Expenditures: 'estimated_filing_date' missing.")
66
+
67
+ # --- Step 3: Aggregation ---
68
+ if all_events:
69
+ print("\nConcatenating and Aggregating Events...")
70
+ full_df = pd.concat(all_events, ignore_index=True)
71
+
72
+ # Parse dates
73
+ tqdm.pandas(desc="Parsing Dates")
74
+ full_df['estimated_filing_date'] = pd.to_datetime(full_df['estimated_filing_date'], errors='coerce')
75
+ full_df = full_df.dropna(subset=['estimated_filing_date'])
76
+
77
+ # Aggregate to Weekly "Pulses"
78
+ full_df = full_df.set_index('estimated_filing_date')
79
+
80
+ # Group and sum
81
+ agg_df = full_df.groupby([pd.Grouper(freq='W'), 'RealCode', 'bioguide_id'])['Amount'].sum().reset_index()
82
+
83
+ agg_df.rename(columns={'estimated_filing_date': 'date', 'RealCode': 'industry_code', 'Amount': 'weight'}, inplace=True)
84
+ agg_df['event_type'] = 'DONATION'
85
+
86
+ agg_df.to_csv(config.CAMPAIGN_FINANCE_EVENTS_PATH, index=False)
87
+ print(f"\nSUCCESS: Saved {len(agg_df)} Campaign Events to {config.CAMPAIGN_FINANCE_EVENTS_PATH}")
88
+ else:
89
+ print("\nNo Campaign Events found.")
90
+
91
+ if __name__ == "__main__":
92
+ build_campaign_events()
src/build_geographical_edges.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import os
4
+ import re
5
+ import gc
6
+ from datetime import datetime
7
+ from concurrent.futures import ProcessPoolExecutor, as_completed
8
+ from tqdm import tqdm
9
+
10
+ # --- CONFIGURATION ---
11
+ RAW_DATA_DIR = "data/raw"
12
+ CBP_DIR = os.path.join(RAW_DATA_DIR, "district_industries")
13
+ NAICS_DIR = os.path.join(RAW_DATA_DIR, "industry_codes_NAICS")
14
+ OUTPUT_FILE = "data/processed/events_geographical_industry.csv"
15
+ MAX_WORKERS = os.cpu_count() - 1 or 1
16
+
17
+ STATE_ABBREV = {
18
+ 'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA',
19
+ 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA',
20
+ 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA',
21
+ 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD',
22
+ 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS',
23
+ 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH',
24
+ 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC',
25
+ 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA',
26
+ 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN',
27
+ 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA',
28
+ 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY', 'District of Columbia': 'DC',
29
+ 'Puerto Rico': 'PR'
30
+ }
31
+
32
+ def load_crosswalks():
33
+ print("[INFO] Loading NAICS-to-SIC Crosswalks...")
34
+ cw_2012 = pd.read_csv(os.path.join(NAICS_DIR, "2012-NAICS-to-SIC-Crosswalk.csv"), dtype=str)
35
+ cw_2017 = pd.read_csv(os.path.join(NAICS_DIR, "2017-NAICS-to-SIC-Crosswalk.csv"), dtype=str)
36
+
37
+ dict_2012 = cw_2012.groupby('NAICS')['SIC'].apply(list).to_dict()
38
+ dict_2017 = cw_2017.groupby('NAICS')['SIC'].apply(list).to_dict()
39
+ return dict_2012, dict_2017
40
+
41
+ def load_release_dates():
42
+ print("[INFO] Loading Survey Release Dates...")
43
+ release_df = pd.read_csv(os.path.join(CBP_DIR, "survey_release_dates.csv"))
44
+ release_df['date'] = pd.to_datetime(release_df['date'], format='mixed')
45
+ return dict(zip(release_df['survey_reference_year'], release_df['date']))
46
+
47
+ def load_legislators():
48
+ print("[INFO] Loading Legislator Metadata...")
49
+ terms_df = pd.read_csv(os.path.join(RAW_DATA_DIR, "congress_terms_all_github.csv"), low_memory=False)
50
+ terms_df['start'] = pd.to_datetime(terms_df['start'])
51
+ terms_df['end'] = pd.to_datetime(terms_df['end'])
52
+ terms_df['district'] = terms_df['district'].replace('At Large', 0)
53
+ terms_df['district'] = pd.to_numeric(terms_df['district'], errors='coerce')
54
+ return terms_df
55
+
56
+ def parse_geography(name_str):
57
+ if pd.isna(name_str):
58
+ return None, None
59
+ match = re.search(r'(?:Congressional District (\d+)|District \(At Large\)).*?,\s*(.*)', str(name_str), re.IGNORECASE)
60
+ if match:
61
+ dist_str = match.group(1)
62
+ district = int(dist_str) if dist_str else 0
63
+ state_name = match.group(2).strip()
64
+ state_abbr = STATE_ABBREV.get(state_name, None)
65
+ return state_abbr, district
66
+ return None, None
67
+
68
+ def get_active_legislator(terms_df, state, district, release_date):
69
+ if state is None or pd.isna(district):
70
+ return None
71
+ active = terms_df[
72
+ (terms_df['state'] == state) &
73
+ (terms_df['district'] == district) &
74
+ (terms_df['start'] <= release_date) &
75
+ (terms_df['end'] >= release_date) &
76
+ (terms_df['type'] == 'rep')
77
+ ]
78
+ if not active.empty:
79
+ return active.iloc[0]['id_bioguide']
80
+ return None
81
+
82
+ def process_chunk(chunk, year, release_date, crosswalk, terms_df):
83
+ edges = []
84
+ cols = chunk.columns
85
+
86
+ # Safely find columns dynamically to handle schema evolution
87
+ col_name = next((c for c in cols if 'NAME' in c), None)
88
+ col_naics = next((c for c in cols if 'NAICS' in c and 'LABEL' not in c), None)
89
+ col_estab = next((c for c in cols if 'ESTAB' in c), None)
90
+ col_emp = next((c for c in cols if 'EMP' in c and 'EMPSZES' not in c), None)
91
+ col_payann = next((c for c in cols if 'PAYANN' in c), None)
92
+
93
+ if not all([col_name, col_naics, col_estab, col_emp, col_payann]):
94
+ return pd.DataFrame()
95
+
96
+ # --- THE FIX: FILTER OUT GRANULAR ROWS ---
97
+ naics_raw = chunk[col_naics].astype(str).str.strip()
98
+
99
+ # Match ONLY top-level 2-digit sectors (e.g., '11', '11----') or hyphenated groups ('31-33')
100
+ is_top_level = naics_raw.str.match(r'^(\d{2}-*|\d{2}-\d{2}-*)$')
101
+ is_not_total = ~naics_raw.str.startswith('00') # Exclude the "All Sectors" total
102
+
103
+ # This perfectly standardizes 2010-2012 to match the 2013+ methodology
104
+ chunk = chunk[is_top_level & is_not_total].copy()
105
+
106
+ # Clean the NAICS codes to the standard format for our crosswalk
107
+ # Removes trailing dashes the Census sometimes uses (e.g. '11----' -> '11')
108
+ chunk[col_naics] = chunk[col_naics].astype(str).str.replace(r'-+$', '', regex=True).str.strip()
109
+
110
+ for c in [col_estab, col_emp, col_payann]:
111
+ chunk[c] = chunk[c].astype(str).str.replace(',', '')
112
+ chunk[c] = pd.to_numeric(chunk[c], errors='coerce')
113
+
114
+ chunk = chunk.dropna(subset=[col_estab, col_emp, col_payann], how='all')
115
+
116
+ # Local cache to prevent redundant crosswalk scans inside the chunk
117
+ resolved_sics_cache = {}
118
+
119
+ for _, row in chunk.iterrows():
120
+ naics_code = str(row[col_naics]).strip()
121
+
122
+ # --- PREFIX-MATCHING LOGIC ---
123
+ if naics_code not in resolved_sics_cache:
124
+ sics = set()
125
+ # Handle hyphenated aggregated sectors (e.g. "31-33")
126
+ if '-' in naics_code:
127
+ try:
128
+ start, end = naics_code.split('-')
129
+ prefixes = tuple(str(p) for p in range(int(start), int(end)+1))
130
+ except:
131
+ prefixes = (naics_code,)
132
+ else:
133
+ prefixes = (naics_code,)
134
+
135
+ # Scan crosswalk for any 6-digit NAICS that starts with this prefix
136
+ for cw_naics, cw_sics in crosswalk.items():
137
+ if str(cw_naics).startswith(prefixes):
138
+ sics.update(cw_sics)
139
+ resolved_sics_cache[naics_code] = list(sics)
140
+
141
+ sic_list = resolved_sics_cache[naics_code]
142
+
143
+ if not sic_list:
144
+ continue
145
+
146
+ state, dist = parse_geography(row[col_name])
147
+ bioguide_id = get_active_legislator(terms_df, state, dist, release_date)
148
+
149
+ if bioguide_id:
150
+ for sic in sic_list:
151
+ edges.append({
152
+ 'bioguide_id': bioguide_id,
153
+ 'sic_code': sic,
154
+ 'release_date': release_date,
155
+ 'reference_year': year,
156
+ 'establishments': row[col_estab],
157
+ 'employment': row[col_emp],
158
+ 'annual_payroll': row[col_payann]
159
+ })
160
+
161
+ return pd.DataFrame(edges)
162
+
163
+ def process_cbp_file(file_path, year, release_date, crosswalk, terms_df):
164
+ print(f"\n[INFO] Reading Year {year} (Release: {release_date.date()})")
165
+
166
+ chunk_size = 25000
167
+ chunks = []
168
+ for chunk in pd.read_csv(file_path, chunksize=chunk_size, dtype=str):
169
+ chunks.append(chunk)
170
+
171
+ print(f" Spawned {len(chunks)} chunks. Processing across {MAX_WORKERS} cores...")
172
+
173
+ results = []
174
+ with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor:
175
+ futures = {
176
+ executor.submit(process_chunk, c, year, release_date, crosswalk, terms_df): i
177
+ for i, c in enumerate(chunks)
178
+ }
179
+
180
+ for future in tqdm(as_completed(futures), total=len(chunks), desc=f"Year {year}", unit="chunk"):
181
+ res_df = future.result()
182
+ if not res_df.empty:
183
+ results.append(res_df)
184
+
185
+ if results:
186
+ return pd.concat(results, ignore_index=True)
187
+ return pd.DataFrame()
188
+
189
+ def main():
190
+ print("=====================================================")
191
+ print(" BUILDING INDUSTRY-GEOGRAPHICAL EDGES (CBP)")
192
+ print(f" Mode: Multiprocessing enabled ({MAX_WORKERS} Workers)")
193
+ print("=====================================================")
194
+
195
+ cw_2012, cw_2017 = load_crosswalks()
196
+ release_dates = load_release_dates()
197
+ terms_df = load_legislators()
198
+
199
+ all_edges = []
200
+
201
+ for year in range(2010, 2024):
202
+ file_name = f"{year}_CB_estimates.csv" if year <= 2012 else f"{year}_CB_survey.csv"
203
+ file_path = os.path.join(CBP_DIR, file_name)
204
+
205
+ if not os.path.exists(file_path):
206
+ continue
207
+
208
+ release_date = release_dates.get(year)
209
+ if not release_date:
210
+ continue
211
+
212
+ active_crosswalk = cw_2012 if year <= 2012 else cw_2017
213
+ df_edges = process_cbp_file(file_path, year, release_date, active_crosswalk, terms_df)
214
+
215
+ if not df_edges.empty:
216
+ all_edges.append(df_edges)
217
+
218
+ print("\n[INFO] Concatenating and saving final edge list...")
219
+ if all_edges:
220
+ final_df = pd.concat(all_edges, ignore_index=True)
221
+ os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True)
222
+ final_df.to_csv(OUTPUT_FILE, index=False)
223
+
224
+ print(f"[SUCCESS] Saved {len(final_df)} geographical-industry edges to {OUTPUT_FILE}.")
225
+ print(f"[STATS] Unique Legislators Mapped: {final_df['bioguide_id'].nunique()}")
226
+ print(f"[STATS] Unique SIC Sectors Mapped: {final_df['sic_code'].nunique()}")
227
+ else:
228
+ print("[WARNING] No edges generated.")
229
+
230
+ if __name__ == "__main__":
231
+ main()
src/build_lobbying_events.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ from tqdm import tqdm
4
+ import pandas as pd
5
+ import config
6
+
7
+ def load_crosswalks():
8
+ """Loads NAICS->SIC, SIC->Ticker, and Legislator Mappings."""
9
+ print("Loading Crosswalks...")
10
+
11
+ naics_sic = pd.read_csv(config.NAICS_TO_SIC_PATH)
12
+ naics_sic['NAICS'] = naics_sic['NAICS'].astype(str).str.replace(r'\.0$', '', regex=True).str.zfill(6)
13
+ naics_sic['SIC'] = naics_sic['SIC'].astype(str).str.replace(r'\.0$', '', regex=True).str.zfill(4)
14
+ naics_to_sic_map = naics_sic.groupby('NAICS')['SIC'].apply(list).to_dict()
15
+
16
+ if os.path.exists(config.COMPANY_SIC_DATA_PATH):
17
+ sic_data = pd.read_csv(config.COMPANY_SIC_DATA_PATH)
18
+ sic_data['sic'] = sic_data['sic'].astype(str).str.replace(r'\.0$', '', regex=True).str.zfill(4)
19
+ sic_to_ticker_map = sic_data.groupby('sic')['ticker'].apply(list).to_dict()
20
+ else:
21
+ print(f"WARNING: {config.COMPANY_SIC_DATA_PATH} not found.")
22
+ sic_to_ticker_map = {}
23
+
24
+ if os.path.exists(config.LEGISLATORS_CROSSWALK_PATH):
25
+ leg_df = pd.read_csv(config.LEGISLATORS_CROSSWALK_PATH, low_memory=False)
26
+ leg_map_df = leg_df[['id_icpsr', 'id_bioguide']].dropna().drop_duplicates()
27
+ leg_map_df['id_icpsr'] = leg_map_df['id_icpsr'].astype(int)
28
+ icpsr_to_bioguide = leg_map_df.set_index('id_icpsr')['id_bioguide'].to_dict()
29
+ else:
30
+ print(f"WARNING: Legislator crosswalk not found at {config.LEGISLATORS_CROSSWALK_PATH}. Voting edges will fail.")
31
+ icpsr_to_bioguide = {}
32
+
33
+ return naics_to_sic_map, sic_to_ticker_map, icpsr_to_bioguide
34
+
35
+ def parse_bill_ids(id_str):
36
+ try:
37
+ if pd.isna(id_str): return []
38
+ matches = re.findall(r'[a-zA-Z0-9]+-[0-9]+', str(id_str))
39
+ return [m.lower().strip() for m in matches]
40
+ except:
41
+ return []
42
+
43
+ def build_lobbying_events():
44
+ print("Building Lobbying & Voting Event Stream (Using Filing Dates)...")
45
+
46
+ bills_df = pd.read_csv(config.LOBBYING_BILLS_PATH)
47
+ clients_df = pd.read_csv(config.LOBBYING_CLIENTS_PATH)
48
+ reports_df = pd.read_csv(config.LOBBYING_REPORTS_PATH)
49
+ issues_df = pd.read_csv(config.LOBBYING_ISSUES_PATH)
50
+
51
+ has_votes = os.path.exists(config.VOTEVIEW_VOTES_PATH) and os.path.exists(config.VOTEVIEW_ROLLCALLS_PATH)
52
+ if has_votes:
53
+ print("Loading VoteView Data...")
54
+ votes_df = pd.read_csv(config.VOTEVIEW_VOTES_PATH)
55
+ rollcalls_df = pd.read_csv(config.VOTEVIEW_ROLLCALLS_PATH, low_memory=False)
56
+
57
+ bills_df['bill_id'] = bills_df['bill_id'].astype(str).str.lower().str.strip()
58
+ reports_df['report_uuid'] = reports_df['report_uuid'].astype(str)
59
+ reports_df['lob_id'] = reports_df['lob_id'].astype(str)
60
+ clients_df['lob_id'] = clients_df['lob_id'].astype(str)
61
+
62
+ naics_map, sic_ticker_map, icpsr_map = load_crosswalks()
63
+
64
+ # --- Step 1: Map Clients to Tickers ---
65
+ clients_df['naics_str'] = clients_df['naics'].astype(str).str.replace(r'\.0$', '', regex=True).str.zfill(6)
66
+ client_ticker_records = []
67
+
68
+ print("Mapping Clients to Tickers...")
69
+ for idx, row in tqdm(clients_df.iterrows(), total=len(clients_df), desc="Mapping Clients"):
70
+ target_tickers = []
71
+ for sic in naics_map.get(row['naics_str'], []):
72
+ target_tickers.extend(sic_ticker_map.get(sic, []))
73
+ if target_tickers:
74
+ for t in set(target_tickers):
75
+ client_ticker_records.append({'lob_id': row['lob_id'], 'ticker': t})
76
+
77
+ client_ticker_df = pd.DataFrame(client_ticker_records)
78
+ print(f"Mapped {client_ticker_df['lob_id'].nunique()} clients to {client_ticker_df['ticker'].nunique()} unique tickers.")
79
+
80
+ if client_ticker_df.empty:
81
+ print("No clients mapped to tickers. Exiting.")
82
+ return
83
+
84
+ # --- Step 2: Link Reports to Bills ---
85
+ print("Parsing Bill IDs from Issues...")
86
+ tqdm.pandas(desc="Parsing Bill IDs")
87
+ issues_with_bills = issues_df.dropna(subset=['bill_id_agg']).copy()
88
+ issues_with_bills['bill_id_list'] = issues_with_bills['bill_id_agg'].progress_apply(parse_bill_ids)
89
+
90
+ issues_exploded = issues_with_bills.explode('bill_id_list').rename(columns={'bill_id_list': 'bill_id'})
91
+ issues_exploded['report_uuid'] = issues_exploded['report_uuid'].astype(str)
92
+ issues_exploded['bill_id'] = issues_exploded['bill_id'].astype(str)
93
+
94
+ print("Merging Issues with Reports...")
95
+ bill_client_chain = pd.merge(
96
+ issues_exploded[['bill_id', 'report_uuid']],
97
+ reports_df[['report_uuid', 'lob_id', 'estimated_filing_date']],
98
+ on='report_uuid',
99
+ how='inner'
100
+ )
101
+
102
+ # NEW OPTIMIZATION: Drop duplicates BEFORE merging to save massive amounts of memory
103
+ base_chain = bill_client_chain[['lob_id', 'bill_id', 'estimated_filing_date']].drop_duplicates()
104
+ ticker_bill_df = pd.merge(base_chain, client_ticker_df, on='lob_id').drop(columns=['lob_id'])
105
+ ticker_bill_df = ticker_bill_df.drop_duplicates()
106
+
107
+ all_events_dfs = []
108
+
109
+ # --- Step 3: Strong Edges (Sponsorship) ---
110
+ if getattr(config, 'INCLUDE_LOBBYING_SPONSORSHIP', True):
111
+ print("Generating Strong Edges (Sponsorship)...")
112
+ strong_df = pd.merge(ticker_bill_df, bills_df[['bill_id', 'bioguide_id']], on='bill_id', how='inner')
113
+ strong_df = strong_df.dropna(subset=['bioguide_id', 'estimated_filing_date'])
114
+
115
+ # Vectorized Event Creation (Replaces the 9-minute loop)
116
+ strong_df = strong_df[['estimated_filing_date', 'ticker', 'bioguide_id']].drop_duplicates()
117
+ strong_df.rename(columns={'estimated_filing_date': 'date'}, inplace=True)
118
+ strong_df['event_type'] = 'LOBBY_STRONG'
119
+ strong_df['weight'] = 1.0
120
+
121
+ print(f"Valid Sponsorship Connections Found: {len(strong_df)}")
122
+ all_events_dfs.append(strong_df)
123
+ else:
124
+ print("Skipping Strong Edges (Sponsorship) per config.")
125
+
126
+ # --- Step 4: Weak Edges (Voting) ---
127
+ if getattr(config, 'INCLUDE_LOBBYING_VOTING', True) and has_votes:
128
+ print("Generating Weak Edges (Voting)...")
129
+ if 'bill_number' in bills_df.columns and 'bill_number' in rollcalls_df.columns:
130
+ lobbied_bills = ticker_bill_df['bill_id'].unique()
131
+
132
+ target_bills_df = bills_df[bills_df['bill_id'].isin(lobbied_bills)][['bill_id', 'bill_type', 'bill_number', 'congress_number']].copy()
133
+ target_bills_df['clean_type'] = target_bills_df['bill_type'].astype(str).str.replace(r'[^a-zA-Z]', '', regex=True).str.upper()
134
+ target_bills_df['clean_num'] = target_bills_df['bill_number'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
135
+ target_bills_df['vv_bill_number'] = target_bills_df['clean_type'] + target_bills_df['clean_num']
136
+ target_bills_df['congress_number'] = target_bills_df['congress_number'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
137
+
138
+ rollcalls_merge = rollcalls_df[['congress', 'rollnumber', 'bill_number']].copy()
139
+ rollcalls_merge['vv_bill_number'] = rollcalls_merge['bill_number'].astype(str).str.replace(r'[^a-zA-Z0-9]', '', regex=True).str.upper()
140
+ rollcalls_merge['congress'] = rollcalls_merge['congress'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
141
+ rollcalls_merge['rollnumber'] = rollcalls_merge['rollnumber'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
142
+
143
+ bill_votes_map = pd.merge(
144
+ target_bills_df[['bill_id', 'congress_number', 'vv_bill_number']],
145
+ rollcalls_merge[['congress', 'rollnumber', 'vv_bill_number']],
146
+ left_on=['congress_number', 'vv_bill_number'],
147
+ right_on=['congress', 'vv_bill_number']
148
+ )
149
+
150
+ bill_votes_map = bill_votes_map[~bill_votes_map['congress'].isin(['nan', 'None', ''])]
151
+ bill_votes_map = bill_votes_map[~bill_votes_map['rollnumber'].isin(['nan', 'None', ''])]
152
+
153
+ yea_votes = votes_df[votes_df['cast_code'].isin([1, 2, 3])].copy()
154
+ yea_votes['bioguide_id'] = yea_votes['icpsr'].map(icpsr_map)
155
+ yea_votes = yea_votes.dropna(subset=['bioguide_id', 'congress', 'rollnumber'])
156
+
157
+ yea_votes['congress'] = yea_votes['congress'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
158
+ yea_votes['rollnumber'] = yea_votes['rollnumber'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip()
159
+ yea_votes = yea_votes[~yea_votes['congress'].isin(['nan', 'None', ''])]
160
+
161
+ print("Mapping Legislator votes to Bills...")
162
+ bill_to_legislator = pd.merge(
163
+ bill_votes_map[['bill_id', 'congress', 'rollnumber']],
164
+ yea_votes[['congress', 'rollnumber', 'bioguide_id']],
165
+ on=['congress', 'rollnumber']
166
+ )
167
+
168
+ bill_to_legislator = bill_to_legislator[['bill_id', 'bioguide_id']].drop_duplicates()
169
+
170
+ print("Merging Voting Records with Lobbying Clients (Chunked to prevent Memory Error)...")
171
+
172
+ # NEW OPTIMIZATION: Process one Ticker at a time to prevent Cartesian explosion
173
+ weak_events_list = []
174
+ valid_bills_with_votes = bill_to_legislator['bill_id'].unique()
175
+ tb_subset = ticker_bill_df[ticker_bill_df['bill_id'].isin(valid_bills_with_votes)]
176
+
177
+ for ticker, group in tqdm(tb_subset.groupby('ticker'), desc="Building Weak Edges"):
178
+ merged = pd.merge(group[['bill_id', 'estimated_filing_date']], bill_to_legislator, on='bill_id')
179
+ unique_edges = merged[['estimated_filing_date', 'bioguide_id']].drop_duplicates()
180
+ unique_edges['ticker'] = ticker
181
+ weak_events_list.append(unique_edges)
182
+
183
+ if weak_events_list:
184
+ weak_df = pd.concat(weak_events_list, ignore_index=True)
185
+ weak_df.rename(columns={'estimated_filing_date': 'date'}, inplace=True)
186
+ weak_df['event_type'] = 'LOBBY_WEAK'
187
+ weak_df['weight'] = 0.5
188
+ print(f"Valid Voting Connections Found: {len(weak_df)}")
189
+ all_events_dfs.append(weak_df)
190
+ else:
191
+ print("Valid Voting Connections Found: 0")
192
+ else:
193
+ print("Skipping Weak Edges (Voting) per config.")
194
+
195
+ if all_events_dfs:
196
+ final_events_df = pd.concat(all_events_dfs, ignore_index=True)
197
+ print(f"\nSUCCESS: Generated {len(final_events_df)} total Lobbying/Voting Events.")
198
+ final_events_df.to_csv(config.LOBBYING_EVENTS_PATH, index=False)
199
+ else:
200
+ print("\nGenerated 0 total events.")
201
+
202
+ if __name__ == "__main__":
203
+ build_lobbying_events()
src/config.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+
4
+ # Project Root (Relative to this config file)
5
+ # Works whether installed as package or run from source
6
+ try:
7
+ import importlib.resources as pkg_resources
8
+ PROJECT_ROOT = Path(pkg_resources.files("src").parent)
9
+ except (ImportError, AttributeError):
10
+ PROJECT_ROOT = Path(__file__).parent.parent.resolve()
11
+
12
+ # Allow override via environment variable
13
+ PROJECT_ROOT = Path(os.getenv("CHOCOLATE_PROJECT_ROOT", PROJECT_ROOT))
14
+
15
+ # Data Directories
16
+ RAW_DATA_DIR = PROJECT_ROOT / "data" / "raw"
17
+ PROCESSED_DATA_DIR = PROJECT_ROOT / "data" / "processed"
18
+ LOBBYING_DIR = RAW_DATA_DIR / "lobbying_data_lobbyview"
19
+ CAMPAIGN_FINANCE_DIR = RAW_DATA_DIR / "campaign_finance_open_secrets"
20
+ DATA_527_DIR = RAW_DATA_DIR / "527_data_open_secrets"
21
+ INDUSTRY_CROSSWALK_DIR = RAW_DATA_DIR / "industry_codes_NAICS"
22
+
23
+ # --- Feature Flags ---
24
+ INCLUDE_LOBBYING_SPONSORSHIP = True
25
+ INCLUDE_LOBBYING_VOTING = True
26
+
27
+ # --- Specific Data Paths ---
28
+ # Lobbying & Votes
29
+ LOBBYING_BILLS_PATH = LOBBYING_DIR / "bills.csv"
30
+ LOBBYING_CLIENTS_PATH = LOBBYING_DIR / "clients.csv"
31
+ LOBBYING_REPORTS_PATH = LOBBYING_DIR / "reports.csv"
32
+ LOBBYING_ISSUES_PATH = LOBBYING_DIR / "issue_text.csv"
33
+
34
+ # VoteView Paths
35
+ VOTEVIEW_VOTES_PATH = RAW_DATA_DIR / "HSall_votes.csv"
36
+ VOTEVIEW_ROLLCALLS_PATH = RAW_DATA_DIR / "HSall_rollcalls.csv"
37
+
38
+ # Campaign Finance Paths
39
+ CAMPAIGN_PACS_PATTERN = "pacs*.csv"
40
+ DATA_527_EXPENDITURES_PATH = DATA_527_DIR / "Expenditures.csv"
41
+ DATA_527_COMMITTEES_PATH = DATA_527_DIR / "Cmtes527.csv"
42
+
43
+ # Crosswalks
44
+ NAICS_TO_SIC_PATH = INDUSTRY_CROSSWALK_DIR / "2017-NAICS-to-SIC-Crosswalk.csv"
45
+ COMPANY_SIC_DATA_PATH = RAW_DATA_DIR / "company_sic_data.csv"
46
+ LEGISLATORS_CROSSWALK_PATH = RAW_DATA_DIR / "congress_terms_all_github.csv"
47
+
48
+ # Outputs
49
+ LOBBYING_EVENTS_PATH = PROCESSED_DATA_DIR / "events_lobbying.csv"
50
+ CAMPAIGN_FINANCE_EVENTS_PATH = PROCESSED_DATA_DIR / "events_campaign_finance.csv"
51
+
52
+ # Make sure local directories exist
53
+ PROCESSED_DATA_DIR.mkdir(parents=True, exist_ok=True)
54
+
55
+ # Convert to strings for backward compatibility
56
+ PROJECT_ROOT = str(PROJECT_ROOT)
57
+ RAW_DATA_DIR = str(RAW_DATA_DIR)
58
+ PROCESSED_DATA_DIR = str(PROCESSED_DATA_DIR)
src/temporal_data.py ADDED
@@ -0,0 +1,865 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ src/temporal_data.py
3
+ Phase 1: Data Ingestion and Standardization
4
+ """
5
+ import pandas as pd
6
+ import numpy as np
7
+ import os
8
+ from sklearn.preprocessing import MultiLabelBinarizer
9
+ import pyarrow.parquet as pq
10
+ import argparse
11
+ import torch
12
+ import duckdb
13
+ import gc
14
+ try:
15
+ from torch_geometric.data import TemporalData
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."""
53
+ missing = [col for col in required_columns if col not in df.columns]
54
+ if missing:
55
+ raise ValueError(f"[{dataset_name}] Missing required columns: {missing}\n"
56
+ f"Available columns: {list(df.columns)}")
57
+
58
+ def load_and_standardize_events(data_dir="data"):
59
+ """
60
+ PHASE 1: Load the four primary data sources and map them to a unified schema.
61
+ Returns standardized pandas DataFrames for each event type.
62
+ """
63
+ print("==================================================")
64
+ print("PHASE 1: DATA INGESTION & STANDARDIZATION")
65
+ print("==================================================")
66
+
67
+ # ---------------------------------------------------------
68
+ # 1.1 TARGET EDGES (Trades)
69
+ # ---------------------------------------------------------
70
+ path_trades = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["trades"])
71
+ print(f"Loading Trades from: {path_trades}")
72
+ df_trades = pd.read_csv(path_trades)
73
+
74
+ # 17 market features + 3 trade mechanics
75
+ market_features = [
76
+ 'vol_20d', 'vol_60d', 'vol_120d', 'vol_252d', 'vol_of_vol_60d', 'vol_trend', 'idio_vol_60d',
77
+ 'mom_60d', 'mom_252d', 'reversal_21d',
78
+ 'beta_20d', 'beta_60d', 'downside_beta', 'excess_vol', 'max_dd_60d', 'skew_60d', 'sharpe_60d'
79
+ ]
80
+ trade_features = ['Trade_Size_USD', 'Filing_Gap', 'Transaction'] # Transaction = Buy/Sell Ratio or is_buy
81
+
82
+ req_trade_cols = ['BioGuideID', 'Matched_Ticker', 'Filed'] + trade_features + market_features
83
+ validate_columns(df_trades, req_trade_cols, "Trades")
84
+
85
+ df_trades = df_trades.rename(columns={
86
+ 'BioGuideID': 'src',
87
+ 'Matched_Ticker': 'dst',
88
+ 'Filed': 'time'
89
+ })
90
+ df_trades['event_type'] = 0
91
+
92
+ # Calculate Label: e.g., Top 25% 6M Excess Return = 1.
93
+ if 'Excess_Return_6M' in df_trades.columns:
94
+ threshold = df_trades['Excess_Return_6M'].quantile(0.75)
95
+ df_trades['y'] = (df_trades['Excess_Return_6M'] >= threshold).astype(int)
96
+ else:
97
+ print("[WARNING] 'Excess_Return_6M' not found. Setting dummy target 'y' = 0")
98
+ df_trades['y'] = 0
99
+
100
+ print(f" -> Trades loaded successfully. Shape: {df_trades.shape}")
101
+
102
+ # ---------------------------------------------------------
103
+ # 1.2 LOBBYING EVENTS
104
+ # ---------------------------------------------------------
105
+ if CONFIG["INCLUDE_EDGES"].get("lobbying", True):
106
+ path_lobbying = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["lobbying"])
107
+ df_lobbying = pd.read_csv(path_lobbying)
108
+
109
+ path_lobbying = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["lobbying"])
110
+ print(f"Loading Lobbying from: {path_lobbying}")
111
+ df_lobbying = pd.read_csv(path_lobbying)
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
+ df_lobbying = df_lobbying.rename(columns={
119
+ 'bioguide_id': 'src',
120
+ 'ticker': 'dst',
121
+ time_col_lobby: 'time'
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
+ else:
132
+ print(" -> [CONFIG] Skipping Lobbying edges...")
133
+ df_lobbying = pd.DataFrame()
134
+
135
+ # ---------------------------------------------------------
136
+ # 1.3 CAMPAIGN FINANCE EVENTS
137
+ # ---------------------------------------------------------
138
+ # ---------------------------------------------------------
139
+ if CONFIG["INCLUDE_EDGES"].get("camp_fin", True):
140
+ path_camp_fin = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["camp_fin"])
141
+ df_camp_fin = pd.read_csv(path_camp_fin)
142
+
143
+ time_col_cf = 'estimated_filing_date' if 'estimated_filing_date' in df_camp_fin.columns else 'date'
144
+ validate_columns(df_camp_fin, ['bioguide_id', 'industry_code', time_col_cf, 'weight'], "Campaign Finance")
145
+
146
+ df_camp_fin = df_camp_fin.rename(columns={
147
+ 'bioguide_id': 'src',
148
+ 'industry_code': 'dst_temp', # Needs broadcasting
149
+ time_col_cf: 'time',
150
+ 'weight': 'Fin_Amt' # Assuming donation amount
151
+ })
152
+ df_camp_fin['event_type'] = 2
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
+ if CONFIG["INCLUDE_EDGES"].get("geo", True):
163
+ path_geo = os.path.join(CONFIG["DATA_DIR"], CONFIG["FILES"]["geo"])
164
+ df_geo = pd.read_csv(path_geo)
165
+
166
+ validate_columns(df_geo, ['bioguide_id', 'sic_code', 'release_date', 'establishments', 'employment', 'annual_payroll'], "Geo-Industrial")
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
+ print(f" -> Geo-Industrial loaded successfully. Shape: {df_geo.shape}")
179
+
180
+ else:
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, "cropped", "industry_codes_NAICS", "2012-NAICS-to-SIC-crosswalk.csv")
189
+ path_cw_2017 = os.path.join(data_dir, "cropped", "industry_codes_NAICS", "2017-NAICS-to-SIC-crosswalk.csv")
190
+ path_cw_cat = os.path.join(data_dir, "cropped", "industry_codes_NAICS", "2013-CAT_to_SIC_to_NAICS_mappings.csv")
191
+
192
+ cw_2012 = pd.read_csv(path_cw_2012)
193
+ cw_2017 = pd.read_csv(path_cw_2017)
194
+ cw_cat = pd.read_csv(path_cw_cat)
195
+
196
+ validate_columns(cw_cat, ['OpenSecretsCatcode', 'SICcode'], "CAT to SIC Crosswalk")
197
+ print(" -> All Data and Crosswalks successfully ingested.")
198
+ print("==================================================\n")
199
+
200
+ return df_trades, df_lobbying, df_camp_fin, df_geo, cw_2012, cw_2017, cw_cat
201
+
202
+ def broadcast_and_pad_edges(df_trades, df_lobbying, df_camp_fin, df_geo, cw_cat, data_dir="data"):
203
+ """
204
+ PHASE 2: Memory-Optimized Sector Broadcasting & Tensor Alignment
205
+ """
206
+ print("==================================================")
207
+ print("PHASE 2: OPTIMIZED BROADCASTING & ALIGNMENT")
208
+ print("==================================================")
209
+
210
+ # 1. Load and Clean Company SIC Master List
211
+ path_company_sic = os.path.join(data_dir, "cropped", "company_sic_data.csv")
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)
215
+
216
+ # 2. Fix Campaign Finance Mapping (Clean CAT/SIC strings)
217
+ df_camp_fin['dst_temp'] = df_camp_fin['dst_temp'].astype(str).str.strip().str.upper()
218
+ cw_cat['OpenSecretsCatcode'] = cw_cat['OpenSecretsCatcode'].astype(str).str.strip().str.upper()
219
+ cw_cat['SICcode'] = cw_cat['SICcode'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
220
+
221
+ # ---------------------------------------------------------
222
+ # 2.1 THE "BROADCAST" MECHANISM
223
+ # ---------------------------------------------------------
224
+ print("Broadcasting Geo-Industrial edges...")
225
+ df_geo['dst_temp'] = df_geo['dst_temp'].astype(str).str.replace(r'\.0$', '', regex=True).str.strip().str.zfill(4)
226
+ df_geo = df_geo.merge(df_comp_sic[['sic', 'ticker']], left_on='dst_temp', right_on='sic', how='inner')
227
+ df_geo = df_geo.rename(columns={'ticker': 'dst'}).drop(columns=['dst_temp', 'sic'])
228
+
229
+ print("Broadcasting Campaign Finance edges...")
230
+ df_camp_fin = df_camp_fin.merge(cw_cat[['OpenSecretsCatcode', 'SICcode']],
231
+ left_on='dst_temp', right_on='OpenSecretsCatcode', how='inner')
232
+ df_camp_fin = df_camp_fin.merge(df_comp_sic[['sic', 'ticker']],
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)
240
+ # ---------------------------------------------------------
241
+ # RESTORED: Map categorical Trade variables to numeric BEFORE downcasting
242
+ print("Mapping categorical Trade variables to numeric...")
243
+ if df_trades['Transaction'].dtype == object:
244
+ df_trades['Transaction'] = df_trades['Transaction'].astype(str).str.lower().apply(
245
+ lambda x: 1.0 if 'purchase' in x or 'buy' in x else 0.0
246
+ )
247
+
248
+ size_map = {
249
+ '$1,001 - $15,000': 1.0,
250
+ '$15,001 - $50,000': 2.0,
251
+ '$50,001 - $100,000': 3.0,
252
+ '$100,001 - $250,000': 4.0,
253
+ '$250,001 - $500,000': 5.0,
254
+ '$500,001 - $1,000,000': 6.0,
255
+ '$1,000,001 - $5,000,000': 7.0,
256
+ '$5,000,001 - $25,000,000': 8.0,
257
+ '$25,000,001 - $50,000,000': 9.0,
258
+ 'Over $50,000,000': 10.0
259
+ }
260
+ if df_trades['Trade_Size_USD'].dtype == object:
261
+ df_trades['Trade_Size_USD'] = df_trades['Trade_Size_USD'].map(size_map).fillna(0.0)
262
+
263
+ market_features = [
264
+ 'vol_20d', 'vol_60d', 'vol_120d', 'vol_252d', 'vol_of_vol_60d', 'vol_trend', 'idio_vol_60d',
265
+ 'mom_60d', 'mom_252d', 'reversal_21d',
266
+ 'beta_20d', 'beta_60d', 'downside_beta', 'excess_vol', 'max_dd_60d', 'skew_60d', 'sharpe_60d'
267
+ ]
268
+ all_msg_cols = ['Trade_Size_USD', 'Filing_Gap', 'Transaction', 'is_sponsorship', 'voted_yea', 'Fin_Amt', 'Geo_Weight'] + market_features
269
+
270
+ def align_schema(df):
271
+ # Broadcast scalar directly to bypass pandas array-copying overhead
272
+ for col in all_msg_cols:
273
+ if col not in df.columns:
274
+ df[col] = np.float32(0.0)
275
+ elif df[col].dtype != 'float32':
276
+ # Convert existing columns to float32
277
+ df[col] = df[col].astype('float32')
278
+ return df
279
+
280
+ print("Aligning D=24 schemas and downcasting to float32...")
281
+ df_trades = align_schema(df_trades)
282
+
283
+ # 2. Fix the missing target label ('y') for structural edges
284
+ df_lobbying['y'] = -1
285
+ df_camp_fin['y'] = -1
286
+ df_geo['y'] = -1
287
+ if 'y' not in df_trades.columns:
288
+ df_trades['y'] = -1
289
+
290
+ df_lobbying['y'] = -1
291
+ df_camp_fin['y'] = -1
292
+ df_geo['y'] = -1
293
+ if 'y' not in df_trades.columns:
294
+ df_trades['y'] = -1
295
+
296
+ # ---------------------------------------------------------
297
+ # 3. OUT-OF-CORE ALIGNMENT & PARQUET WRITING
298
+ # ---------------------------------------------------------
299
+ import gc
300
+ import pyarrow as pa
301
+ import pyarrow.parquet as pq
302
+
303
+ output_dir = CONFIG["EDGE_OUT_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 = [
311
+ ("trades", df_trades),
312
+ ("lobbying", df_lobbying),
313
+ ("camp_fin", df_camp_fin),
314
+ ("geo", df_geo)
315
+ ]
316
+
317
+ # Destroy the loose global references immediately
318
+ del df_trades, df_lobbying, df_camp_fin, df_geo
319
+ gc.collect()
320
+
321
+ # Process 5 million rows at a time (~480 MB per chunk, extremely safe for RAM)
322
+ chunk_size = 5_000_000
323
+
324
+ for i in range(len(datasets)):
325
+ name, df_full = datasets[i]
326
+
327
+ out_path = os.path.join(output_dir, f"edges_{name}.parquet")
328
+ writer = None
329
+
330
+ # 1. Slice, format, pad, and append in chunks
331
+ for start in range(0, len(df_full), chunk_size):
332
+ end = min(start + chunk_size, len(df_full))
333
+ df_chunk = df_full.iloc[start:end].copy()
334
+
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
+
341
+ # Apply schema alignment locally to this small chunk
342
+ for col in all_msg_cols:
343
+ if col not in df_chunk.columns:
344
+ df_chunk[col] = np.float32(0.0)
345
+ else:
346
+ df_chunk[col] = df_chunk[col].astype('float32')
347
+
348
+ # Filter down to base + msg cols
349
+ df_chunk = df_chunk[base_cols + all_msg_cols]
350
+
351
+ # Append to Parquet file
352
+ table = pa.Table.from_pandas(df_chunk)
353
+ if writer is None:
354
+ # Initialize the writer with the schema of the first padded chunk
355
+ writer = pq.ParquetWriter(out_path, table.schema)
356
+ writer.write_table(table)
357
+
358
+ # Destroy the padded chunk to free RAM
359
+ del df_chunk
360
+ gc.collect()
361
+
362
+ if writer:
363
+ writer.close()
364
+
365
+ print(f" -> Saved {name} ({len(df_full)} rows) to {out_path}")
366
+
367
+ # 2. Destroy the reference to the full dataset before loading the next one
368
+ datasets[i] = None
369
+ del df_full
370
+ gc.collect()
371
+
372
+ print(" -> Master Edge Parquet chunks successfully written.")
373
+ print("==================================================\n")
374
+
375
+ return output_dir, all_msg_cols
376
+
377
+ # ==========================================
378
+ # PHASE 3: NODE FEATURE EXTRACTION
379
+ # ==========================================
380
+
381
+ SEC_FACTS = [
382
+ "NetIncomeLoss", "StockholdersEquity", "EarningsPerShareBasic",
383
+ "EarningsPerShareDiluted", "IncomeTaxExpenseBenefit",
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
660
+ # ==========================================
661
+
662
+ # ==========================================
663
+ # PHASE 4: ASSEMBLY & PYG VALIDATION (OUT-OF-CORE)
664
+ # ==========================================
665
+
666
+ # ==========================================
667
+ # PHASE 4: OUT-OF-CORE TEMPORAL SHARDING
668
+ # ==========================================
669
+
670
+ def generate_hillstreet_dataset(edge_dir="data/processed/master_edges_parquet", start_date="2012-07-01", include_structural_edges=True):
671
+ """
672
+ PHASE 4: Sharded conversion to PyTorch Geometric TemporalData.
673
+ Anchored to the true STOCK Act start date: July 2012.
674
+ """
675
+ print("==================================================")
676
+ print("PHASE 4: OUT-OF-CORE TEMPORAL SHARDING")
677
+ print("==================================================")
678
+
679
+ # 4.1 VALIDATE FILES
680
+ edge_files = [
681
+ "edges_trades.parquet",
682
+ "edges_lobbying.parquet",
683
+ "edges_camp_fin.parquet",
684
+ "edges_geo.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]) + "]"
712
+
713
+ # 4.2 BUILD GLOBAL NODE ID DICTIONARIES
714
+ print(f"Extracting global distinct Node IDs for events >= {start_date}...")
715
+ out_dir = "data/processed/pyg_graph"
716
+ os.makedirs(out_dir, exist_ok=True)
717
+
718
+ # Use .df() for DuckDB to avoid the AttributeError
719
+ df_src = duckdb.query(f"""
720
+ SELECT DISTINCT src FROM read_parquet({files_sql})
721
+ WHERE src IS NOT NULL AND time >= '{start_date}'
722
+ """).df()
723
+ unique_src = df_src['src'].values
724
+ src_map = {val: i for i, val in enumerate(unique_src)}
725
+
726
+ df_dst = duckdb.query(f"""
727
+ SELECT DISTINCT dst FROM read_parquet({files_sql})
728
+ WHERE dst IS NOT NULL AND time >= '{start_date}'
729
+ """).df()
730
+ unique_dst = df_dst['dst'].values
731
+ dst_start_idx = len(unique_src)
732
+ dst_map = {val: i + dst_start_idx for i, val in enumerate(unique_dst)}
733
+
734
+ # Save mapping for inference/analysis
735
+ np.save(os.path.join(out_dir, "src_id_map.npy"), src_map)
736
+ np.save(os.path.join(out_dir, "dst_id_map.npy"), dst_map)
737
+ print(f" -> Global mapping established: {len(src_map)} Politicians | {len(dst_map)} Companies")
738
+
739
+ del df_src, df_dst
740
+ gc.collect()
741
+
742
+ # 4.3 DETERMINE ACTIVE YEARS
743
+ print("Identifying active years...")
744
+ years_df = duckdb.query(f"""
745
+ SELECT DISTINCT extract(year from time) as yr
746
+ FROM read_parquet({files_sql})
747
+ WHERE time >= '{start_date}'
748
+ ORDER BY yr
749
+ """).df()
750
+ active_years = years_df['yr'].dropna().astype(int).tolist()
751
+
752
+ saved_shards = []
753
+
754
+ # 4.4 GENERATE YEARLY SHARDS
755
+ for year in active_years:
756
+ print(f"\n--- Processing Shard: {year} ---")
757
+
758
+ # Filter for the year, but respect the July 2012 start month for that specific year
759
+ query = f"""
760
+ SELECT * FROM read_parquet({files_sql})
761
+ WHERE extract(year from time) = {year}
762
+ AND time >= '{start_date}'
763
+ ORDER BY time ASC
764
+ """
765
+
766
+ master_table = duckdb.query(query).arrow()
767
+ if hasattr(master_table, 'read_all'):
768
+ master_table = master_table.read_all()
769
+
770
+ num_rows = master_table.num_rows
771
+ if num_rows == 0:
772
+ print(f" -> No valid events found for {year} after {start_date}. Skipping.")
773
+ continue
774
+
775
+ print(f" -> Mapping {num_rows:,} events...")
776
+ df_ids = master_table.select(['src', 'dst']).to_pandas()
777
+ src_idx_array = df_ids['src'].map(src_map).values
778
+ dst_idx_array = df_ids['dst'].map(dst_map).values
779
+ del df_ids
780
+
781
+ # Base Tensors (Using long/int64 for standard PyG compatibility)
782
+ src_tensor = torch.from_numpy(src_idx_array).to(torch.long)
783
+ dst_tensor = torch.from_numpy(dst_idx_array).to(torch.long)
784
+ y_tensor = torch.from_numpy(master_table['y'].to_numpy()).to(torch.long)
785
+ event_type_tensor = torch.from_numpy(master_table['event_type'].to_numpy()).to(torch.long)
786
+
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)
795
+ for i, col in enumerate(msg_cols):
796
+ arr = master_table[col].combine_chunks().to_numpy(zero_copy_only=False)
797
+ msg_tensor[:, i] = torch.from_numpy(arr)
798
+ del arr
799
+
800
+ # Assemble Object
801
+ data = TemporalData(
802
+ src=src_tensor,
803
+ dst=dst_tensor,
804
+ t=t_tensor,
805
+ msg=msg_tensor,
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()
812
+ assert is_sorted, f"[{year}] Temporal leak detected: Events are not strictly chronological!"
813
+
814
+ # Save Shard
815
+ shard_path = os.path.join(out_dir, f"hillstreet_temporal_graph_{year}.pt")
816
+ torch.save(data, shard_path)
817
+ saved_shards.append(shard_path)
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==================================================")
825
+ print(f"PHASE 4 COMPLETE: Generated {len(saved_shards)} annual shards.")
826
+ print("==================================================\n")
827
+
828
+ return saved_shards
829
+ # ==========================================
830
+ # MAIN ORCHESTRATION & CLI
831
+ # ==========================================
832
+
833
+ if __name__ == "__main__":
834
+ # 1. Setup Directories from CONFIG
835
+ EDGE_DIR = CONFIG["EDGE_OUT_DIR"]
836
+ os.makedirs(EDGE_DIR, exist_ok=True)
837
+
838
+ # Check which edges are required based on the toggle panel
839
+ REQUIRED_EDGES = []
840
+ if CONFIG["INCLUDE_EDGES"].get("trades", True): REQUIRED_EDGES.append("edges_trades.parquet")
841
+ if CONFIG["INCLUDE_EDGES"].get("lobbying", True): REQUIRED_EDGES.append("edges_lobbying.parquet")
842
+ if CONFIG["INCLUDE_EDGES"].get("camp_fin", True): REQUIRED_EDGES.append("edges_camp_fin.parquet")
843
+ if CONFIG["INCLUDE_EDGES"].get("geo", True): REQUIRED_EDGES.append("edges_geo.parquet")
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) and len(REQUIRED_EDGES) > 0
847
+
848
+ if phase2_done:
849
+ print(f" -> Found existing edge parquets in {EDGE_DIR}. Skipping Phases 1 & 2.")
850
+ schema = pq.read_schema(os.path.join(EDGE_DIR, REQUIRED_EDGES[0]))
851
+ base_cols = ['src', 'dst', 'time', 'y', 'event_type']
852
+ all_msg_cols = [c for c in schema.names if c not in base_cols]
853
+ else:
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. Process Node Features
858
+ pol_feat_path, comp_feat_path = process_node_features()
859
+
860
+ # 4. Generate Final PyG Dataset using the START_DATE from CONFIG
861
+ shards_generated = generate_hillstreet_dataset(
862
+ start_date=CONFIG["START_DATE"],
863
+ )
864
+
865
+ print(f"Successfully generated the following shards:\n{shards_generated}")