โ† Back to Course Home
MODULE 00

NLP Foundations

From text to understanding - the bridge to modern AI. Learn the fundamentals of Natural Language Processing that laid the groundwork for today's powerful language models.

1. Introduction to Natural Language Processing

Natural Language Processing (NLP) is the field of AI that enables computers to understand, interpret, and generate human language. Before we had powerful foundation models like GPT and Claude, NLP researchers spent decades developing techniques to make sense of text.

What is Natural Language Processing?

NLP sits at the intersection of computer science, linguistics, and artificial intelligence. Its goal: enable machines to process and understand human language in a way that is both meaningful and useful.

๐Ÿ“– Natural Language Understanding (NLU)

Extracting meaning from text. Examples: sentiment analysis, named entity recognition, question answering.

โœ๏ธ Natural Language Generation (NLG)

Producing human-like text. Examples: report generation, summarization, machine translation.

๐Ÿ”„ Natural Language Interaction (NLI)

Conversational AI. Examples: chatbots, virtual assistants, dialogue systems.

Why is NLP So Hard?

Human language is incredibly complex. Unlike structured data or images, language has ambiguity, context-dependency, and cultural nuance that make it challenging for machines to understand.

1. Ambiguity

The same word can have different meanings depending on context:

  • "Bank" โ†’ financial institution or river bank?
  • "Interest" โ†’ financial interest or curiosity?
  • "Apple" โ†’ fruit or tech company?

2. Context Dependency

Meaning changes based on surrounding words:

"The company reported strong earnings, but investors remain cautious."

โ†’ Positive fundamentals, negative sentiment. Understanding requires reading the full sentence.

3. Sarcasm & Figurative Language

Literal meaning โ‰  intended meaning:

"Oh great, another market crash. Just what we needed!" ๐Ÿ˜’

โ†’ Clearly negative, but uses the word "great" (positive). Machines struggle with this.

4. Domain-Specific Language

Financial jargon requires specialized understanding:

"The Fed's hawkish stance on inflation has led to a flight to quality, with investors rotating from growth to value stocks."

โ†’ Requires knowledge of monetary policy, market dynamics, and investment strategies.

The Evolution of NLP: From Rules to Transformers

NLP has gone through several paradigm shifts over the past 60+ years. Understanding this evolution helps us appreciate why modern foundation models are so powerful.

1950s-1980s

Rule-Based NLP

Hand-crafted rules and expert systems. Linguists manually wrote grammar rules and patterns.

Example: "If sentence contains 'not' before a positive word, classify as negative."

โš ๏ธ Problem: Doesn't scale. Too many exceptions and edge cases.

1990s-2000s

Statistical NLP

Machine learning on large text corpora. Models learned patterns from data using probabilistic methods (Hidden Markov Models, Naive Bayes, etc.).

Example: "In financial news, 'earnings beat' appears 87% of the time with positive sentiment."

โœ“ Better generalization, but still limited by feature engineering.

2010s

Neural NLP

Deep learning with word embeddings (Word2Vec, GloVe) and neural networks (RNNs, LSTMs). Models learned to represent words as dense vectors.

Example: "Revenue" and "sales" have similar vector representations because they appear in similar contexts.

โœ“ Automatic feature learning, but still struggled with long-range dependencies.

2017-Present

Transformer Era

Attention mechanisms and Transformers revolutionized NLP. Models can attend to any part of the input, handling long-range dependencies effortlessly.

Example: BERT, GPT, Claude - models that understand context across entire documents.

โœ“ State-of-the-art across all NLP tasks. This is where we are today.

๐Ÿ’ผ NLP Challenges in Financial Services

Finance has unique NLP challenges that make it particularly interesting (and difficult):

๐Ÿ“Š

Numerical Data Mixed with Text

"$1.2B revenue, up 15% YoY" - numbers carry critical meaning

โš–๏ธ

Regulatory Language

Dense, formal, precise language with legal implications

๐Ÿ”ค

Domain-Specific Jargon

P/E ratios, EBITDA, alpha, beta - specialized vocabulary

๐Ÿ“…

Temporal Context Matters

"Fed raised rates" - when? Pre-2022 or post-2022? Huge difference.

2. Text Preprocessing & Tokenization

Before we can analyze text, we need to clean and transform it into a format machines can process. This step is critical - garbage in, garbage out!

What is Text Preprocessing?

Text preprocessing involves cleaning and normalizing raw text to make it suitable for analysis. The goal: reduce noise and standardize the input.

Common Preprocessing Steps

1

Lowercasing

"Apple" and "apple" should be treated the same (usually)

text = text.lower() # "Apple Inc." โ†’ "apple inc."
2

Removing Punctuation

Strip special characters (but be careful with financial data!)

import re text = re.sub(r'[^\w\s]', '', text)
3

Removing Stopwords

Remove common words like "the", "is", "and" (low information)

from nltk.corpus import stopwords stops = set(stopwords.words('english'))
4

Normalization

Handle contractions, unicode, special characters

"won't" โ†’ "will not" | "cafรฉ" โ†’ "cafe"

Tokenization: Breaking Text into Units

Tokenization is the process of splitting text into smaller units called tokens (words, subwords, or characters). This is the first step in any NLP pipeline.

Example: Tokenizing a Financial Sentence

Input:

"Apple Inc.'s Q4 revenue reached $90.1B, up 8% YoY."

Word Tokenization:

['Apple', 'Inc', '.', "'s", 'Q4', 'revenue', 'reached', '$', '90.1', 'B', ',', 'up', '8', '%', 'YoY', '.']

Word Tokenization

Split by whitespace and punctuation

Example:

"Hello world" โ†’ ["Hello", "world"]

โœ“ Simple, interpretable

โœ— Large vocabulary, out-of-vocabulary words

Subword Tokenization

Split into smaller meaningful units (BPE, WordPiece)

Example:

"unhappiness" โ†’ ["un", "happiness"]

โœ“ Handles rare words, smaller vocab

~ Used by GPT, BERT

Character Tokenization

Split into individual characters

Example:

"Hi" โ†’ ["H", "i"]

โœ“ No out-of-vocabulary issues

โœ— Very long sequences

Stemming vs Lemmatization

Both techniques reduce words to their base form, but they work differently:

Stemming

Crude heuristic process that chops off word endings. Fast but imprecise.

Examples:

"running" โ†’ "run" "runner" โ†’ "run" "running" โ†’ "run" "studies" โ†’ "studi" โš ๏ธ "studying" โ†’ "study"

Popular Algorithm: Porter Stemmer

Lemmatization

Uses vocabulary and morphological analysis. Returns actual dictionary words.

Examples:

"running" โ†’ "run" "better" โ†’ "good" "was" โ†’ "be" "studies" โ†’ "study" โœ“ "studying" โ†’ "study"

Popular Tool: spaCy, WordNet Lemmatizer

๐Ÿ’ผ Preprocessing Financial Documents

Financial text has special considerations - you can't just apply standard preprocessing blindly!

โš ๏ธ

Don't Remove All Numbers!

"$1.2B" and "15%" carry critical meaning in finance. Instead, normalize them: "$1.2B" โ†’ "MONEY_1.2B" or keep as-is.

โš ๏ธ

Be Careful with Stopwords

"not" is a stopword, but "not profitable" vs "profitable" have opposite meanings! Consider context before removing.

โœ“

Preserve Financial Entities

Company names, tickers, dates, amounts - these are gold. Consider using Named Entity Recognition (NER) to protect them during preprocessing.

Example: Financial Text Preprocessing Pipeline

import re from spacy import load nlp = load("en_core_web_sm") def preprocess_financial_text(text): # 1. Normalize currency text = re.sub(r'\$(\d+\.?\d*)(B|M|K)?', r'MONEY_\1\2', text) # 2. Normalize percentages text = re.sub(r'(\d+\.?\d*)%', r'PERCENT_\1', text) # 3. Tokenization with spaCy (preserves entities) doc = nlp(text) # 4. Lemmatize but keep financial terms tokens = [token.lemma_ for token in doc if not token.is_stop] return tokens

3. Text Representation: From Words to Numbers

Machines only understand numbers. To process text, we need to represent words as numerical vectors. The question is: how do we capture meaning in numbers?

Bag of Words (BoW): The Simplest Approach

Bag of Words represents text as a vector of word counts. Simple, but loses word order and context.

Example: BoW for Financial Sentences

Sentence 1: "Company revenue increased significantly"

Sentence 2: "Revenue increased slightly"

Vocabulary: [company, revenue, increased, significantly, slightly]

Sentence 1: [1, 1, 1, 1, 0] Sentence 2: [0, 1, 1, 0, 1]

Each position represents a word from the vocabulary. The number is the count of that word in the sentence.

โœ“ Advantages

  • โ€ข Simple to implement
  • โ€ข Interpretable
  • โ€ข Works for short texts

โœ— Disadvantages

  • โ€ข Loses word order
  • โ€ข Ignores context
  • โ€ข Sparse, high-dimensional vectors

TF-IDF: Weighting Words by Importance

TF-IDF (Term Frequency-Inverse Document Frequency) improves on BoW by giving more weight to rare, informative words and less weight to common words.

The Formula

TF-IDF(word, document) = TF(word, document) ร— IDF(word) TF = (# times word appears in doc) / (# total words in doc) IDF = log(# total documents / # documents containing word)

Intuition: If a word appears often in one document but rarely across all documents, it's probably important to that specific document.

๐Ÿ’ผ Example: TF-IDF in Financial Documents

Analyzing 3 earnings call transcripts:

Document 1 (Tech Company):

"Our cloud revenue grew 40% while AI investments increased."

Document 2 (Retail Company):

"Revenue grew 5% driven by store expansion."

Document 3 (Bank):

"Revenue grew 3% as loan volumes increased."

TF-IDF Scores:

"revenue" (appears in all 3) โ†’ Low TF-IDF (common) "cloud" (only in Doc 1) โ†’ High TF-IDF (distinctive) "store" (only in Doc 2) โ†’ High TF-IDF (distinctive) "loan" (only in Doc 3) โ†’ High TF-IDF (distinctive)

โ†’ TF-IDF helps identify what makes each company unique!

Word Embeddings: Capturing Semantic Meaning

BoW and TF-IDF treat words as independent units. Word embeddings represent words as dense vectors where similar words have similar vectors.

The Big Idea: Distributional Semantics

"You shall know a word by the company it keeps"

Words that appear in similar contexts tend to have similar meanings. Embeddings learn these relationships from data.

Example 1:

"The company reported strong earnings."

"The firm reported strong earnings."

โ†’ "company" and "firm" appear in similar contexts

Example 2:

"Revenue increased by 10%."

"Sales increased by 10%."

โ†’ "revenue" and "sales" are interchangeable

Word2Vec (2013)

Predicts context words from target word (Skip-gram) or target from context (CBOW). Learns 100-300 dimensional vectors.

Famous example:

king - man + woman โ‰ˆ queen Paris - France + Germany โ‰ˆ Berlin

โ†’ Vector arithmetic captures relationships!

GloVe (2014)

Global Vectors. Uses word co-occurrence statistics. Pre-trained on Wikipedia, Common Crawl.

Financial example:

revenue - sales โ‰ˆ 0 (very similar vectors) revenue - expense โ‰  0 (different concepts)

โ†’ Captures semantic relationships

โš ๏ธ Limitation: Static Embeddings

Word2Vec and GloVe give each word a single, fixed vector regardless of context. This is a problem!

Example: The Word "Bank"

Sentence 1: "The bank approved my loan." (financial institution)

Sentence 2: "I sat by the river bank." (riverbank)

โ†’ Word2Vec/GloVe assign the SAME vector to both uses of "bank"! ๐Ÿ˜•

This is where contextual embeddings (BERT, ELMo) and eventually Transformers came in! We'll explore this in Module 1. ๐Ÿš€

4. Core NLP Tasks

NLP encompasses many different tasks, each solving a specific problem. Understanding these tasks helps you recognize when and how to apply NLP in finance.

1. Named Entity Recognition (NER)

Named Entity Recognition identifies and classifies named entities (people, organizations, locations, dates, amounts) in text.

๐Ÿ’ผ Financial NER Example

Input Text:

"JPMorgan Chase CEO Jamie Dimon announced a $2.5 billion investment in AI technology on January 15, 2024."

NER Output:

ORGANIZATIONJPMorgan Chase
PERSONJamie Dimon
MONEY$2.5 billion
DATEJanuary 15, 2024

Financial Use Cases

  • โ€ข Extracting companies and executives from earnings transcripts
  • โ€ข Identifying monetary amounts in contracts
  • โ€ข Finding dates of financial events
  • โ€ข Regulatory compliance: detecting mentions of regulated entities

2. Sentiment Analysis

Sentiment Analysis determines the emotional tone of text: positive, negative, or neutral.

โœ“ Positive

"Strong earnings beat expectations, revenue up 25%"

Score: +0.85

โ—‹ Neutral

"The company maintained its dividend at $0.50 per share"

Score: 0.00

โœ— Negative

"Profit warnings issued as costs spiral out of control"

Score: -0.72

๐Ÿ’ผ Financial Sentiment Analysis Use Cases

๐Ÿ“ฐ News Sentiment

Track sentiment of news articles about stocks to predict price movements

๐Ÿ“Š Earnings Call Analysis

Analyze tone of management commentary to gauge confidence

๐Ÿ’ฌ Social Media Monitoring

Track public sentiment on Twitter/Reddit for trading signals

๐Ÿ“ Analyst Reports

Quantify bullish/bearish tone in research reports

3. Text Classification

Text Classification assigns predefined categories to documents.

๐Ÿ’ผ Example: Classifying Financial Documents

10-K

"This annual report provides information about our business, risk factors, and financial condition..."

8-K

"Current report: Material event disclosure regarding acquisition of XYZ Corp..."

S-1

"Registration statement for initial public offering. We intend to offer..."

โ†’ Automatically route documents to appropriate teams based on type

4. Question Answering

Question Answering (QA) systems extract answers from text given a question.

Context (from 10-K):

"Our total revenue for fiscal year 2023 was $125.3 billion, representing a 12% increase from the prior year. Operating income reached $45.2 billion with an operating margin of 36%."

Q: What was the total revenue in 2023?

A: $125.3 billion

Q: What was the operating margin?

A: 36%

โ†’ Modern QA systems power chatbots that can answer questions about financial documents!

5. Traditional Machine Learning for NLP

Before deep learning dominated NLP, traditional ML algorithms (Naive Bayes, SVM, Logistic Regression) were the go-to methods. They still have their place today!

Feature Engineering for Text

Traditional ML requires manual feature engineering - converting text into numerical features that capture important patterns.

Statistical Features

  • โ€ข Word counts, character counts
  • โ€ข Average word length
  • โ€ข Sentence length distribution
  • โ€ข Presence of specific keywords
  • โ€ข Punctuation patterns

Linguistic Features

  • โ€ข Part-of-speech tags
  • โ€ข Named entity counts
  • โ€ข Dependency parse features
  • โ€ข Readability scores
  • โ€ข Sentiment lexicon matches

Classic ML Algorithms for Text

1. Naive Bayes

Probabilistic classifier based on Bayes' theorem. Assumes features are independent (naive assumption).

from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import TfidfVectorizer # Vectorize text vectorizer = TfidfVectorizer() X = vectorizer.fit_transform(documents) # Train classifier clf = MultinomialNB() clf.fit(X, labels) # labels: [0=negative, 1=positive]

โœ“ Fast, works well with small datasets, good for spam detection and sentiment analysis

2. Support Vector Machines (SVM)

Finds the optimal hyperplane that separates classes with maximum margin. Powerful for high-dimensional data (like text).

from sklearn.svm import LinearSVC # SVM with linear kernel clf = LinearSVC() clf.fit(X_train, y_train) predictions = clf.predict(X_test)

โœ“ Effective for text classification, especially with TF-IDF features

3. Logistic Regression

Despite the name, it's a classification algorithm. Models probability of class membership.

from sklearn.linear_model import LogisticRegression clf = LogisticRegression(max_iter=1000) clf.fit(X_train, y_train) # Get probability scores probabilities = clf.predict_proba(X_test)

โœ“ Interpretable, outputs probabilities, good baseline for text classification

When Traditional ML Still Makes Sense

Deep learning isn't always the answer! Traditional ML still shines in certain scenarios:

โšก

Small Datasets

Less than 10,000 examples? Traditional ML often outperforms deep learning which needs more data.

๐Ÿ”

Interpretability Required

Can inspect feature weights to understand why model made a decision. Critical for regulated finance.

๐Ÿ’ฐ

Low Cost/Latency

Fast inference, no GPU required. Can run on edge devices or in real-time systems.

๐ŸŽฏ

Simple Tasks

Spam detection, basic sentiment - don't need a sledgehammer for a nail.

6. Neural Networks for NLP

The 2010s brought a revolution: deep learning. Neural networks, especially those designed for sequences (RNNs, LSTMs), transformed NLP. Then came attention mechanisms - the breakthrough that led to Transformers and modern LLMs.

Recurrent Neural Networks (RNNs)

Unlike traditional neural networks that process fixed inputs, RNNs can handle sequences of variable length by maintaining a "memory" of previous inputs.

How RNNs Work (Intuition)

At each time step, an RNN takes:

  1. Current input (e.g., the current word)
  2. Hidden state (memory from previous words)
  3. Produces: new hidden state + output
Input: "Revenue", "increased", "by", "25%" Step 1: "Revenue" โ†’ h1 (hidden state 1) Step 2: "increased" + h1 โ†’ h2 Step 3: "by" + h2 โ†’ h3 Step 4: "25%" + h3 โ†’ h4 โ†’ Final prediction

โ†’ The hidden state "remembers" earlier words in the sentence!

โš ๏ธ Problem: Vanishing Gradients

RNNs struggled with long-range dependencies. By the time the network processed word #50, it had "forgotten" word #1.

Example: "The company, which was founded in 1995 and operates in 47 countries, reported strong earnings."

โ†’ RNN struggles to connect "company" with "reported" due to long distance.

Long Short-Term Memory (LSTM)

LSTMs solved the vanishing gradient problem with a more sophisticated memory mechanism: gates that control what to remember and forget.

Forget Gate

Decides what information to discard from cell state

Input Gate

Decides what new information to add to cell state

Output Gate

Decides what to output based on cell state

โœ“ LSTMs could handle longer sequences, powering machine translation, speech recognition, and more!

๐ŸŒŸ The Attention Mechanism: The Game Changer

Attention (2014-2017) was the breakthrough that revolutionized NLP. Instead of compressing the entire input sequence into a fixed vector, attention lets the model focus on relevant parts of the input dynamically.

How Attention Works (Simplified)

When translating "The company reported strong revenue growth":

  1. To translate "reported", the model attends to (pays attention to) the words "company" and "reported" more than "the" or "strong"
  2. To translate "growth", it attends to "revenue" and "growth"
  3. Each output word gets a weighted combination of all input words, with weights learned by the model

Attention Weights Visualization:

When generating "reported": "The" โ†’ 0.05 "company" โ†’ 0.40 โ† high attention "reported" โ†’ 0.45 โ† high attention "strong" โ†’ 0.05 "revenue" โ†’ 0.03 "growth" โ†’ 0.02

โ†’ Attention solved the long-range dependency problem and became the foundation for Transformers (which we'll cover in Module 1)!

7. NLP in Financial Services: Real-World Applications

Let's see how NLP techniques we've learned are applied in finance today. These are production systems running at major financial institutions!

1. Sentiment Analysis on Earnings Calls

Problem: Analyzing thousands of earnings call transcripts manually is impossible. Can we automatically detect management sentiment?

NLP Pipeline:

  1. Preprocessing: Extract Q&A section, remove filler words
  2. Feature extraction: TF-IDF or BERT embeddings
  3. Classification: LSTM or Transformer for sentiment (positive/neutral/negative)
  4. Signal generation: High negativity โ†’ sell signal

โœ“ Hedge funds use this to make trading decisions within minutes of earnings releases!

2. Automated Document Routing

Problem: Banks receive thousands of documents daily (contracts, invoices, regulatory filings). How to route them to the right department?

NLP Solution:

  • Extract text from PDFs using OCR
  • Classify document type (10-K, contract, invoice, KYC doc)
  • Extract entities (company name, date, amount)
  • Route automatically to appropriate team

โœ“ Reduces manual processing time by 80%!

3. Regulatory Compliance Monitoring

Problem: Monitor news and communications for mentions of sanctioned entities or potential money laundering patterns.

NLP Techniques:

  • NER to extract company names, people, locations
  • Entity linking to match against watchlists
  • Relationship extraction to find connections between entities
  • Alert generation for suspicious patterns

โ†’ Critical for AML (Anti-Money Laundering) and KYC (Know Your Customer) compliance

4. Chatbots for Customer Support

Problem: Customers ask the same questions repeatedly. Can we automate responses while maintaining accuracy?

Modern Approach:

  • RAG (Retrieval-Augmented Generation): Retrieve relevant policy docs, feed to LLM
  • Intent classification: Understand what customer wants
  • Entity extraction: Account number, transaction ID, etc.
  • Response generation: LLM generates personalized answer

โœ“ 60-70% of customer queries can be automated with high accuracy!

8. From NLP to Foundation Models: The Bridge Forward

We've covered the evolution of NLP from simple Bag of Words to sophisticated attention mechanisms. Now let's connect this to the Transformer revolution that birthed modern foundation models.

What Traditional NLP Still Couldn't Do

1. Task-Specific Models

Every task (sentiment, NER, classification) required training a separate model from scratch. No knowledge transfer.

2. Limited Context Understanding

Even LSTMs struggled with paragraphs or documents. Context window was limited.

3. Data Hungry

Required thousands of labeled examples for each new task. Expensive and time-consuming.

4. Sequential Processing

RNNs/LSTMs processed words one at a time. Couldn't be parallelized. Slow training on long sequences.

๐Ÿš€ The Transformer: "Attention Is All You Need" (2017)

The Transformer architecture, introduced by Google researchers in 2017, changed everything. It threw away recurrence entirely and relied purely on attention mechanisms.

โœ“ What Transformers Solved

  • โœ“ Parallel processing: Process all words simultaneously โ†’ 10x faster training
  • โœ“ Long-range dependencies: Attention to any word, regardless of distance
  • โœ“ Scalability: Can be trained on billions of words
  • โœ“ Transfer learning: Pre-train once, fine-tune for many tasks

๐Ÿ”‘ Key Innovation: Self-Attention

Each word attends to every other word in the sentence, learning which words are most relevant to each other.

"The bank approved my loan."

โ†’ "bank" attends strongly to "approved" and "loan" to understand it's a financial institution, not a riverbank.

From Transformers to Foundation Models

2017

Transformer (Google)

Original architecture for machine translation. "Attention Is All You Need" paper.

2018

BERT (Google) & GPT-1 (OpenAI)

First pre-trained Transformer models. BERT: bidirectional, GPT: autoregressive (predict next word).

2019-2020

GPT-2, GPT-3

Scaling up: 1.5B โ†’ 175B parameters. Few-shot learning emerged. "Foundation model" era begins.

2022-Present

ChatGPT, GPT-4, Claude, Gemini

Instruction-tuned, RLHF-aligned models. Multimodal capabilities. The era we're in now!

๐ŸŽฏ You're Ready for Module 1!

You've now learned the foundations of NLP: from basic text preprocessing to sophisticated neural architectures. You understand what problems Transformers solved and why modern foundation models are so powerful.

In Module 1, we'll dive deep into Foundation Models themselves - GPT, Claude, BERT - and understand how they're revolutionizing finance. Let's go! ๐Ÿš€

๐Ÿงช
Try Lab 0: Document Preprocessor
Clean a real SEBI circular, extract entities, and find distinctive terms with spaCy and TF-IDF. No API key needed. About 45 minutes.
Try the Lab โ†’