Earnings-Call Sentiment: FinBERT vs Loughran-McDonald in Python

Earnings-Call Sentiment: FinBERT vs Loughran-McDonald in Python

QuantBrainAI covers the tooling layer where natural language processing meets market data. This guide is written for the quant developer or research analyst who wants to score corporate disclosures in Python without hand-waving over licences or data provenance.

About this guide: everything here is documentation- and paper-based. It is built from the FinBERT paper, the ProsusAI/finbert model card, the Financial PhraseBank dataset card, the Loughran-McDonald Master Dictionary documentation, SEC’s EDGAR API page and webmaster FAQ, and the Hugging Face pipelines docs. No hands-on benchmarking was run; the code follows the documented interfaces, and any engineering inference is labelled as ours.

Two families of sentiment method, one trade-off

FinBERT is a context-aware transformer that outputs softmax probabilities over three sentiment labels, while the Loughran-McDonald Master Dictionary is a transparent lexicon that counts words across seven sentiment categories. The trade-off is context sensitivity versus auditability: the neural model understands phrasing but its weights are opaque; the dictionary is fully inspectable but scores tokens in isolation.

The FinBERT paper by Dogu Araci frames the problem precisely: financial sentiment is hard because of specialized language and scarce labelled data, and general-purpose models are not effective enough in a financial context. Pre-trained language models need fewer labelled examples and can be further trained on domain corpora. FinBERT — a language model based on BERT — reportedly improves every measured metric over then-current state-of-the-art results on two financial sentiment analysis datasets, and outperforms state-of-the-art machine learning methods even with a smaller training set and only part of the model fine-tuned. Those are the paper’s reported results, not our measurements.

The ProsusAI/finbert model card fills in the architecture: BERT base — 12 layers, hidden size 768, 12 attention heads — plus a sequence classification head, roughly 0.1B parameters, with the underlying language model further pre-trained on a subset of the Reuters TRC2 corpus and then fine-tuned for sentiment on the Financial PhraseBank. The output is a softmax over three labels: positive, negative, neutral.

The Loughran-McDonald Master Dictionary takes the opposite approach. It is a word list, distributed as CSV, where each entry carries counts, proportions, document counts, and identifiers for seven sentiment categories: negative, positive, uncertainty, litigious, strong modal, weak modal, and constraining. There are no trained weights to interpret, which is why the output can be audited line by line.

The text you can actually get

Earnings-call transcripts are proprietary, so a licence-clean pipeline scores EDGAR filing text instead — 8-K press releases, 10-K and 10-Q documents — fetched through SEC’s free, no-authentication JSON APIs. This is a deliberate substitution: the text is different, but the reuse rights are unambiguous.

This matters more than most tutorials admit. The Loughran-McDonald dictionary itself was constructed partly from tokens examined in all 10-K filings in the full EDGAR archive and earnings calls from CapIQ — calls that sit behind a commercial terminal, not a public API. If your product or research needs text you can legally redistribute and build on, EDGAR is the answer: SEC’s webmaster FAQ states that government-created sec.gov content and EDGAR public filings are free to access and reuse. The practical stand-in for an earnings call is the 8-K earnings press release, plus the richer but slower-moving 10-K and 10-Q documents. If your research specifically needs transcript-level tone, treat that as a data-licensing problem to solve separately, not something EDGAR solves for you.

One more search note: per the webmaster FAQ, only EDGAR Full-Text Search indexes the text content of filings; other EDGAR searches index only filing header metadata. If you need to find which filings mention a phrase, that is the tool.

Fetch, extract, and chunk: the EDGAR front end

Fetch the company’s submissions JSON by 10-digit CIK, pick a filing, download its primary document with a declared User-Agent at no more than 10 requests per second, strip HTML, and split the text into chunks of at most 512 tokens. The chunking exists because the transformer input — not the dictionary — is the bottleneck.

The EDGAR API page documents that data.sec.gov serves RESTful JSON and that “these APIs do not require any authentication or API keys to access.” The submissions endpoint is https://data.sec.gov/submissions/CIK##########.json, where the CIK is the 10-digit central index key with leading zeros; it contains the company name, former names, exchanges, tickers, and at least one year (or 1,000) of recent filings in compact columnar arrays. Two access rules from the webmaster FAQ are non-negotiable: declare a User-Agent in your request headers, and respect the maximum access rate of 10 requests per second. Also note that data.sec.gov does not support CORS — this is a server-side pipeline, not a browser app.

For chunking, our engineering inference from the pipelines docs and BERT base architecture: the pipeline truncates inputs to the model max length, and BERT base has 512 max position embeddings, so long documents must be split and chunk scores aggregated. The dictionary method has no such limit — the constraint is purely on the transformer side.

"""
EDGAR front end: fetch filings for one CIK, extract plain text, chunk.
Respects SEC access rules: declared User-Agent, <= 10 requests/second.
"""
import json
import re
import time
import requests

HEADERS = {
    # Replace with your own declared identity: "Your Company AdminContact@yourdomain.com".
    "User-Agent": "Sample Company Name AdminContact@example.com",
    "Accept-Encoding": "gzip, deflate",
    "Host": "www.sec.gov",
}
MIN_SECONDS_BETWEEN_REQUESTS = 0.11  # ~9 req/s, under the 10 req/s cap


def polite_get(url: str) -> requests.Response:
    time.sleep(MIN_SECONDS_BETWEEN_REQUESTS)
    resp = requests.get(url, headers=HEADERS, timeout=30)
    resp.raise_for_status()
    return resp


def list_recent_filings(cik: str) -> list[dict]:
    """cik must be the 10-digit zero-padded central index key, e.g. '0000320193'."""
    url = f"https://data.sec.gov/submissions/CIK{cik}.json"
    data = polite_get(url).json()
    recent = data["filings"]["recent"]
    filings = []
    for form, accession, primary_doc, date in zip(
        recent["form"],
        recent["accessionNumber"],
        recent["primaryDocument"],
        recent["filingDate"],
    ):
        if form in ("8-K", "10-K", "10-Q"):
            filings.append(
                {
                    "form": form,
                    "filing_date": date,
                    "url": (
                        f"https://www.sec.gov/Archives/edgar/data/"
                        f"{int(cik)}/{accession.replace('-', '')}/{primary_doc}"
                    ),
                }
            )
    return filings


TAG_RE = re.compile(r"<[^>]+>")


def html_to_plain_text(html: str) -> str:
    text = TAG_RE.sub(" ", html)
    text = re.sub(r"&nbsp;|&#160;", " ", text)
    text = re.sub(r"&amp;", "&", text)
    return re.sub(r"\s+", " ", text).strip()


def chunk_text(text: str, max_chars: int = 1600) -> list[str]:
    """
    Split on sentence boundaries into chunks small enough to fit a
    512-token BERT input after tokenization. max_chars is a conservative
    proxy; a production pipeline should count tokens with the model's
    tokenizer instead.
    """
    sentences = re.split(r"(?<=[.!?])\s+", text)
    chunks, current = [], ""
    for sentence in sentences:
        if len(current) + len(sentence) + 1 > max_chars and current:
            chunks.append(current.strip())
            current = ""
        current += (" " if current else "") + sentence
    if current.strip():
        chunks.append(current.strip())
    return chunks


if __name__ == "__main__":
    cik = "0000320193"  # 10-digit, zero-padded
    filings = list_recent_filings(cik)
    example = filings[0]
    raw = polite_get(example["url"]).text
    plain = html_to_plain_text(raw)
    chunks = chunk_text(plain)
    print(example["form"], example["filing_date"], len(chunks), "chunks")
    with open("chunks.json", "w") as f:
        json.dump(chunks, f)

Scoring with FinBERT

Load ProsusAI/finbert through the transformers pipeline, pass the chunk list for batched inference, and request all three label scores with top_k=None. The label ids are 0 positive, 1 negative, 2 neutral; the pipeline returns human-readable labels with probabilities.

The model card’s canonical usage is a two-liner: pipeline("text-classification", model="ProsusAI/finbert"), then call it on a sentence. The pipelines docs explain that the pipeline wraps the model, tokenizer, and pre/post-processing; that “text-classification” has the alias “sentiment-analysis”; and that passing a list of strings runs batched inference and returns a list of dicts. For full datasets, the docs recommend iterating the dataset with KeyDataset rather than allocating everything at once — the pattern we use below for corpus-scale runs. The model card also documents top_k=None to get scores for all three labels rather than just the argmax, which is what you want for a signed sentiment score. At the time we read the card, the model showed 3,378,925 downloads in the last month, 118 fine-tunes, and 100 Spaces — evidence of how widely this exact checkpoint is deployed.

"""
FinBERT scoring over EDGAR chunks, using only documented pipeline behavior.
"""
from transformers import pipeline
from transformers.pipelines.pt_utils import KeyDataset
from datasets import Dataset
import json

# Label ids per the model card: 0 positive, 1 negative, 2 neutral.
LABEL_IDS = {0: "positive", 1: "negative", 2: "neutral"}

classifier = pipeline("text-classification", model="ProsusAI/finbert")


def score_chunks(chunks: list[str]) -> list[dict]:
    """Batched inference; returns one {label: prob} dict per chunk."""
    results = []
    # top_k=None returns scores for all three labels, not just the argmax.
    for out in classifier(chunks, top_k=None, batch_size=8):
        results.append({item["label"]: item["score"] for item in out})
    return results


def score_corpus(corpus: dict[str, list[str]]) -> dict[str, list[dict]]:
    """
    Corpus-scale pattern recommended by the HF docs: iterate a Dataset
    with KeyDataset instead of materializing every string in memory.
    corpus maps document_id -> list of chunk strings.
    """
    rows = [{"doc_id": doc_id, "chunk": c}
            for doc_id, chunks in corpus.items() for c in chunks]
    ds = Dataset.from_list(rows)
    scored = []
    for out in classifier(KeyDataset(ds, "chunk"), top_k=None, batch_size=8):
        scored.append({item["label"]: item["score"] for item in out})
    by_doc: dict[str, list[dict]] = {}
    for row, scores in zip(rows, scored):
        by_doc.setdefault(row["doc_id"], []).append(scores)
    return by_doc


if __name__ == "__main__":
    with open("chunks.json") as f:
        chunks = json.load(f)
    chunk_scores = score_chunks(chunks)
    print(chunks[0][:80], "->", chunk_scores[0])

Scoring with the Loughran-McDonald dictionary

Load the Master Dictionary CSV — or use the Python loader module provided on the dictionary’s page — and match document tokens against the seven sentiment categories. Remember that a negative value in a word’s year-added field means it was removed from that category, so filter on positive years only.

The dictionary’s documentation describes its construction: the base word list derives from release 4.0 of 2of12inf — a common baseline list that includes inflections but excludes abbreviations, acronyms, British spellings, hyphenated words, names, and phrases — extended with words appearing in 10-K documents and earnings calls that were missing from 2of12inf. Each sentiment word carries the year it was added to its category; a negative year means it was removed from that category, which is why the loader below excludes negative years. The Complexity column holds the words from the 2024 JFQA firm-complexity measure, and a Python module that loads the dictionary and its components is provided on the page if you prefer that over hand-rolling. The dictionary is distributed as CSV covering 1993-2025 (an XLSX is also available), free for academic research.

"""
Loughran-McDonald scoring. Download the Master Dictionary CSV from
https://sraf.nd.edu/loughranmcdonald-master-dictionary/ and place it
next to this script as Loughran-McDonald_MasterDictionary_CSV.csv.
"""
import re
import pandas as pd

LM_CSV = "Loughran-McDonald_MasterDictionary_CSV.csv"

CATEGORIES = [
    "negative", "positive", "uncertainty",
    "litigious", "strongmodal", "weakmodal", "constraining",
]
# The CSV's header casing is not something to guess at: resolve each
# category to its real column name after inspecting the file.


def resolve_columns(df, categories):
    """Map normalised category names to the CSV's actual column headers."""
    lookup = {str(c).lower().replace("_", "").replace(" ", ""): c for c in df.columns}
    missing = [cat for cat in categories if cat not in lookup]
    if missing:
        raise KeyError(f"categories not found in CSV header: {missing}")
    return {cat: lookup[cat] for cat in categories}


def load_lm_dictionary(path: str = LM_CSV) -> dict[str, set[str]]:
    df = pd.read_csv(path)
    cols = resolve_columns(df, CATEGORIES)
    lexicon = {}
    for cat in CATEGORIES:
        # A negative year means the word was REMOVED from that category,
        # so keep only entries whose category year is positive.
        words = df.loc[df[cols[cat]] > 0, "Word"].astype(str).str.upper()
        lexicon[cat] = set(words)
    return lexicon


def tokenize(text: str) -> list[str]:
    return re.findall(r"[A-Za-z]+", text.upper())


def lm_scores(text: str, lexicon: dict[str, set[str]]) -> dict[str, float]:
    tokens = tokenize(text)
    n = len(tokens)
    if n == 0:
        return {cat: 0.0 for cat in CATEGORIES}
    counts = {cat: sum(1 for t in tokens if t in lexicon[cat])
              for cat in CATEGORIES}
    return {cat: counts[cat] / n for cat in CATEGORIES}


if __name__ == "__main__":
    lexicon = load_lm_dictionary()
    with open("chunks.json") as f:
        import json
        chunks = json.load(f)
    full_text = " ".join(chunks)
    shares = lm_scores(full_text, lexicon)
    for cat, share in sorted(shares.items(), key=lambda kv: -kv[1]):
        print(f"{cat:>14}: {share:.4f}")

Two construction caveats belong next to any LM result. First, because the base list is 2of12inf, words outside that baseline only enter the dictionary if they appeared in 10-Ks or CapIQ earnings calls — so vocabulary from other domains may simply be absent. Second, the dictionary is a per-token matcher: “no” and “not” do not flip a nearby positive word the way a transformer would. That is the auditability-for-context trade you accepted.

Aggregation and the head-to-head comparison

Our aggregation is a design choice rather than a published convention: we reduce FinBERT to a per-document signed score — the mean of P(positive) minus P(negative) across chunks, or a share-weighted variant — and reduce the dictionary output to category shares on the same text. Then the two methods can be laid side by side on identical documents.

"""
Aggregate both methods per document and render the comparison table.
"""
import json


def finbert_document_score(
    chunk_scores: list[dict],
    chunk_lengths: list[int] | None = None,
) -> float:
    """Mean signed score; optionally weighted by chunk character length."""
    signed = [s.get("positive", 0.0) - s.get("negative", 0.0)
              for s in chunk_scores]
    if chunk_lengths is None:
        return sum(signed) / len(signed)
    total = sum(chunk_lengths)
    return sum(w * s for w, s in zip(chunk_lengths, signed)) / total


def finbert_label_proportions(chunk_scores: list[dict]) -> dict[str, float]:
    """Share of chunks whose argmax label is each class."""
    n = len(chunk_scores)
    argmax = [max(s, key=s.get) for s in chunk_scores]
    return {lab: argmax.count(lab) / n for lab in ("positive", "negative", "neutral")}


if __name__ == "__main__":
    from transformers import pipeline
    classifier = pipeline("text-classification", model="ProsusAI/finbert")

    with open("chunks.json") as f:
        chunks = json.load(f)
    chunk_scores = [
        {item["label"]: item["score"] for item in out}
        for out in classifier(chunks, top_k=None, batch_size=8)
    ]
    lengths = [len(c) for c in chunks]

    print("signed score (mean):",
          finbert_document_score(chunk_scores))
    print("signed score (length-weighted):",
          finbert_document_score(chunk_scores, lengths))
    print("argmax label shares:",
          finbert_label_proportions(chunk_scores))

Which aggregation to use is a design decision, not a settled convention. The unweighted mean treats every chunk equally regardless of density of content; the length-weighted version lets substantive passages dominate; the argmax-label share answers “how much of this document reads as negative at all.” For the dictionary, the natural per-document output is the seven category shares from the previous section — negative share, uncertainty share, and so on — which have no FinBERT counterpart because the model was never trained on those constructs.

Aspect FinBERT (ProsusAI/finbert) Loughran-McDonald Master Dictionary
Method type Transformer: BERT further pre-trained on finance text (model card) Lexicon counting over word lists (dictionary docs)
Output Softmax over 3 labels: positive, negative, neutral Counts and shares across 7 sentiment categories
Context handling Contextual — sentence-level understanding of phrasing Per-token matching; no context or negation handling
Input length Truncated to model max length; chunk to 512 tokens (our inference from the pipelines docs) No model limit; score text of any length
Underlying data Reuters TRC2 subset (further pre-training) + Financial PhraseBank (fine-tuning) 2of12inf baseline extended with 10-K tokens and CapIQ earnings calls
Auditability Weights not inspectable in any practical sense Fully auditable CSV with per-word provenance
Python access One pipeline call CSV download plus the loader module provided on the dictionary page
Licence Weights CC BY-NC-SA 4.0 — non-commercial (model card) Free for academic research; commercial licences via the authors

Validation discipline: agreement rates and the neutral-class trap

Before trusting either method on your documents, interrogate the labelled data behind FinBERT. The Financial PhraseBank contains 4,840 sentences from financial news — the dataset card also cites 4,846 for the 50-agreement config — each labelled by 5-8 annotators from a pool of 16, and it ships in four agreement configurations: sentences_50agree with 4,846 sentences, sentences_66agree with 4,217, sentences_75agree with 3,453, and sentences_allagree with 2,264. Higher-agreement configs are smaller but cleaner.

The dataset card carries two caveats that should shape your expectations. First, all annotators came from one institution — three researchers plus 13 Aalto University School of Business master’s students, mostly finance, accounting, and economics — so the agreement figures should be read with that homogeneity in mind. Second, the labels reflect an investor’s viewpoint: whether the news may move the stock price positively, negatively, or neutrally, with sentiment irrelevant to an economic or financial perspective labelled neutral. That neutral class is generous, and it is where most scoring surprises live — a sentence that is emotionally vivid but financially inert lands in neutral. The source material was English news on OMX Helsinki listed companies via LexisNexis, filtered from a 10,000-article random subset to 53,400 sentences containing a recognised lexicon entity, then sampled to roughly 5,000.

On performance claims: attribute them to the paper, which reports improvement in every measured metric on two financial sentiment datasets and that FinBERT outperforms state-of-the-art machine learning methods even with a smaller training set. That is the authors’ result on their benchmarks — not a measurement of your documents.

Finally, the discipline point that separates a text-scoring exercise from quant research: a sentiment score is not a return signal without an event study. To claim any predictive content, you must align scores with event dates, define a window, and measure abnormal returns against a benchmark — the same discipline as the post-earnings-announcement-drift event-study work covered elsewhere on this site. A signed score that correlates with nothing after alignment is a description, not a signal.

Licence hygiene: research-friendly, product-hostile

Every component in this pipeline carries a non-commercial or academic-only default, and stacking them does not relax any of them. Four licences to track:

  1. FinBERT weights (model card): CC BY-NC-SA 4.0 — non-commercial, adaptations shared alike; the card states plainly that this licence restricts commercial use.
  2. Financial PhraseBank (dataset card): CC BY-NC-SA 3.0; commercial use requires a licence from the authors, Pekka Malo and Ankur Sinha.
  3. Reuters TRC2 corpus: the corpus used for FinBERT’s further pre-training is distributed by NIST under its own access terms — check those terms before any redistribution of derived artifacts.
  4. Loughran-McDonald Master Dictionary (dictionary page): free for academic research; commercial licences are available via the authors.

The practical read: a research notebook, a thesis, or an internal academic study can assemble this entire stack at zero cost. A commercial product — a paid screener, an API you sell, a fund’s proprietary tooling subject to your own licensing review — needs a licensing conversation for essentially every ingredient. EDGAR filing text is the one component with clean reuse rights: per the webmaster FAQ, government-created sec.gov content and EDGAR public filings are free to access and reuse. Plan your architecture around that asymmetry.

One operational note on the dataset side: the Hugging Face dataset viewer for Financial PhraseBank is currently broken because dataset scripts are no longer supported, so an unqualified load_dataset call is not a guaranteed path. Download the data directly from the dataset repository and load the config file you need.

FAQ

Is FinBERT free to use in a commercial product?

No. The weights are CC BY-NC-SA 4.0 (non-commercial, share-alike) and the fine-tuning data, Financial PhraseBank, is CC BY-NC-SA 3.0, so commercial use requires separate licensing from the rights holders.

Can I download earnings-call transcripts for free from EDGAR?

No — transcripts are proprietary, and the Loughran-McDonald dictionary’s call-based vocabulary came from CapIQ, not a public source. EDGAR’s free, reuse-permitted text is filings material such as 8-K press releases and 10-K/10-Q documents.

Why chunk text into 512-token pieces before scoring?

The pipeline truncates inputs to the model max length, and BERT base’s max position embeddings are 512, so long documents must be split and chunk scores aggregated. This is a transformer-side constraint only; the dictionary method has no such limit.

← Back to all posts