Â
1. Learning Objectives
By the end of this lesson, you will be able to:
-
Understand the architecture of openâdomain and closedâdomain question answering (QA) systems in finance.
-
Implement dense passage retrieval (DPR) and BM25 for retrieving relevant documents from large financial corpora.
-
Apply fineâtuned transformer models (e.g., FinBERTâQA, RoBERTaâbased) for extractive and abstractive QA.
-
Evaluate QA systems using exact match (EM) and F1 scores on financial benchmarks (e.g., FinQA, ConvFinQA).
-
Handle numerical reasoning and tableâbased questions typical in financial reports.
-
Build a endâtoâend QA pipeline for earnings call transcripts or SEC filings.
2. Question Answering in Finance: Overview
Why QA matters:
-
Financial analysts spend significant time searching for specific information (e.g., âWhat was Appleâs revenue growth in Q3 2023?â).
-
Automated QA can provide instant answers from 10âKs, earnings transcripts, and news.
-
Numerical reasoning is essential â many questions involve arithmetic (e.g., âBy how much did net income increase?â).
Types of questions:
| Type | Example | Challenge |
|---|---|---|
| Factoid | âWho is the CEO of JPMorgan?â | Entity extraction |
| Numerical | âWhat was the EPS for Q2 2024?â | Number retrieval |
| Reasoning | âDid revenue grow faster than expenses?â | Multiâstep inference |
| Tableâbased | âWhat is the sum of R&D and SG&A expenses?â | Table parsing + arithmetic |
3. RetrievalâAugmented QA Pipeline
A typical QA system consists of:
-
Retriever:Â Selects a small set of relevant passages from a large corpus.
-
Reader:Â Extracts or generates the answer from the selected passages.
3.1 Retriever: Sparse vs. Dense
BM25 (Sparse):
BM25 is a bagâofâwords ranking function that scores a document d for a query q:
BM25(d,q)=âi=1nIDF(qi)â f(qi,d)â (k1+1)f(qi,d)+k1â (1âb+bâ âŁdâŁavgdl)
where:
-
f(q_i, d) = term frequency in document.
-
|d| = document length; avgdl = average document length.
-
kâ, b = hyperparameters (commonly kâ=1.2, b=0.75).
-
IDF(q_i) = inverse document frequency (log(N / df_i)).
Implementation (using rank_bm25):
from rank_bm25 import BM25Okapi tokenized_corpus = [doc.split() for doc in documents] bm25 = BM25Okapi(tokenized_corpus) scores = bm25.get_scores(query.split()) top_n = sorted(range(len(scores)), key=lambda i: scores[i], reverse=True)[:10]
Dense Passage Retrieval (DPR):
DPR uses dual encoders (one for query, one for passage) to map both to dense vectors. The relevance score is the dot product:
score(q,p)=EQ(q)â¤EP(p)
Training uses a contrastive loss (negative sampling) to push positive pairs closer and negative pairs apart.
Advantage:Â Captures semantic similarity beyond exact word overlap, crucial for financial phrasing.
Implementation with HuggingFace:
from transformers import DPRQuestionEncoder, DPRContextEncoder q_encoder = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base") p_encoder = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base") # Encode passages offline and store vectors in FAISS for fast retrieval.
3.2 Reader: Extractive and Generative
Extractive Reader (e.g., BERTâbased):
Given a passage and a question, the model predicts the start and end positions of the answer span.
Training objective: Minimise crossâentropy loss for start and end logits:
L=âlogâĄP(start)âlogâĄP(end)
where:
P(start=i)=expâĄ(si)âjexpâĄ(sj)
(similar for end).
Abstractive Reader (e.g., T5, BART):
Generates a freeâtext answer, allowing paraphrasing and numerical reasoning.
Fineâtuning on financial datasets:
-
FinQA:Â Dataset with numerical reasoning from financial reports.
-
ConvFinQA:Â Conversational QA with multiâturn reasoning.
4. Handling Numerical and Tabular Questions
Many financial questions involve tables (income statements, balance sheets). We need to parse tables and perform arithmetic.
Approach 1: Tableâaware transformers (e.g., TAPAS, TaBERT)
-
These models take a table and question as input and output a cell selection or an aggregation operation (sum, average, count).
Approach 2: Program synthesis (e.g., FinQA)
-
The model generates a program (operation tree) that is executed on the table to compute the answer.
Example:
Question: âWhat is the operating income divided by revenue?â
Program:Â (op_income / revenue)Â â answer.
Training:Â Sequenceâtoâsequence with program generation.
5. Evaluation Metrics
-
Exact Match (EM):Â The predicted answer matches the ground truth exactly (after normalisation).
-
F1 score:Â Tokenâlevel overlap between predicted and ground truth.
For financial QA, we often use ROUGEâL for generative answers.
Normalisation:Â Remove punctuation, lowercase, standardise numbers (e.g., â$1.2Bâ â â1200000000â).
6. Building a Financial QA System: StepâbyâStep
-
Corpus preparation:Â Collect documents (10âKs, transcripts). Chunk into passages (~100â200 words) with metadata (company, date, section).
-
Indexing:Â Build a retriever index (BM25 or DPR+FAISS).
-
Retrieval:Â For a given question, retrieve topâk passages.
-
Reading:Â Apply a fineâtuned reader (BERTâbase for extractive; T5âbase for abstractive).
-
Postâprocessing:Â If numerical, validate arithmetic; if entity, resolve tickers.
-
Deployment:Â Wrap in an API with caching for frequent questions.
7. Challenges in Financial QA
-
Domainâspecific language:Â Models fineâtuned on general SQuAD perform poorly.
-
Long documents:Â Transformer token limits (512) â we must chunk wisely.
-
Numerical reasoning:Â Models often struggle with arithmetic; explicit program execution is better.
-
Timeâsensitivity:Â Answers may become outdated; incorporate date awareness.
8. Summary for the AI Practitioner
-
Financial QA is a highâvalue application, automating analyst workflows.
-
A twoâstage retrieverâreader architecture is standard; dense retrieval (DPR) often outperforms BM25 for semantic matches.
-
Fineâtuning on financial QA datasets (FinQA, ConvFinQA) is essential.
-
Numerical reasoning can be addressed with tableâaware models or programâsynthesis approaches.
-
Evaluation must consider both exact match and tokenâlevel F1, with normalisation for numbers.
-
Always test with real analyst questions to ensure practical usefulness.
9. References
-
Chen, D., et al. (2017). Reading Wikipedia to answer openâdomain questions. ACL.
-
Karpukhin, V., et al. (2020). Dense passage retrieval for openâdomain question answering. EMNLP.
-
Chen, Z., et al. (2021). FinQA: A dataset of numerical reasoning over financial texts. EMNLP.
-
Reddy, S., et al. (2019). CoQA: A conversational question answering challenge. TACL.
-
Herzig, J., et al. (2020). TAPAS: Weakly supervised table parsing via preâtraining. ACL.