dissertation-dataset / data_collection_readme.md
SarthakVishnu's picture
Upload data_collection_readme.md with huggingface_hub
1eb5536 verified
|
Raw
History Blame
34.2 kB

Data Collection README

Project: Hybrid Topic and Domain-Adaptive Modelling for Financial Risk and Forecasting Student: S2880814 | Supervisor: Prof Tiejun Ma Phase covered: Phase 1 — Data Pipeline (IPP §3.1.1, Milestone M1)


What Phase 1 Required (from the IPP Report)

Section 3.1.1 of the report specifies four things that must exist before Phase 2 (DAPT) can begin:

Report Requirement Where stated
Item 1A text corpus, sentence-tokenised, temporal split 2006–2024 / 2025 / 2026 §3.1.1, Figure 1 (Ph.1 DATA PIPELINE box)
CIK–PERMNO linkage for volatility label assignment §3.1.1 bullet 1
CIK–SIC 2-digit linkage for sector-view positive-pair construction (Phase 3) §3.1.1 bullet 2
30-day realised volatility labels (lagged + forward) aligned to filing dates §3.1.1, §3.1.5, Milestone M1

The output of Phase 1 is Milestone M1: "Clean corpus, temporal split indices, volatility labels".


Dataset Inventory

Raw / Source Data (inputs — not generated by scripts)

File Size Source Report Role
sp500_1A/ (folder, 8,247 .pickle files) ~1 GB Shared by Sunnie Li (enquire actual source) Primary text corpus — Item 1A Risk Factor sections from S&P 500 10-K filings, 2006–2025. Used as the sole text input for all five phases (§3.1.1: "Item 1A is selected as the sole text source"). Each file is named {TICKER}_{YEAR}.pickle and contains a plain string.
sp500_union_constituents(1).csv ~50 KB Shared by Sunnie Li (enquire actual source) Universe definition — 656 unique CIK/ticker pairs representing all firms that were ever S&P 500 constituents. Used as the spine for all linkage and data-collection scripts.
ticker_cik_mapping(1).csv ~30 KB Shared by Sunnie Li (enquire actual source) Auxiliary cross-reference; superseded by sp500_union_constituents for pipeline use.
ccm_linking_table.csv ~2.1 MB WRDS CRSP/Compustat Merged (CCM) — downloaded via WRDS web query Raw CCM linking table: maps CIK → GVKEY → PERMNO/PERMCO with link type and date range. Input to build_permno_linkage.py.
all_sp500_prices_2000_2024_delisted_include.csv ~253 MB FINSABER dataset (waylonli/FINSABER-reproduce on HuggingFace) Daily stock prices 2000–2024 for all S&P 500 firms including delisted. Columns: date, open, high, low, close, adjusted_close, volume, symbol. Used to compute volatility labels for all filings up to and including fiscal year 2024. Replaces WRDS CRSP for the training period, keeping the pipeline free of institutional data for 2006–2024.
crsp_2025_daily.csv ~9.5 MB WRDS CRSP Annual Update → Stock Version 2 (CIZ) → Daily Stock File — query crsp_2025_daily (ID 11299163) Daily stock prices for 2025 (Jan–Dec). 159,093 rows across 647 PERMNOs. Columns: PERMNO, HdrCUSIP, Ticker, PERMCO, DlyCalDt, DlyPrc, DlyRet, ShrOut. Required for volatility labels on 2025 filings (validation set per §3.1.1 temporal split). CRSP data is accessed under the University's institutional licence and will not be redistributed (§3.4 Ethics).
crsp_dsenames.csv ~290 KB WRDS CRSP Annual Update → Legacy Data - Stock / Events → Names — query ID 11340756 CRSP Security Names history table (dsenames). 4,431 rows across 647 PERMNOs — one row per name period per security. Columns: namedt (as DATE), comnam, ticker, permno, nameendt, shrcd, exchcd, siccd, permco. namedt/nameendt define the date range for which each company name and ticker was valid. Current use: provided to PhD verifier (Sean Choi) for PERMNO linkage verification — namedt/nameendt confirm each security was active and correctly identified during the study period. Future use (planned): essential for GDELT news matching — GDELT references companies by their news-mentioned name at the time of publication; comnam+namedt/nameendt enable temporal name→PERMNO resolution (e.g. "Allied Signal" articles in 1997 correctly map to the same PERMNO as "Honeywell" articles in 2005). Also useful for: historical ticker→PERMNO joins when collecting Form 4 insider data; exchcd (NYSE/NASDAQ/AMEX) as a control variable in Phase 5 regression. CRSP data accessed under University's institutional licence (§3.4 Ethics).

Intermediate / Derived Data (generated by scripts)

File Rows Script What it contains Report Requirement met
permnos_for_wrds.txt 647 lines (helper, no script) One PERMNO per line — used to upload the PERMNO list to the WRDS query form to pull crsp_2025_daily.csv.
permno_linkage.csv 656 scripts/build_permno_linkage.py Clean CIK → PERMNO mapping. Columns: ticker, cik, permno, permco, sic_ccm, gvkey, linktype, linkprim, linkdt, linkenddt. Deduplicates CCM to best link per CIK (LINKPRIM=P preferred, then active, then latest). 651/656 matched (99.2%); 5 unmatched (ETN, ACV, PARA, DAY, CPWR). CIK–PERMNO linkage (§3.1.1 bullet 1) — required for assigning volatility labels to filings.
filings_index.csv 11,447 scripts/build_filings_index.py EDGAR submissions API output for all 656 CIKs. Columns: ticker, cik, sic, sic_description, fiscal_year, filing_date, report_date, has_pickle. Covers 10-K and 10-K405 filings from fiscal years 2006–2025. has_pickle=True for 8,105 rows — these are the filings with text in sp500_1A/. CIK–SIC 2-digit linkage (§3.1.1 bullet 2) — SIC codes needed for inter-firm sector-view positive pairs in Phase 3 contrastive fine-tuning. Also provides the fiscal-year index aligning filing dates to return windows (§3.1.1 bullet 3).
volatility_labels.csv 8,105 scripts/compute_volatility_labels.py 30-day annualised volatility windows for every filing with a pickle file. Columns: ticker, cik, sic, sic_description, fiscal_year, filing_date, report_date, lagged_vol_30d, fwd_vol_30d. Price sources: FINSABER (2000–2024) → CRSP 2025 → yfinance fallback (ETN). Coverage: 7,695/8,105 filings have both windows (94.9%). 30-day realised volatility labels (§3.1.1, §3.1.5) — fwd_vol_30d is the prediction target throughout Phases 2–5. lagged_vol_30d is the AR(1) baseline feature. Annualised as std(log-returns) × √252.

Additional Datasets (collected post-Phase 1, per supervisor request)


👤 form4_transactions.csv — SEC Form 4 Insider Trading

What it is: Non-derivative insider transactions (open-market stock buys/sells by directors, officers, and >10% shareholders) for all 656 S&P 500 CIKs, covering 2006 Q1 – 2026 Q1.

Metric Value
Rows 1,670,042
Unique companies 645
Date range 2006-03-01 → 2025-12-30
File size 215 MB
Officer transactions 428,543
Director transactions 282,857

Columns: ticker, issuer_cik, accession_number, owner_name, rptownercik, is_officer, is_director, is_ten_pct_owner, officer_title, transaction_date, transaction_code, acquired_disposed, shares, price_per_share, shares_after_txn, value_after_txn, security_title, ownership_type, form_type

Transaction codes: S = open-market sale · P = open-market purchase · A = award/grant · F = tax withholding by shares · M = option exercise

Purpose: TBD by Prof Tiejun Ma — likely as an insider sentiment signal alongside 10-K text embeddings in Phase 5 volatility forecasting.


Step-by-Step: Collection and Pre-Processing

Step 1 — Source selection: SEC flat files over XML scraping (run scripts/collect_form4.py → generates datasets/form4_transactions.csv, 1,670,042 rows, 32 columns, ~11 min)

Why SEC flat files? The SEC publishes pre-parsed quarterly ZIP archives of all Form 3/4/5 XML submissions as flat TSV files at: https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{n}_form345.zip

Browse all available quarters and download manually: https://www.sec.gov/data-research/sec-markets-data/insider-transactions-data-sets

The alternative — scraping 357,000+ individual Form 4 XML files via the EDGAR submissions API — was first attempted but abandoned for three reasons: (1) runtime of ~11 hours at EDGAR's 10 req/sec rate limit; (2) primaryDocument in the submissions API pointed to XSL-rendered HTML files (path prefix xslF345X05/) rather than raw XML, requiring expensive directory-listing fallbacks per filing; (3) the SEC flat files contain the same data, already parsed, with no rate-limit concerns. The flat-file approach completed in ~11 minutes.

What the script does:

  • Downloads all 81 quarterly ZIPs (2006 Q1 → 2026 Q1) into memory — no local ZIP storage needed
  • From each ZIP reads three TSV tables: SUBMISSION (issuer CIK, filing date), REPORTINGOWNER (insider identity), NONDERIV_TRANS (transaction details)
  • Filters SUBMISSION to rows where issuer_cik is in the 652-CIK universe from sp500_union_constituents(1).csv
  • Joins the three tables on accession_number, adds ticker via CIK→ticker mapping
  • Why NONDERIV_TRANS only? Non-derivative transactions represent actual stock ownership changes (buying/selling shares). Derivative transactions (options, warrants) reflect contingent claims and require a separate valuation model — excluded for now per supervisor's TBD scope
  • Output: raw form4_transactions.csv (1,670,042 rows, 32 columns including 12 footnote columns)

Step 2 — Post-processing: clean columns and fix dates (run scripts/postprocess_form4.py → overwrites datasets/form4_transactions.csv, 20 columns, ~12 min)

Why drop _fn columns? The SEC flat files include 12 columns with the suffix _fn (e.g., trans_shares_fn, trans_pricepershare_fn). These are footnote reference IDs — integers pointing to footnote entries in the original XML filing. They carry no analytical value for this project and bloat the file. All 12 were dropped, reducing columns from 32 to 20.

Why fix the date format? Raw dates from the SEC flat files are in DD-MON-YYYY format (e.g., 30-MAR-2006). All other dates in the pipeline (volatility_labels.csv, feature_table.parquet, filings_index.csv) use ISO YYYY-MM-DD. Standardising prevents silent join failures in downstream code.

Why errors='coerce' in date conversion? A handful of rows in the raw EDGAR data contain corrupted dates (e.g., 08-MAY-0013 — year 0013, likely a filer keying error for 2013). Pandas raises OutOfBoundsDatetime on these. Using errors='coerce' converts invalid dates to NaT rather than crashing — the ~10 affected rows out of 1.67M are acceptable data-quality noise.

Output: cleaned form4_transactions.csv (same 1,670,042 rows, 20 columns, 215 MB, dates now in YYYY-MM-DD).


Step 3 — Role enrichment: add officer/director flags (run scripts/form4_add_roles.py → overwrites datasets/form4_transactions.csv, 24 columns, ~12 min)

Why add is_officer, is_director, officer_title? Not all insider trades carry equal information. Research (Seyhun 1986; Lakonishok & Lee 2001) shows that trades by corporate officers (CEO, CFO) and directors are significantly more informative about future returns than trades by large shareholders. These flags allow downstream analysis to filter to high-signal trades (e.g., is_officer=1 AND transaction_code='P' = CEO buying open-market — a strong bullish signal).

Why was a separate script needed? The initial collection merged the REPORTINGOWNER table but the role columns (is_officer, is_director, is_ten_pct_owner, officer_title) were absent from the output. Investigation revealed that the SEC changed the REPORTINGOWNER schema in their newer flat files: instead of separate boolean columns (ISOFFICER, ISDIRECTOR), roles are now encoded as a comma-separated string in a single column rptowner_relationship (e.g., "Director,Officer,TenPercentOwner"). The form4_add_roles.py script re-downloads all 81 quarters, extracts only the REPORTINGOWNER table (small — ~1 MB per quarter), parses rptowner_relationship using string containment to derive the three boolean flags, and merges them onto the existing clean CSV.

Why re-download rather than re-run everything? The 1.67M transaction rows were already correctly collected and cleaned. Re-running collect_form4.py from scratch would repeat 11 minutes of work unnecessarily. The targeted role-enrichment script only re-reads the small REPORTINGOWNER table (~10% of each ZIP's size), completing in ~12 minutes.

Output: final form4_transactions.csv (1,670,042 rows, 24 columns, with is_officer, is_director, is_ten_pct_owner, officer_title added).



🏷️ crsp_dsenames.csv — CRSP Security Names History

Metric Value
Rows 4,431
Source WRDS CRSP Annual Update → Legacy Data - Stock / Events → Names (query ID 11340756)
File size ~290 KB

What it is: One row per name period per PERMNO — the full history of each firm's trading name, ticker, and exchange listing. Columns: namedt, comnam, ticker, permno, nameendt, shrcd, exchcd, siccd, permco.

Why namedt/nameendt? These date-bound name periods are what distinguish crsp_dsenames from the header-level crsp_2025_daily.csv. A given PERMNO (e.g., 10145) may have been "Allied Chemical Corp" in 1970, "Allied Signal Inc" in 1985, and "Honeywell International Inc" in 2000. Any downstream process that matches by company name (e.g., GDELT news matching) must use the name that was active at the time of the relevant event — namedt/nameendt provide that temporal boundary.

Why collected separately from permno_linkage.csv? The CCM linking table (ccm_linking_table.csv) tracks when a CIK↔PERMNO link was valid (linkdt/linkenddt). This is a different question from when a security's name was active (namedt/nameendt). These are two different CRSP tables (crsp.ccmxpf_linktable vs crsp.dsenames) answering different questions.

Current use: Provided to PhD verifier Sean Choi (2026-05-28) for PERMNO linkage verification — namedt/nameendt confirm each security was active under a valid name during the study period.

Future use (planned):

  • GDELT news matching — temporal comnam lookup to resolve news mentions to PERMNOs
  • exchcd (1=NYSE, 3=NASDAQ, 2=AMEX) as a control variable in Phase 5 regression
  • Historical ticker validation when joining Form 4 data for companies that changed tickers

CRSP data accessed under University of Edinburgh's institutional licence (§3.4 Ethics) — not for redistribution.


Phase 1 Final Output

File Rows Script Description
feature_table.parquet 8,105 scripts/build_feature_table.py Milestone M1 deliverable. Joins filings index + PERMNO linkage + volatility labels into a single row-per-filing table. Columns: ticker, cik, permno, permco, gvkey, sic, sic_description, fiscal_year, filing_date, report_date, lagged_vol_30d, fwd_vol_30d, embedding (NaN placeholder), topic_vector (NaN placeholder), linktype, linkprim. The embedding and topic_vector columns are filled in Phase 2 and Phase 4 respectively.
feature_table_preview.csv 8,105 scripts/build_feature_table.py Human-readable CSV version of the feature table (without placeholder columns). For inspection only.

Coverage Summary

Metric Value
Firms in S&P 500 universe 656
Firms with at least one Item 1A filing 485
Total filings with Item 1A text (has_pickle) 8,105
Filings with PERMNO assigned 8,079 (99.7%)
Filings with both vol labels 7,695 (94.9%)
Date range (filing dates) 2006-02-22 → 2026-03-02
Unique SIC codes 179
Temporal split Train ≤ 2024 · Val 2025 · Test 2026

Temporal Split (§3.1.1)

The report mandates a strictly forward-looking split to prevent leakage from base-model pre-training data:

Split Filing fiscal years Filings (approx.) Used in
Train 2006 – 2024 ~7,600 Phase 2 DAPT MLM, Phase 3 contrastive FT, Phase 4 BERTopic
Val 2025 ~380 Phase 2 perplexity checkpoint selection; Phase 3 FinMTEB intrinsic eval
Test 2026 (YTD) ~125 Phase 5 downstream volatility forecasting (held-out, never seen during training)

The split boundary is applied via filing_date (not report_date) per §3.1.1: "filing_date defines the temporal boundary".




📄 sec/ — Full 10-K and 10-Q SEC Filings

What it is: Complete SEC 10-K (annual) and 10-Q (quarterly) filings in plain text for 634 S&P 500 companies, downloaded from the Finstream lab server (labvm). Each filing is the full document — all sections including Item 1 Business, Item 1A Risk Factors, Item 7 MD&A, financials, and exhibits.

Metric Value
CIK folders 634
Total filing files 2,285 (classified) + 45 UNCERTAIN (exhibits, safely ignored)
10-K filings 817
10-Q filings 1,468
Total size ~9 GB
Date range 2025–2026 (latest filings)

Local directory structure (datasets/sec/):

datasets/
└── sec/
    ├── sec_filings_index.csv        ← master index (paths relative to datasets/)
    ├── sec_filings_UNCERTAIN.csv    ← 45 exhibit/non-filing files flagged for review
    └── firm/
        ├── txt/<CIK>/<YYYY-MM-DD>.txt    ← plain text (primary)
        ├── html/<CIK>/<YYYY-MM-DD>.html  ← HTML version
        └── pdf/<CIK>/<YYYY-MM-DD>.pdf    ← PDF version

Server path: /data/finstream/airflow/data/SP500/sec/ on labvm

Why this complements sp500_1A/: The existing sp500_1A/ corpus contains only the extracted Item 1A Risk Factors section from 10-Ks (2006–2025). This dataset provides the full filing text for all sections, and includes 10-Q quarterly reports which are absent from sp500_1A/.


Step-by-Step: Collection and Sorting

Step 1 — Download from Finstream server (SSH to labvm, rsync to local — no script required)

Files are stored on the University of Edinburgh Finstream lab server at /data/finstream/airflow/data/SP500/sec/. Downloaded into datasets/sec/ via:

rsync -avz --progress labvm:/data/finstream/airflow/data/SP500/sec/ \
  "D:/UoE AI/Dissertation/IPP Draft/datasets/sec/"

Files are named by date only (YYYY-MM-DD.txt) with no form-type label in the filename.

Step 2 — Sort into 10-K vs 10-Q (run scripts/sort_sec_filings.py → generates datasets/sec_filings_index.csv + datasets/sec_filings_UNCERTAIN.csv, ~6 sec)

Why not use filename or file size? Filenames contain only the filing date. File size correlates loosely with form type but is unreliable — 10-Q files range from 80 KB to 900 KB depending on company complexity, overlapping with 10-K sizes entirely.

How classification works (sure-shot method): Every SEC XBRL txt file embeds the fiscal period token in its first line of metadata:

abt-20241231  0000001800  2024  FY  false  ...

The token FY → 10-K (annual); Q1/Q2/Q3/Q4 → 10-Q (quarterly). The script scans all whitespace-separated tokens in the first line (position-independent, since the token appears at different offsets across XBRL format variants). Only 1 line per file is read — the full 9 GB is never loaded.

Why sec_filings_UNCERTAIN.csv is safe to ignore: Of 45 unclassified files, 43 are exhibit documents (insider trading policies, RSU agreements, consent letters, XBRL viewer fragments) that are not 10-K or 10-Q filings. The remaining 2 (CIK 0001881551) are genuine 10-Ks in a non-XBRL plain text format — manually patched into the index via scripts/patch_sec_index.py.

Step 3 — Patch 2 manually identified 10-Ks (run scripts/patch_sec_index.py → overwrites datasets/sec_filings_index.csv, adds 2 rows)

Appends the 2 plain-text 10-K filings from CIK 0001881551 (Apr 2025 and Apr 2026) that the XBRL parser could not classify, marked with confidence = MANUAL.

Output: sec/sec_filings_index.csv — master reference for all 2,285 filings (2,283 HIGH confidence + 2 MANUAL).



🗂️ sec/sec_filings_index.csv — SEC Filings Master Index

Metric Value
Rows 2,285
10-K 817
10-Q 1,468
Confidence HIGH 2,283
Confidence MANUAL 2 (CIK 0001881551)

Columns: cik, filing_date, form_type, fiscal_period, size_kb, confidence, txt_path, html_path, pdf_path

Purpose: Lookup table mapping every filing file to its form type and paths. Any downstream script reads this CSV rather than scanning the 9 GB directory. confidence is HIGH for XBRL-classified files and MANUAL for the 2 hand-labelled entries.

Path convention: All paths (txt_path, html_path, pdf_path) are relative to the datasets/ directory (one level above sec/). This makes the index portable across machines (local Windows, GPU cluster, HuggingFace download). To resolve a path in Python:

from pathlib import Path
import pandas as pd

# Note: index lives inside datasets/sec/ but paths are relative to datasets/
datasets_dir = Path("datasets")
df = pd.read_csv(datasets_dir / "sec" / "sec_filings_index.csv")
full_path = datasets_dir / df.iloc[0]['txt_path']
# → datasets/sec/firm/txt/0000001800/2025-02-21.txt


🎙️ calls/ — S&P 500 Earnings Call Transcripts

What it is: Quarterly earnings call transcripts for S&P 500 firms. Two separate datasets exist — one on the Finstream server (historic, not yet downloaded) and one downloaded locally (recent, 2025–2026).


Local dataset — datasets/calls/ (already on disk)

Metric Value
Total transcripts 299
Total tickers 172
Date range 2025–2026
Format JSON, one file per ticker/year/quarter

Directory structure:

datasets/calls/firm/json/<ticker>/<year>/calls_<TICKER>_<YEAR>_<Q>.json

JSON structure (example — AAPL Q1 2025):

{
  "date": "2025-01-30",
  "transcript": "Suhasini Chandramouli: Good afternoon...",
  "transcript_split": "split transcript is available for premium subscribers only."
}

Note on transcript_split: Full Q&A/executive section breakdown requires a premium API Ninjas subscription. Only the combined transcript field is available — this is sufficient for DAPT corpus expansion and sentiment scoring.

Source: API Ninjas (https://api-ninjas.com/). No redistribution restrictions.


Finstream server dataset — NOT YET DOWNLOADED (pending)

The Finstream lab server holds a much larger historic corpus:

Metric Value
Total transcripts 37,962
Total firms 653
Coverage (recall) 96.25%
Date range Jan 2008 – Dec 2024
Missing 6,373 transcripts (concentrated in 2008–2012 and Q1 filings)

Server path: /data/finstream/airflow/data/SP500/calls/firm/<ticker>/<year>/

Download command (when ready):

rsync -avz --progress labvm:/data/finstream/airflow/data/SP500/calls/ \
  "D:/UoE AI/Dissertation/IPP Draft/datasets/calls_historic/"

This dataset would provide the historical coverage (2008–2024) needed if earnings calls are to be included in the DAPT corpus (see Literature (new)/Literature (new).md Section 5 for the scientific rationale). For 2025–2026 pipeline work, the local 299-file dataset is sufficient.

Why two datasets: The local 299-file dataset covers the 2025–2026 test/val period used in the SEC filings pipeline. The Finstream corpus covers the 2008–2024 training period. If both are downloaded and merged, they provide full temporal coverage aligned to the feature_table.parquet training split.

Purpose: Per literature survey (Literature (new).md, Section 5): earnings calls are the only new dataset with a scientific case for NLP training integration (DAPT corpus expansion + 4th contrastive view). Stage 5 use: call tone features (net_optimism, Q&A tone) as scalar predictors alongside embeddings.




📰 gdelt/ — GDELT Global Knowledge Graph News Sentiment

What it is: Daily news sentiment signals for S&P 500 companies, extracted from the GDELT 1.0 Global Knowledge Graph (GKG). GDELT monitors 215 languages of global news media and scores each article for tone (positive/negative sentiment), organisations mentioned, and economic/financial themes. Used as a company-specific news sentiment feature alongside SEC filings and earnings calls.

Why GDELT and not RavenPack: RavenPack is the standard financial-research news sentiment dataset available via WRDS, but the University of Edinburgh's WRDS subscription does not include it. GDELT is the closest freely available alternative and is used extensively in financial research.

Metric Value
Daily rows (final output) 170,153
Unique PERMNOs covered 543 / 646 (84%)
Date range 2025-01-01 → 2026-06-10
Raw daily parquet files 508
Source http://data.gdeltproject.org/gkg/YYYYMMDD.gkg.csv.zip
Cost Free — no account required

PERMNO coverage note: 543 of 646 PERMNOs (84%) are matched. The 103 unmatched PERMNOs are companies with short, ambiguous, or rarely news-mentioned names that do not reliably appear in GDELT's ORGANIZATIONS field. Coverage is sufficient for pilot analysis; the supervisor will decide whether to pursue BigQuery (GDELT 2.0 GKG) for richer coverage and historical extension to 2006–2024.

Key output columns:

gdelt_gkg_daily.parquet — richest output, one row per (PERMNO, date):

Column Meaning
permno CRSP PERMNO — links to volatility labels and prices
article_date Date of news article (YYYY-MM-DD)
n_articles Articles mentioning this company that day
n_sources Distinct news outlets
avg_tone Mean overall tone (negative = bad news, positive = good news)
avg_tone_pos Mean positive sentiment density
avg_tone_neg Mean negative sentiment density
avg_polarity Mean polarity score
n_econ_themes Articles with at least one ECON_ theme code
n_fin_themes Articles with finance-specific themes

gdelt_daily.parquet — combined output (future use, currently ignorable):

Column Meaning
permno CRSP PERMNO
date Date (YYYY-MM-DD)
n_records Articles mentioning this company that day
n_sources Distinct news outlets
avg_tone Mean overall tone
avg_tone_pos Mean positive sentiment score
avg_tone_neg Mean negative sentiment score
source Data source (GKG or EVENTS)

Which file to use: Use gdelt_gkg_daily.parquet for all pipeline work — it has more columns and no information has been dropped. gdelt_daily.parquet strips out avg_polarity, n_econ_themes, and n_fin_themes to prepare a common schema for a future merge with GDELT 1.0 Events data (2006–2014). Until that historical data is collected, gdelt_daily.parquet is a strict subset of gdelt_gkg_daily.parquet and can be ignored.

How company matching works: crsp_dsenames.csv provides the bridge between CRSP PERMNOs and GDELT organisation names. Each CRSP company name (comnam) is cleaned to GDELT-style — suffixes stripped (INC, CORP, &) and 30+ manual overrides applied (e.g. AMAZON COM INCAMAZON, JOHNSON & JOHNSONJOHNSON JOHNSON). Matching uses temporal bounds (namedt/nameendt) so a 2025 article mentioning ORACLE is only assigned to PERMNO 10104 if that name was active on the article date. This produces 800 unique patterns across 646 PERMNOs stored in datasets/gdelt/company_names.csv.

Why GDELT 1.0 GKG for direct download: GDELT 1.0 GKG publishes one file per day (527 files for 2025–2026). GDELT 2.0 GKG publishes one file every 15 minutes (~50,592 files for the same period) — impractical to direct-download. GDELT 2.0 GKG is accessible via Google BigQuery (pending supervisor decision on historical extension). See datasets/gdelt_readme.md for full detail on both approaches.


Step-by-Step: Collection

Step 1 — Prepare company name patterns (run scripts/gdelt/step1_prepare_names.py → generates datasets/gdelt/company_names.csv)

Reads crsp_dsenames.csv, strips legal suffixes from each comnam, applies manual overrides for edge cases, and outputs 800 GDELT-style search patterns with PERMNO and temporal bounds (namedt/nameendt).

Step 2 — Download and filter daily GKG files (run scripts/gdelt/step2_download_gkg.py → generates datasets/gdelt/raw/gkg_YYYYMMDD.parquet, one per day)

Downloads each daily ZIP into RAM (never written to disk as a temp file), extracts the CSV, filters rows where the ORGANIZATIONS column contains any S&P 500 pattern via regex match, saves only the filtered rows as a parquet file, then discards the ZIP. Peak disk usage: ~500 MB total for all 508 filtered parquets. Resume-safe — already-downloaded dates are skipped on re-run.

python scripts/gdelt/step2_download_gkg.py --year 2025
python scripts/gdelt/step2_download_gkg.py --year 2026

Step 3 — PERMNO matching and daily aggregation (run scripts/gdelt/step3_aggregate_daily.py → generates datasets/gdelt/gdelt_daily.parquet)

Reads all 508 daily parquets, matches organisation names to PERMNOs using temporal bounds from company_names.csv, and aggregates to one row per (PERMNO, date) with tone averages, article counts, source counts, and theme flags.

Output: datasets/gdelt/gdelt_daily.parquet — 170,153 rows, 543 PERMNOs, 2025-01-01 → 2026-06-10.


Scripts Reference

Script Input(s) Output Purpose
scripts/inspect_Item_1A_dataset.py sp500_1A/ (console) Inspect pickle corpus structure
scripts/build_permno_linkage.py ccm_linking_table.csv, sp500_union_constituents(1).csv permno_linkage.csv CIK → PERMNO mapping
scripts/investigate_unmatched.py ccm_linking_table.csv (console) Debug 5 unmatched tickers
scripts/build_filings_index.py sp500_union_constituents(1).csv, EDGAR API filings_index.csv Filing dates + SIC codes
scripts/compute_volatility_labels.py filings_index.csv, all_sp500_prices_2000_2024_delisted_include.csv, crsp_2025_daily.csv volatility_labels.csv 30-day vol windows
scripts/build_feature_table.py filings_index.csv, permno_linkage.csv, volatility_labels.csv feature_table.parquet, feature_table_preview.csv Phase 1 final table
scripts/sanity_check_vol(delete_later).py volatility_labels.csv (console) Vol label validation
scripts/collect_form4.py sp500_union_constituents(1).csv, SEC EDGAR quarterly ZIPs form4_transactions.csv (raw, 32 cols) Downloads 81 quarterly SEC flat files, filters to 652 CIKs, joins SUBMISSION + REPORTINGOWNER + NONDERIV_TRANS
scripts/postprocess_form4.py form4_transactions.csv (raw) form4_transactions.csv (clean, 20 cols) Drops 12 _fn footnote columns; converts dates from DD-MON-YYYY to YYYY-MM-DD
scripts/form4_add_roles.py form4_transactions.csv (clean), SEC EDGAR quarterly ZIPs form4_transactions.csv (final, 24 cols) Re-fetches REPORTINGOWNER from all 81 quarters; parses rptowner_relationship to derive is_officer, is_director, is_ten_pct_owner, officer_title
scripts/test_form4_pipeline.py SEC EDGAR API (console) Smoke-test: validates metadata fetch + XML parse + column structure for 5 companies before full run
scripts/sort_sec_filings.py sec/firm/txt/<CIK>/*.txt sec/sec_filings_index.csv, sec/sec_filings_UNCERTAIN.csv Classifies each filing as 10-K or 10-Q by reading XBRL period token from first line only; flags non-filing exhibit documents as UNCERTAIN
scripts/patch_sec_index.py sec/sec_filings_index.csv sec/sec_filings_index.csv (updated) Manually appends 2 plain-text 10-K filings (CIK 0001881551) that XBRL parser could not classify; already applied — do not re-run
scripts/gdelt/step1_prepare_names.py crsp_dsenames.csv gdelt/company_names.csv Cleans CRSP company names to GDELT-style patterns; 30+ manual overrides; outputs 800 patterns with PERMNO + temporal bounds
scripts/gdelt/step2_download_gkg.py gdelt/company_names.csv, GDELT website gdelt/raw/gkg_YYYYMMDD.parquet Downloads daily GKG ZIPs into RAM, filters for S&P 500 companies, saves filtered rows. Resume-safe.
scripts/gdelt/step3_aggregate_daily.py gdelt/raw/*.parquet, gdelt/company_names.csv gdelt/gdelt_gkg_daily.parquet (primary), gdelt/gdelt_daily.parquet (slim secondary) Matches organisation names to PERMNOs via temporal bounds; aggregates to daily per-PERMNO tone/count features. Use gdelt_gkg_daily.parquet for all pipeline work.

Notes on Data Access and Ethics (§3.4)

  • EDGAR data is publicly available and freely accessible via the SEC submissions API. No licence restrictions.
  • FINSABER prices are sourced from the HuggingFace dataset waylonli/FINSABER-reproduce (public). No redistribution restrictions for research use.
  • WRDS/CRSP data (crsp_2025_daily.csv, ccm_linking_table.csv) is accessed under the University of Edinburgh's institutional licence. Per §3.4 of the report: "CRSP data will be accessed exclusively through WRDS under the University's institutional licence and will not be redistributed or retained beyond the project period." These files must not be shared outside the project.
  • No personal data, human subjects, or proprietary datasets are used.