Â
1. Learning Objectives
By the end of this lesson, you will be able to:
-
Understand the evolution of LLMs (GPT, LLaMA, BloombergGPT) and their financial capabilities.
-
Design effective prompts for financial tasks (sentiment, summarization, QA, earnings translation).
-
Implement fewâshot and chainâofâthought prompting for multiâstep financial reasoning.
-
Fineâtune a preâtrained LLM on financial instructionâfollowing datasets.
-
Address hallucinations and numerical inaccuracies in LLM outputs.
-
Evaluate LLM performance using taskâspecific metrics and human evaluation.
2. LLMs in Finance: Landscape
Generalâpurpose LLMs (GPTâ4, Claude, Gemini) have shown remarkable zeroâshot performance on many tasks. Domainâspecific models like BloombergGPT (50B parameters, trained on financial data) and FinBERT (encoderâonly, smaller) are also available.
Capabilities:
-
Sentiment analysis, summarization, QA, entity extraction (without fineâtuning).
-
Complex reasoning (e.g., âIf the Fed raises rates by 25bps, how might bank stocks react?â).
-
Generation of financial reports, emails, and presentations.
Limitations:
-
Hallucinations: generating plausible but incorrect numbers or facts.
-
Numerical reasoning: can be unreliable; better to offload arithmetic to tools.
-
Knowledge cutoff: may not know recent events; need retrieval augmentation.
3. Prompt Engineering Fundamentals
A prompt is the input text provided to an LLM. The quality of the output heavily depends on the prompt design.
Components:
-
Instruction:Â Clear task description (e.g., âSummarise the following earnings call transcript.â).
-
Context:Â Relevant background (e.g., company name, sector, reference period).
-
Input text:Â The document to process.
-
Output format specification:Â e.g., JSON, bullet points, tables.
-
Fewâshot examples:Â Provide a few inputâoutput pairs to guide the model.
3.1 Zeroâshot, Fewâshot, and ChainâofâThought
-
Zeroâshot:Â No examples; relies solely on instruction.
-
Fewâshot:Â Give 2â5 examples of the task. This dramatically improves performance on structured outputs.
-
ChainâofâThought (CoT):Â Ask the model to âthink stepâbyâstepâ before giving the final answer. This is crucial for multiâstep arithmetic or reasoning.
Example:
Prompt: âA companyâs revenue grew from $100M to $130M over two years. What is the annualised growth rate? Explain step by step.â
Output: âStep 1: Growth factor = 130/100 = 1.3. Step 2: Annualised rate = (1.3)^(1/2) – 1 â 0.1402, i.e., 14.02%.â
3.2 Prompt Templates for Financial Tasks
Sentiment analysis:
Classify the sentiment of the following financial news as 'positive', 'negative', or 'neutral'.
News: {news_text}
Sentiment:
Earnings summary:
Given the following earnings call transcript, produce a summary with the following sections:
- Revenue and EPS (beat/miss)
- Key drivers mentioned
- Guidance
- Risks mentioned
Transcript: {transcript}
Tool use:Â For calculations, prompt the model to output a Python expression, then execute it.
4. Fineâtuning LLMs for Finance
When general models underperform, fineâtune on a financial instruction dataset. Use a base model (e.g., LLaMAâ2, GPTâNeoX) and a dataset of prompts and desired responses.
Instruction tuning:Â Format as (instruction, input, output) triples. Use supervised fineâtuning (SFT) with crossâentropy loss.
ParameterâEfficient Fineâtuning (PEFT):
-
LoRA (LowâRank Adaptation):Â Freeze base model weights and insert trainable lowârank matrices. Reduces memory and time.
Example:
from peft import LoraConfig, get_peft_model, TaskType lora_config = LoraConfig( r=8, lora_alpha=32, target_modules=["q_proj", "v_proj"], lora_dropout=0.05, bias="none", task_type=TaskType.CAUSAL_LM ) model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf") model = get_peft_model(model, lora_config) # Then train with a trainer.
Data sources: Finâinstruction datasets like FinGPTâinstruct, or create your own from SEC filings and earnings calls with humanâwritten summaries.
5. RetrievalâAugmented Generation (RAG)
To incorporate the latest data or specific documents, use RAG: retrieve relevant passages from a vector database (using DPR or BM25) and append them to the prompt.
RAG pipeline:
-
Chunk documents (e.g., 10âK sections) and embed them.
-
For each query, retrieve topâk chunks.
-
Build a prompt: âContext: {chunk1} {chunk2} … Question: {user_question}â
-
Generate answer with the LLM.
Benefits:Â Reduces hallucinations, enables citing sources.
6. Handling Numerical Accuracy
LLMs are not calculators. For reliable arithmetic:
-
Use toolâcalling: have the model generate a Python code snippet to compute the result, then execute it.
-
Alternatively, use chainâofâthought and encourage the model to express the equation.
-
For exact numbers, prefer retrieval over generation.
7. Evaluation of LLM Outputs
-
Automatic metrics:Â For summarization: ROUGE, BERTScore. For QA: EM, F1.
-
Factual consistency:Â Use a separate verification model (e.g., QAFactEval) or check numerical correctness via ground truth.
-
Human evaluation:Â For subjective tasks (e.g., investment recommendations), use expert raters on a Likert scale.
8. Deployment Considerations
-
Latency:Â LLMs are slow; consider smaller models for realâtime tasks.
-
Cost:Â APIâbased models can be expensive; openâsource models may be deployed onâpremise.
-
Security:Â Financial data is sensitive; use local deployments or trusted cloud with encryption.
-
Versioning:Â LLMs evolve; ensure reproducible outputs by pinning model versions.
9. Summary for the AI Practitioner
-
LLMs offer powerful zeroâshot capabilities for many financial NLP tasks.
-
Prompt engineering (instruction, fewâshot, chainâofâthought) is the first lever to improve performance.
-
For domainâspecific needs, fineâtune with LoRA on a financial instruction dataset.
-
RAG is essential for incorporating fresh or proprietary documents and reducing hallucinations.
-
Offload numerical computations to external tools to ensure accuracy.
-
Always evaluate with both automatic metrics and human checks, especially for highâstakes decisions.
10. References
-
Brown, T. B., et al. (2020). Language models are fewâshot learners. NeurIPS.
-
Wu, S., et al. (2023). BloombergGPT: A large language model for finance. arXiv.
-
Hu, E. J., et al. (2022). LoRA: Lowârank adaptation of large language models. ICLR.
-
Lewis, P., et al. (2020). Retrievalâaugmented generation for knowledgeâintensive NLP tasks. NeurIPS.
-
Wei, J., et al. (2022). Chainâofâthought prompting elicits reasoning in large language models. NeurIPS.
-
Zhang, T., et al. (2023). FinGPT: Instruction tuning for financial large language models. Workshop on Financial NLP.