--- configs: - config_name: processed_events_campaign_finance data_files: - split: train path: data/processed/events_campaign_finance.csv - config_name: processed_events_geographical_industry data_files: - split: train path: data/processed/events_geographical_industry.csv - config_name: processed_events_lobbying data_files: - split: train path: data/processed/events_lobbying.csv - config_name: raw_527_committees data_files: - split: train path: data/raw/527_data_open_secrets/cmtes527.csv - config_name: raw_527_expenditures data_files: - split: train path: data/raw/527_data_open_secrets/expends527.csv - config_name: raw_527_receipts data_files: - split: train path: data/raw/527_data_open_secrets/rcpts527.csv - config_name: raw_voteview_members data_files: - split: train path: data/raw/HSall_members_VoteView.csv - config_name: raw_voteview_rollcalls data_files: - split: train path: data/raw/HSall_rollcalls.csv - config_name: raw_voteview_votes data_files: - split: train path: data/raw/HSall_votes.csv - config_name: raw_voteview_ideology data_files: - split: train path: data/raw/ideology_scores_quarterly_VoteView.csv - config_name: raw_cf_candidates data_files: - split: train path: data/raw/campaign_finance_open_secrets/cands*.csv - config_name: raw_cf_committees data_files: - split: train path: data/raw/campaign_finance_open_secrets/cmtes*.csv - config_name: raw_cf_expenditures data_files: - split: train path: data/raw/campaign_finance_open_secrets/expenditures*.csv - config_name: raw_cf_individuals data_files: - split: train path: data/raw/campaign_finance_open_secrets/indivs*.csv - config_name: raw_cf_pac_other data_files: - split: train path: data/raw/campaign_finance_open_secrets/pac_other*.csv - config_name: raw_cf_pacs data_files: - split: train path: data/raw/campaign_finance_open_secrets/pacs*.csv - config_name: raw_committee_assignments data_files: - split: train path: data/raw/committee_assignments.csv - config_name: raw_company_sic data_files: - split: train path: data/raw/company_sic_data.csv - config_name: raw_congress_terms data_files: - split: train path: data/raw/congress_terms_all_github.csv - config_name: raw_sec_financials data_files: - split: train path: data/raw/sec_quarterly_financials.csv - config_name: raw_district_industries_estimates data_files: - split: train path: data/raw/district_industries/*_CB_estimates.csv - config_name: raw_district_industries_surveys data_files: - split: train path: data/raw/district_industries/*_CB_survey.csv - config_name: raw_district_industries_dates data_files: - split: train path: data/raw/district_industries/survey_release_dates.csv - config_name: raw_naics_2012_crosswalk data_files: - split: train path: data/raw/industry_codes_NAICS/2012-NAICS-to-SIC-Crosswalk.csv - config_name: raw_naics_2013_mappings data_files: - split: train path: data/raw/industry_codes_NAICS/2013-CAT_to_SIC_to_NAICS_mappings.csv - config_name: raw_naics_2017_crosswalk data_files: - split: train path: data/raw/industry_codes_NAICS/2017-NAICS-to-SIC-Crosswalk.csv - config_name: raw_naics_2022_crosswalk data_files: - split: train path: data/raw/industry_codes_NAICS/2022-NAICS-to-SIC-Crosswalk.csv - config_name: raw_naics_effective_dates data_files: - split: train path: data/raw/industry_codes_NAICS/classification_effective_dates.csv - config_name: raw_lobbyview_bills data_files: - split: train path: data/raw/lobbying_data_lobbyview/bills.csv - config_name: raw_lobbyview_clients data_files: - split: train path: data/raw/lobbying_data_lobbyview/clients.csv - config_name: raw_lobbyview_issue_text data_files: - split: train path: data/raw/lobbying_data_lobbyview/issue_text.csv - config_name: raw_lobbyview_issues data_files: - split: train path: data/raw/lobbying_data_lobbyview/issues.csv - config_name: raw_lobbyview_network data_files: - split: train path: data/raw/lobbying_data_lobbyview/network.csv - config_name: raw_lobbyview_reports data_files: - split: train path: data/raw/lobbying_data_lobbyview/reports.csv license: cc-by-nc-sa-4.0 task_categories: - graph-ml - tabular-classification tags: - finance - politics - legal - gnn - temporal-graph pretty_name: "HillStreet: Relational Congressional Trading Dataset" size_categories: - 10M **Where the node bundle lives differs between the two.** The merged-edge pipeline writes its bundle *inside* `pyg_graph_merged/`, so that directory is self-contained. The multi-edge-type pipeline writes its bundle to `data/processed/node_features_static.pt`, one level up. The two never collide, but if you download only the multi-edge-type graph, remember its bundle does **not** sit in `pyg_graph/`. #### Multi-edge-type Lobbying, campaign-finance, and geographical-industrial relations are carried as **their own edges** alongside the trade edges, each declaring its kind through `event_type` (`0` trade, `1` lobbying, `2` campaign, `3` geo). All four streams share the one 24-column `msg` layout, zero-filled where a stream carries nothing. Message passing therefore sees each relation type as a distinct edge that a model can route, weight, or ablate separately. #### Merged-edge The alternative hypothesis: instead of a separate campaign-finance *edge* linking a legislator to a company, fold a **point-in-time summary of that prior relationship onto the trade edge** the same pair later transacts. If legislator *P* received industry money mapping to company *C*, and *P* later trades *C*, the trade edge's features should already "know" about that link. For every trade `(legislator, company, Filed)` the builder looks back over **all** prior structural events between that exact pair, strictly before the filing time, and appends 11 columns: | Block | Columns | |---|---| | Lobbying (3) | `m_lobby_count`, `m_lobby_recency`, `m_lobby_flag` | | Campaign finance (4) | `m_camp_logamt`, `m_camp_count`, `m_camp_recency`, `m_camp_flag` | | Geographical-industrial (4) | `m_geo_logwt`, `m_geo_count`, `m_geo_recency`, `m_geo_flag` | They are appended **after** the original 24, so code indexing the base layout positionally stays valid, and they are non-zero only on trade rows. The structural streams are still written to the merged shards, so the node universe and node features are identical to the multi-edge-type construction — a driver simply chooses not to route them into message passing. **Fan-out normalization.** Campaign-finance and geo events link a legislator to *every* ticker in an industry or sector, not to one company: a single industry-PAC donation fans out across every ticker in that SIC. Each broadcast edge is therefore down-weighted by its fan-out — the number of distinct tickers the originating event reached: ``` effective count = Σ over prior events of 1 / fanout_e effective amount = Σ over prior events of amount_e / fanout_e ``` A pair in a 2-ticker industry counts ~25× more than one in a 50-ticker industry. Recency and the `*_flag` indicator are **not** normalized. Fan-out is computed exactly for campaign and geo (each pre-broadcast event is tagged and its expansion counted). For lobbying it is a documented **proxy**: `events_lobbying.csv` is already exploded to ticker level and the originating client/bill identity is gone, so fan-out is taken as the number of distinct tickers linked to that legislator on that filing date. **Leakage boundary.** The lookback is a `merge_asof(direction="backward", allow_exact_matches=False)`, so each trade sees only structural events **strictly before its own filing time** — the same standard applied to the trade's market features. Because the merge is anchored to the trade's own timestamp rather than to a moving backtest cutoff, it is fold-independent and is baked into the shards once. #### Which one should I use? They answer different questions, and both are shipped so the comparison can be run head-to-head. Use **multi-edge-type** when you want the model to learn how to route each relation type. Use **merged-edge** when you want the relational history available directly to the trade-edge decoder without message passing having to carry it. `ml_dataset_continuous_merged.csv` is the flat-feature analogue of the merged-edge graph — the same 11 columns as tabular features — so gradient-boosted baselines can be compared against the GNNs on byte-identical inputs. --- ### The Label `y` is **direction-adjusted**, **peak-based**, and thresholded at the **top quartile within each direction**. For each trade, the signal is the **direction-adjusted peak six-month excess return** over SPY — the most favorable excursion the excess-return path reaches at any point in the horizon, measured in the direction the legislator actually bet: ``` buy : signal = Max_Excess_Return_6M (best favorable long excursion) sell : signal = -Min_Excess_Return_6M (inverted: the adverse excursion of the excess path) y = 1 iff signal >= q_0.75 over all trades of that same direction ``` **Inverted sell scoring** is the key asymmetry. A *sale* is a correct call when the stock **lagged** SPY at some point in the window, so the sell side is scored on the **negated minimum** of the excess path, not its maximum. Scoring both directions on `Max` would reward a legislator for selling a stock that then outperformed. Three further properties are worth stating explicitly: - **It is a path maximum, not an endpoint return.** The question is whether the trade *reached* the threshold at any point in the six months, not where it closed. - **It is excess over SPY**, not raw return. - **It is anchored on the filing date, not the trade date.** This is the copy-trading frame: the earliest moment the public could have acted on the disclosure. Two thresholds are estimated once over the whole dataset — one per direction — giving roughly 25% positives on each side. This is deliberately **not** fold-local: the threshold is global by design, so the label can be baked at build time and every downstream consumer simply reads `y`. Trades whose horizon has not resolved yield a NaN signal, fail the `>=` test, and land at `y = 0` rather than corrupting the threshold. Structural edges carry `y = -1` and must be excluded from supervision. The definition lives in `src/data_prep/labeling.py` and is imported by both label bakes, so the graph and tabular targets are byte-identical. ### Evaluation Protocol Results on this dataset use a **gap-aware walk-forward split**, anchored on `Filed + horizon_days`: - **Train** — `Filed < test_start` **and** `Filed + horizon < test_start` (fully resolved outcomes only) - **Gap** — `Filed < test_start` **and** `Filed + horizon >= test_start` (excluded from supervision; the outcome is not yet known at test time) - **Test** — `Filed ∈ [test_start, test_start + 1 month)`, walked forward month by month The primary metric is **pooled AUROC**: pool every per-trade prediction across the full test year, then compute a single AUROC. The average of monthly AUROCs is a diagnostic, not the headline number. The secondary metric is **precision among the top 10%** of highest-confidence predictions per month — the actionable copy-trading measure. --- ### Reproduction Pipeline All commands are run from the repository root, with `data/processed/ml_dataset_continuous.csv` and `data/parquet/` in place (see [Prerequisite](#prerequisite-data-you-must-acquire-separately)). Use the `python -m` form throughout: it puts the repository root on `sys.path`, and `build_clean_dataset.py` uses package-relative imports that require it. **Requirements:** Python 3.12, `torch==2.9.1`, `torch-geometric==2.7.0`, plus `pandas`, `numpy`, `pyarrow`, `duckdb`, `scikit-learn`, `scipy`, `tqdm`. The CPU build of PyTorch is sufficient — a GPU only speeds up model training, not dataset construction. Install PyTorch and PyG *before* the rest. ```bash # 0. (Only if regenerating the trade table from raw filings) python -m src.data_prep.build_clean_dataset # -> data/processed/ml_dataset_continuous.csv # 1. Build the three processed structural-event tables (any order) python -m src.data_prep.build_lobbying_events python -m src.data_prep.build_campaign_events python -m src.data_prep.build_geographical_edges # 2. Build edge parquets, annual PyG shards, node-id maps, and aligned node features. # Run either or both constructions; each writes to its own directories. # (Phase 3 node features run automatically at the end of each.) python -m src.build_graph_multi_edge_type # -> pyg_graph/ + master_edges_parquet/ python -m src.build_graph_merged_edges # -> pyg_graph_merged/ + master_edges_parquet_merged/ # 3. (Optional) the flat-CSV analogue, for tabular and blending baselines python -m src.build_tabular_merged_dataset # -> ml_dataset_continuous_merged.csv ``` The orchestrators do **not** call the three structural builders themselves — they read their CSV outputs — but each **does** invoke `node_features.py` (which imports `feature_lookups.py`) as its final phase, so both must be present. The 17 market features are handled automatically: the orchestrators call `ensure_price_features()`, which appends them to the trade CSV only if they are absent. There is no separate manual step. Pass `--refresh_price_features` to recompute them (e.g. after rebuilding the price parquets) or `--skip_price_features` to leave the CSV untouched and fail if the columns are missing. Other useful flags: `--start_date YYYY-MM-DD` bounds the graph timeline (the STOCK Act era begins July 2012); `--skip_node_features` emits edges and shards only; `--snapshot_date` pins the as-of date for time-varying node features; `--force` (merged builder) rebuilds the edge parquets rather than reusing them. `build_tabular_merged_dataset.py` does not read the structural CSVs itself — it reuses the merged trade parquet, so run `build_graph_merged_edges.py` first or pass `--build_merged` to have it build that parquet in-process. ### Loading the Tensors ```python import torch, numpy as np shard = torch.load("data/processed/pyg_graph_merged/hillstreet_temporal_graph_2023.pt", weights_only=False) print(shard.src.shape, shard.msg.shape) # [E], [E, 35] # Supervised trade edges only trades = shard.event_type == 0 X, y = shard.msg[trades], shard.y[trades] # Node indices back to entity ids src_map = np.load("data/processed/pyg_graph_merged/src_id_map.npy", allow_pickle=True).item() bioguide_of = {v: k for k, v in src_map.items()} # Static node features bundle = torch.load("data/processed/pyg_graph_merged/node_features_static.pt", weights_only=False) x_pol, x_comp = bundle["x_pol"], bundle["x_comp"] print(bundle["meta"]["n_pol"], bundle["meta"]["n_comp"], bundle["meta"]["snapshot_date"]) ``` `node_features.load_combined_graph()` does the same work at a higher level: it recombines the annual shards into one static graph, converts the unified node ids to the bipartite-local convention the models expect, and attaches the node bundle. ### Feature Engineering & Normalization To stabilize variance in graph training, continuous features are transformed using signed log-scaling: $$x' = \text{sign}(x) \times \log(1 + |x|)$$ Counts and amounts follow the same treatment: edge weights use `log1p(total_count)` normalized by the maximum, trade size is an ordinal bracket, and filing gap is `log1p(days)` winsorized at 120 days. ### Caveats - **Volatility features are strong, and are not leakage.** `vol_120d` measured at the filing date is the single most predictive feature for flat-feature baselines. High-volatility stocks mechanically reach a top-quartile *peak* more often — a real, known-at-filing-time relationship rather than lookahead — but any analysis should account for it. - **Broadcast relations are diffuse.** Campaign-finance and geo events are industry-level, so they connect a legislator to every ticker in an industry. The merged-edge construction down-weights by fan-out; the multi-edge-type construction does not, leaving that to the model. - **Lobbying fan-out is a proxy.** See [Merged-edge](#merged-edge). - **Structural edges are collapsed.** Repeated events for the same `(legislator, company, event_type)` are merged into one weighted edge, with `t` the earliest event and `last_seen` the most recent. Trades are never collapsed — each is a distinct supervised event. - **Tickers without price history are dropped** from the dataset entirely. - **The graph is bipartite.** There are no legislator↔legislator or company↔company edges. ### Intended Use - **Trade Signal Validation:** Determining if a trade constitutes a meaningful price signal based on political context. - **Graph Representation Learning:** A benchmark for GNNs and TGNs. > [!WARNING] > **Non-Intended Use:** This dataset is for research purposes only. It is not designed for legal determinations of insider trading nor for real-time automated trading.