Dataset Viewer
Auto-converted to Parquet Duplicate
Search is not available for this dataset
pdf
pdf

YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

Project One — Can Yesterday's Headlines Tell Us Which Stocks Beat the Market Tomorrow?

Course: FTEC 6V96 · Financial NLP & Textual Analysis · Author: Ashly Caicedo

This project builds a story from two earlier homeworks, HW1 (a data-driven sentiment lexicon compared against TextBlob, VADER and Loughran-McDonald) and HW2 (RBM topic modelling), on a dataset of S&P 500, Dow and NASDAQ news headlines. As the assignment requires, it changes the target variable, the tokenization technique and the ML approach, and reports metrics on the train, test and inference partitions.

Main finding. Once the market-wide move is removed from the target, the words in these headlines do not predict which stocks beat their peers the next day. The lexicon beats the coin flip only on the data it learned from (64.1% precision vs. a 49.5% base rate on train). On data it never saw, it ties (46.7% vs. 46.4% on test) or loses (47.3% vs. 49.9% on inference). Its strongest words are largely company names: it memorized which firms did well in 2019–20, not which language predicts performance.


Contents

File What it is
Project_One_NLP.ipynb The full, self-contained analysis, with every output saved and viewable
Project_One_Slides.pptx The 10-minute presentation, with speaker notes
images/ Charts used in this README, exported from the notebook
README.md This file

1 · What HW1 and HW2 taught us

HW1, the lexicon's edge was the market's mood. The custom lexicon beat all three benchmarks on train and test but lost on inference (0.604 vs. 0.623 precision). In October 2020 the market rose on 62% of days, and the benchmarks said "up" on ~94% of them, so their precision was simply the rally. The label (did the stock go up?) mostly measured the whole market, which no headline about one company can know.

HW2, the topics collapsed. The RBM found three readable topics (earnings data feeds, shareholder-lawsuit ads, analyst ratings and NYSE notices), but assigned 98.4% of documents to one topic, and one topic received none. Much of the "news" is machine-generated templates.

2 · What changed in Project One

Component HW1 / HW2 Project One
Target Did the stock go up the next day? Did the stock beat the median stock the next day?
Tokenization Unigrams; standard stopwords Unigrams + bigrams, finance-aware stopwords, phrase-first counting for the lexicon
Topic model RBM LDA on Bag of Words (course L2 recipe)
Lexicon Estimated on the old target, unigrams Same estimator, re-fit on the new target with phrase-first unigram + bigram tokens
Benchmarks TextBlob, VADER, Loughran-McDonald Same three, re-scored on the new target

3 · The data

  • Source: Hugging Face, firobeid/SP_DOW_NASDAQ_stocks__News_Headlines_labeled, post_processing branch
  • Unit: one row = one ticker on one day (all its headlines that day, plus its next-day return)
  • Size: 91,851 ticker-days · 524 tickers · July 8, 2019 – October 13, 2020, a window that includes the COVID crash
Partition Period Rows after cleaning Base rate (new target)
Train Aug 2019 – Sep 2020 84,745 49.5%
Test Jul 2019 (before train in time) 4,451 46.4%
Inference Oct 2020 (the only forward period) 2,393 49.9%

Integrity checks (Section 3): no missing values or duplicate ticker-days; the old label matches the sign of the return 100% of the time; and returns correlates 0.72 with the next day's price move vs. −0.05 with the previous day's, so the label is the move after the news (no look-ahead).


4 · Method

4.1 Target variable: relative next-day direction

yi,t=1[ ri,t+1−median⁡j(rj,t+1)>0 ]y_{i,t} = \mathbb{1}\left[\, r_{i,t+1} - \operatorname{median}_j\left(r_{j,t+1}\right) > 0 \,\right]

A stock-day is 1 if it beat the median stock the next day. This removes the market-wide move: the monthly share of 1s moves from 41.7%–61.5% under the old target to 46.4%–49.9% under the new one.

Monthly base rate by target definition

Assumptions: the median is taken over tickers in this dataset (not the S&P 500 index); ties count as 0; days with fewer than 20 tickers are dropped (5 of 326 days, 7 rows). The median defines the label only and is never a model input.

4.2 NLP pipeline

  1. Clean: keep letters, tokenize (NLTK), POS-tag, lowercase, and lemmatize with the POS tag (WordNet), as in HW1.
  2. Finance-aware stopwords: the HW1 list (NLTK + Glasgow + spaCy, 430 words) minus 26 direction and negation words that were being deleted (not, no, never, up, down, above, below, over, under, higher, lower, more, less, …), plus 17 wire-service boilerplate words (reuters, rpt, nyse, imbalance, inc, corp, …). Final list: 417 words.
  3. Bigrams: each document's unigrams plus adjacent-word bigrams written as single tokens (price_target), so one token list feeds Bag of Words, gensim coherence and the lexicon.
  4. Phrase-first (lexicon only): a lexicon sums weights, so price + target + price_target would count one idea three times. Where a candidate bigram occurs, it replaces its two words, and overlaps go to the more frequent bigram. This is applied at estimation and scoring, and verified on every document: each word position is counted exactly once.

Token statistics (train): 70,450 distinct unigrams (46.4% appear in only one document) and 1,108,504 distinct bigrams (73.8% appear once). 91,589 of 91,844 ticker-days kept (those with ≥ 3 cleaned words); 66.7% of raw words survive cleaning. Document length is not a shortcut to the label (38.9 vs. 39.6 words on 1 vs. 0 days).

Top unigrams and bigrams

Vocabulary passed to Bag of Words for LDA: tokens appearing in ≥ 10 and ≤ 95% of training documents give 38,309 tokens (12,898 unigrams + 25,411 bigrams; 66.3% bigrams). The professor's max_features = 3,500 cap was removed so bigrams would not crowd out unigrams.

4.3 LDA topic model

The course L2 recipe: CountVectorizer Bag of Words (raw counts) → scikit-learn LatentDirichletAllocation(learning_method='online', random_state=42), swept over K = 1–15 topics, with c_v coherence (gensim) and perplexity; K = argmax(coherence). Fit on train only, then transformed on all three partitions. Adaptations: bigram tokens, a gensim dictionary built from the same tokens, no feature cap, and n_jobs=1 (parallel workers exhausted Colab's shared-memory disk).

Coherence and perplexity

The rule selected K = 2 (c_v = 0.6073), but K = 9 (0.6071) and K = 14 (0.6065) are practically tied, so the data does not strongly prefer any number of topics. Perplexity falls steadily as K grows, which is why it is not used for selection.

LDA topic words

Topic Top words Share of documents (train / test / inference)
1 · Corporate & market news insider, new, market, announces, global, investor, stock, launch, moody, amazon 48.9% / 45.1% / 52.7%
2 · Price targets & earnings price, target, share, raise, earnings, target_price, quarter, cut, mln, price_target 51.1% / 54.9% / 47.3%

The largest topic holds 51.1% of documents, vs. 98.4% under HW2's RBM. But the topics carry no signal on their own: 49.4% (Topic 1) and 49.7% (Topic 2) of training days beat the median, within 0.15 points of the overall 49.5%.

4.4 The lexicon (HW1 estimator, new target, new tokens)

For each token $w$ seen on $n_w$ training days, $k_w$ of them labeled 1, with base rate $b$:

p^w=kw+K bnw+K,scorew=clip⁡(4 S (p^w−b), −4, +4)\hat{p}_w = \frac{k_w + K\,b}{n_w + K}, \qquad \text{score}_w = \operatorname{clip}\big(4\,S\,(\hat{p}_w - b),\,-4,\,+4\big)

A day's scores are summed, normalized VADER-style, and mapped to a probability. The hyperparameters (minimum document frequency, $K$, $S$) are chosen by grid search on train, as in HW1. The selected settings were the loosest in the grid (min 25 days, K = 50, S = 12), giving a 10,507-entry phrase-first lexicon (vs. 6,255 for unigrams only).

4.5 Evaluation

The professor's metrics() on train, test and inference, headlined by precision (when the model says "beats the market," how often is it right?) and always read against that period's base rate. Every scorer's threshold is tuned identically on train: maximum precision subject to recall ≥ 0.30.


5 · Results

Precision vs. base rate

Table B: thresholds tuned on train (recall ≥ 0.30)

Scorer Train Test Inference
Lexicon, phrase-first uni + bi 0.641 0.467 0.473
Lexicon, unigrams only 0.611 0.455 0.488
Loughran-McDonald 0.497 0.467 0.498
TextBlob 0.496 0.465 0.500
VADER (professor's version) 0.496 0.464 0.497
Base rate (coin flip) 0.495 0.464 0.499
Phrase-first lexicon Train Test Inference
Edge over base rate +14.6 pts +0.3 pts −2.7 pts
KS statistic 0.168 0.018 0.036
Accuracy 0.571 0.521 0.487

Reading the results

  • The edge exists only in-sample. On unseen data the lexicon ties or loses to the coin flip, and KS separation collapses from 0.17 to 0.02–0.04. On test its accuracy (0.521) is even below always predicting 0 (0.536).
  • Bigrams helped only on train (0.611 → 0.641).
  • The benchmarks match the base rate by construction: their tuned thresholds make them say "beats" on 73–92% of days, and they give exactly neutral scores on 25–58% of days (vocabulary missing from their dictionaries).

Score distributions

What the lexicon learned. About half of its strongest entries (all at ±4) are company and people names (gardner_denver, carrier_global, walgreens, skyworks, roll_royce) or law-firm boilerplate (kessler_topaz, meltzer_check). A minority is genuine finance language (share_fall, negatively_impacted, up_earnings), and several negative entries are pandemic phrases (spread_coronavirus, face_shield, face_covering). Even terrible scored +4. The lexicon memorized which firms did well in the training window.

Most positive and negative lexicon entries

Results by topic (phrase-first lexicon, precision minus base rate):

Topic Train Test Inference
1 · Corporate & market news +16.3 +3.6 −1.0
2 · Price targets & earnings +12.9 −2.0 −4.7

Same pattern in both topics. Out of sample each cell rests on only 242–584 positive predictions, so differences of a few points are within noise (≈ ±5 points).


6 · Takeaways

  1. The new target removed an illusion. HW1's apparent edge was largely the market's mood.
  2. Headline words did not predict relative next-day returns out of sample, consistent with markets absorbing public news quickly.
  3. LDA described the news far better than HW2's RBM (balanced topics instead of a 98% collapse), but the topics carry no predictive signal.

Next steps for the final project: mask company names; choose hyperparameters on held-out months rather than on train; filter machine-generated notices (tenders, order-imbalance alerts, law-firm ads); try a regularized classifier (e.g., logistic regression with time-based validation); compare K = 2, 9 and 14 by reading the topics, not only by score.

7 · Caveats and assumptions

  • No headline separator exists in the data, so each ticker-day is one text and a few bigrams span two headlines.
  • Ticker A (Agilent) has implausible price levels (median Close 1,243); the other tickers checked (AAPL, MSFT, JPM, XOM) look correct, and the timing check passed.
  • The base rate is not exactly 50% (46.4% on test), likely because of ties at the median, so every result is compared with its own period's base rate.
  • Hyperparameters and thresholds are tuned on train (as in HW1), so train precision is optimistic by construction.
  • Test (July 2019) precedes train; only inference (October 2020, 2,393 rows) is truly forward-looking.
  • Topic names are human interpretations of word lists, and K = 2 won coherence by 0.0002.
  • Bigrams are formed after stopword removal, and LDA counts price_target, price and target separately (accepted, to stay with the course Bag-of-Words recipe).

8 · How to run

  1. Open Project_One_NLP.ipynb in Google Colab and choose Runtime → Run all.
  2. Allow Google Drive access when prompted. Intermediate files (tokens, the LDA sweep, the fitted model, predictions) are saved to MyDrive/project_one_artifacts/lexicon/, so a re-run skips the slow steps and a crashed sweep resumes where it stopped.
  3. Loughran-McDonald: the notebook expects the master dictionary CSV on Drive (LM_PATH in Section 9). If it is missing, that benchmark is skipped with a message.
  4. Runtime on free Colab (first run): tokenization ~15–30 min; LDA sweep ~1 hour; the rest a few minutes.
  5. To force a full recompute, set REBUILD_TOKENS = True and RERUN_LDA = True, and delete lda_sweep_partial.csv from the artifacts folder.

Main libraries: datasets, pandas, numpy, nltk, scikit-learn, gensim>=4.4, textblob, matplotlib, seaborn.


Built on the course materials for FTEC 6V96 (L1 lexicon comparison, L2 topic modelling).

Downloads last month
59