This is an archived snapshot, not the current syllabus. It is the single-page version of this course as it stood in February 2026, kept for reference. The course has since been reorganized into twelve topics across several pages, and Topics 13–16 (asset pricing with ML, reinforcement learning, mean field games, and large language models) have moved on — see retired topics for where each went.

Current material: course home  ·  syllabus  ·  slides  ·  labs  ·  recordings

Quant Macro with AI, Machine Learning

Professor: Zhigang Feng

E-mail: z.feng2@gmail.com

Webpage: https://sites.google.com/site/zfeng202/

Course cover: Quant Macro with AI and Machine Learning

Table of Contents

Course Description and Learning Objectives

Quick Links:

Summary

This course prepares economists to thrive in the AI era by fundamentally rethinking the researcher's role: from coder to Research Architect. The central premise is that as AI increasingly handles code implementation, the economist's competitive advantage lies in critical validation and economic safeguarding—the ability to design algorithms, direct AI tools strategically, and rigorously audit outputs for both technical correctness and economic sensibility.

Students will master computational and statistical tools for analyzing structural economic models, integrating traditional methods (dynamic programming, perturbation, projection) with modern AI/ML techniques (deep learning, reinforcement learning). The course emphasizes high-performance computing technologies and uses Python/PyTorch as primary implementation languages. Beyond technical skills, students will explore AI's broader implications for economics, including natural language processing and large language models, with content adapting to reflect the field's rapid evolution.

🏛️ The Paradigm Shift: From Coder to Research Architect

The Big Picture: In the AI era, economic research is undergoing a fundamental transformation. The bottleneck is no longer writing code—it's knowing what code to write, how to validate it works correctly, and ensuring results are economically meaningful. This course trains you to be a Research Architect: someone who masters the logic and theory, leverages AI as a powerful implementation assistant, and critically safeguards the entire research pipeline.

Your competitive advantage as an economist is not in syntax—it's in:

This course is structured around four integrated competencies that together enable you to flourish in this new paradigm:

  1. Competency 1: Theoretical & Algorithmic Mastery

    Master economic theory and numerical methods on paper, before touching code. This includes core economic models and both conventional computational methods (VFI, perturbation, projection) and ML/RL-based approaches. This human-driven, tool-agnostic logic is your irreplaceable foundation—it cannot be outsourced to AI.

  2. Competency 2: Technical Fluency & Tool Literacy

    Develop working knowledge of the modern computational ecosystem:

    • Core Programming Concepts: Data structures, syntax, and programming paradigms (object-oriented, procedural, vectorized, multiple dispatch)
    • Scientific Stack: NumPy, SciPy, JAX for numerical computing; PyTorch for ML/DL
    • Specialized Tools: QuantEcon, EconML, optimization libraries (Gurobi)
    • Infrastructure: HPC, parallel computing (MPI, GPU), version control (Git/GitHub), cloud platforms

    Note: The goal is not to become an expert programmer, but to understand the computational landscape well enough to effectively direct AI tools and critically evaluate their outputs.

  3. Competency 3: AI-Augmented Implementation

    Learn to collaborate with AI coding assistants (LLMs) through what we call "specification-driven development": translating your algorithmic logic (Competency 1) into detailed specifications—pseudocode, data structures, objectives—that AI can transform into working code. This dramatically accelerates the idea-to-implementation pipeline while keeping you in the architect role.

    Evolving Landscape: This competency requires continuous updating as new models and techniques emerge roughly every 2-3 months. Course materials will adapt accordingly.

  4. Competency 4: Critical Validation & Economic Safeguarding

    This is the heart of the course and your future role. You shift from writing code to becoming a rigorous validator:

    • Technical Auditing: Debug AI-generated code, verify numerical stability, check convergence properties
    • Economic Safeguarding: Use economic intuition to detect when results are implausible, validate comparative statics against theory, ensure policy functions satisfy economic constraints
    • Research Integrity: Maintain the intellectual rigor that prevents AI from becoming a sophisticated "garbage generator"

    This competency determines whether you control AI or are controlled by it—whether you're augmented or replaced.

🎯 Learning Objectives

This course serves as a catalyst for faculty and graduate students to enhance their quantitative research capabilities. Upon completion, you will be able to:

In short: You will learn to architect research in the AI era—combining irreplaceable economic judgment with powerful computational tools, while never ceding the critical validation role that defines rigorous scholarship.

This curriculum has been continuously developed and refined since 2019 through teaching experiences at Zhongnan University of Economics and Law (2021-2024), University of International Business and Economics (2023-2025), Huazhong University of Science and Technology (2019), Iowa State University (2025), University of Miami (2025), and Wuhan University (2024, 2025).

▲ Return to Table of Contents

Course Materials

Lecture Slides

Jupyter Notebooks (Labs)

Note: Jupyter notebooks can be viewed directly on GitHub or downloaded and run locally with Python/Anaconda.

▲ Return to Table of Contents

🏛️ Hands-On Philosophy: Practicing the "Research Architect"

The hands-on sessions are the core component of this course, designed to train you in the "Research Architect" role. In the AI era, your value is not in writing boilerplate code but in your ability to specify, direct, and validate complex computational tasks. Our sessions are built around this "specification-driven" workflow.

This workflow transforms how we move from economic theory to computational results. Each hands-on exercise, from a simple cake-eating problem to a complex heterogeneous-agent model, follows this structure:

  1. Mathematical & Economic Formulation:

    We start on paper, defining the optimization problem, recursive formulation (e.g., Bellman equation), and economic constraints.

  2. Algorithmic Specification:

    We design a clear algorithm and write detailed pseudocode (e.g., Value Function Iteration, Euler-equation-based solver). This is the "human logic" that cannot be outsourced.

  3. Define Deliverables:

    We explicitly state our goals. What outputs do we need? A plot of the policy function? A graph showing Euler equation errors? A table of simulated statistics exported to a file?

  4. AI-Augmented Implementation:

    We feed this precise specification (Steps 1-3) to an AI assistant (like ChatGPT, Claude, or Copilot) to generate the initial Python/PyTorch code.

  5. Critical Validation & Expansion:

    This is the most crucial step. We audit the AI's output for technical bugs, economic plausibility, and numerical stability. We then refine the algorithm, expand the model, or enhance the analysis, starting the loop over.

This approach differs fundamentally from static, pre-AI notebooks. The implementation is live, customizable, and expandable. You are in an interactive loop with the AI—using it to fill knowledge gaps (e.g., "Explain this PyTorch function") while you simultaneously safeguard the output with your economic and computational judgment.

These sessions are designed to prove a critical point: your background understanding matters. We will tackle problems where a vague prompt yields a flawed or simple-minded AI response. You will see how providing more detailed, economically-informed instructions and rigorous validation (i.e., being a good Research Architect) allows you to produce more robust, accurate, and sophisticated results.

▲ Return to Table of Contents

List of Topics

(Subject to change based on field advancements and class interest)

Topic 1: Artificial Intelligence for Economics Research

Conceptual Content

🛠️ Hands-On Session: Generic vs. Specification-Driven Prompting

Objective:

Demonstrate how precise, specification-driven prompts yield superior AI-generated code compared to generic requests.

Activities:
  • Example 1: Solving the classical optimal growth model (with closed-form solution for validation).
  • Example 2: Estimating an AR(1) process for TFP shocks.
  • Comparison & Discussion: Evaluate AI outputs from generic vs. specification-driven prompts for correctness and economic plausibility.
▲ Return to Table of Contents

Topic 2: Introduction to Computation for Macroeconomists

Conceptual Content

🛠️ Hands-On Session: Setting Up & First Steps

Objective:

Establish a functional Python environment and apply the Research Architect workflow to simulate the Solow growth model.

Activities:
  • The Digital Workshop: Installing Python (Anaconda) and VS Code.
  • Floating Point Precision: Demonstrating why $0.1 + 0.2 \neq 0.3$ in computers.
  • Algorithmic Thinking: Translating the Solow model into pseudocode and Python loops.
  • Vectorization Basics: Transitioning from loops to NumPy arrays.
▲ Return to Table of Contents

Topic 3: Programming Basics for Economists

Conceptual Content

🛠️ Hands-On Session: Object-Oriented Economics & PyTorch Basics

Objective:

Apply Python programming fundamentals to solve a two-period consumption-saving problem. This session bridges the gap between standard economic modeling (using scipy) and modern AI frameworks (introducing PyTorch tensors).

Learning Outcome:

Students will be able to organize economic models using Python Classes, perform numerical optimization for intertemporal choice, and execute basic linear algebra operations using both NumPy and PyTorch to understand computational efficiency.

Activities:
  • Object-Oriented Economics: Creating an Agent class to encapsulate parameters ($\beta$, $r$) and utility functions.
  • Optimization: Solving the two-period consumption-saving problem using scipy.optimize.
  • Comparative Statics: Visualizing how optimal consumption changes with interest rates.
  • Intro to PyTorch: Creating Tensors, understanding the difference between CPU and GPU data structures.
  • The Speed Race: Benchmarking matrix operations across Pure Python, NumPy, and PyTorch.
▲ Return to Table of Contents

NEW 2026 Topic 3A: AI Coding for Dynamic Equilibrium Models

Slide deck: Lec_2026_3A_AI_Coding.pdf

This lecture formalizes a practical "Research Architect" workflow for AI-assisted macro coding. The key idea is to separate algorithm design from code implementation: economists define theory, numerical method, and validation criteria; AI tools (especially Claude Code) handle implementation loops under supervision.

Conceptual Content

🛠️ Hands-On Session: Claude Code Workflow for Macro Models

Objective:

Use Claude Code to implement and validate a dynamic equilibrium model with a structured, specification-first workflow.

Learning Outcome:

Students will be able to convert an economic specification into a reproducible AI coding pipeline, enforce validation gates, and organize project memory with skills/agents/rules.

Activities:
  • Start from the provided template: Notebooks/my-macro-project.zip.
  • Implement a baseline model version with explicit convergence and Euler-error diagnostics.
  • Add one extension feature at a time and validate each version before moving forward.
  • Run specialized review checks for numerical stability and economic consistency.
▲ Return to Table of Contents

Topic 4: Numerical Methods for Macroeconomists

Conceptual Content

🛠️ Hands-On Session: Numerical Methods & Version Control

Objective:

Master the "Research Architect" workflow by implementing core numerical algorithms (optimization, root-finding, interpolation) and managing the research code lifecycle using Git and GitHub.

Learning Outcome:

Students will be able to initialize a Git repository for their research, select and implement appropriate scipy solvers for economic equilibrium and optimization problems, and discretize stochastic processes (AR(1)) for dynamic models.

Activities:
  • Version Control Basics: Setting up a GitHub repository, creating a .gitignore, and performing the first commit/push cycle.
  • Root-Finding: Solving for market equilibrium prices in non-linear supply/demand systems using Newton-Raphson (scipy.optimize).
  • Optimization: Solving a constrained consumer utility maximization problem and validating First Order Conditions (FOCs).
  • Interpolation: Approximating production functions using Linear vs. Cubic Splines (scipy.interpolate).
  • Stochastic Processes: Discretizing an AR(1) productivity shock using the Tauchen method and validating moments via simulation.
▲ Return to Table of Contents

Topic 5: Introduction to Machine Learning for Economists

Conceptual Content

🛠️ Hands-On Session: Data Fitting with Neural Networks & API Usage

Objective:

Build a neural network from scratch using PyTorch to fit synthetic policy functions and real economic data. Learn to fetch data from online APIs (FRED), preprocess it for AI models, and implement a complete machine learning pipeline.

Learning Outcome:

Students will be able to construct a feedforward neural network using torch.nn.Module, implement a training loop with backpropagation, manage Train/Test splits to prevent overfitting, and interpret model predictions in an economic context.

Activities:
  • The Universal Approximator: Training a Neural Network to "learn" a known non-linear consumption function (Synthetic Data).
  • Building the Engine: Writing a custom PyTorch training loop (Forward Pass, Loss Calculation, Backpropagation, Optimizer Step).
  • Real World Data: Using pandas_datareader to fetch Unemployment and Inflation data from the FRED API.
  • The Phillips Curve: Training a model to predict Inflation based on Unemployment and visualizing the learned relationship.
  • Validation: Using Learning Curves (Train vs. Validation Loss) to diagnose overfitting.
▲ Return to Table of Contents

Topic 6: Solving Macroeconomic Models Using Machine Learning

Conceptual Content

🛠️ Hands-On Session: The Bridge – From VFI to Deep Learning

Objective:

Bridge the gap between classical numerical methods and modern AI. First, solve the Stochastic Optimal Growth model using standard Grid-Based Value Function Iteration (VFI) to establish a benchmark. Then, reframe the problem as a supervised learning task and solve it using PyTorch Neural Networks.

Learning Outcome:

Students will understand the limitations of grid-based methods (Curse of Dimensionality) and how Neural Networks overcome them. They will implement an "Actor-Critic" style architecture where one network approximates the Value Function ($V$) and another approximates the Policy ($\pi$), training them via gradient descent.

Activities:
  • Lab 6A (The Benchmark): Implementing classical VFI with discretization to find the "True" solution.
  • Lab 6B (The Innovation): Building a ValueNet and PolicyNet in PyTorch.
  • The Training Loop: Implementing alternating updates (minimizing Bellman error vs. maximizing expected utility).
  • Comparison: Overlaying the Neural Network's solution on the Classical VFI solution to validate accuracy.
▲ Return to Table of Contents

Topic 7: Numerical Solution Methods for Dynamic Models

Conceptual Content

🛠️ Hands-On Session: Solving the RBC Model with VFI and Time Iteration

Objective:

Implement foundational numerical methods for solving the stochastic growth model using grid-based dynamic programming and Euler equation methods.

Learning Outcome:

Students will be able to calibrate the RBC model, construct appropriate grids, implement VFI with various interpolation schemes, implement time iteration on Euler equations, and compare approaches in terms of implementation complexity and performance.

Activities:
  • Calibrating the RBC model to US business cycle moments.
  • Constructing capital grids and discretizing productivity shocks.
  • Implementing VFI with linear and cubic spline interpolation.
  • Implementing time iteration on the consumption Euler equation.
  • Monitoring convergence and visualizing policy functions.
  • Simulating model economies and computing business cycle statistics.
▲ Return to Table of Contents

Topic 8: Advanced Numerical Methods and Accuracy Assessment

Conceptual Content

🛠️ Hands-On Session: Accelerated Solutions and Accuracy Assessment

Objective:

Implement acceleration techniques and the Endogenous Grid Method, and develop rigorous accuracy assessment skills for validating numerical solutions.

Learning Outcome:

Students will be able to implement Howard's improvement and EGM, compute Euler equation errors across the state space, conduct systematic accuracy comparisons, and select appropriate methods based on problem characteristics.

Activities:
  • Implementing Howard's policy improvement and measuring speedups.
  • Exploiting monotonicity via binary search.
  • Implementing EGM for the RBC model.
  • Computing and visualizing Euler equation errors.
  • Sensitivity analysis: grid density, tolerance, interpolation method.
  • Generating impulse responses and verifying economic plausibility.
▲ Return to Table of Contents

Topic 9: Perturbation and Projection Methods

Conceptual Content

🛠️ Hands-On Session: Perturbation and Chebyshev Approximation for RBC

Objective:

Implement first- and second-order perturbation methods and Chebyshev polynomial projection for the RBC model, comparing local and global solution accuracy across different regions of the state space.

Learning Outcome:

Students will be able to compute linearized and quadratic approximations around steady states, verify Blanchard-Kahn conditions, implement Chebyshev polynomial approximations with collocation, compare accuracy of perturbation vs. projection methods in different state space regions, and determine appropriate solution methods based on problem characteristics.

Activities:
  • Computing the deterministic steady state of the RBC model.
  • Deriving and implementing first-order (log-linear) approximation.
  • Checking Blanchard-Kahn conditions for uniqueness and stability.
  • Implementing second-order perturbation with pruning.
  • Generating impulse responses from perturbation solutions.
  • Implementing Chebyshev polynomial approximation for policy functions.
  • Choosing collocation nodes (Chebyshev zeros or extrema).
  • Solving for polynomial coefficients using collocation equations.
  • Comparing accuracy: perturbation vs. Chebyshev vs. VFI across state space.
  • Analyzing errors: near steady state vs. far from steady state.
  • Computational efficiency comparison: solution time and memory usage.
  • Discussing trade-offs: when to use each method in practice.
▲ Return to Table of Contents

Topic 10: High-Performance and Parallel Computing (HPC)

Conceptual Content

🛠️ Hands-On Session: Parallelizing the RBC VFI Solver

Objective:

Parallelize the Value Function Iteration solver for the RBC model using both traditional MPI approaches and modern PyTorch DDP, comparing scalability and efficiency on multi-core and GPU hardware.

Learning Outcome:

Students will be able to implement parallel VFI using mpi4py with master-worker architecture, parallelize neural network training using PyTorch DDP, submit and manage jobs on HPC clusters with SLURM, measure speedup and efficiency, and select appropriate parallelization strategies based on problem structure and available hardware.

Activities:
  • Analyzing the VFI algorithm for parallelization opportunities.
  • Implementing domain decomposition: partitioning the state space across processes.
  • Writing MPI code with mpi4py: distributing grid points to workers.
  • Implementing gather/scatter operations for value function updates.
  • Handling communication overhead and synchronization.
  • Parallelizing neural network VFI with PyTorch DDP.
  • Setting up process groups and distributed training.
  • Implementing data parallelism for batch processing.
  • Writing SLURM submission scripts for CPU and GPU jobs.
  • Running scaling studies: measuring speedup vs. number of cores/GPUs.
  • Analyzing Amdahl's law limitations in practice.
  • Comparing traditional MPI vs. PyTorch DDP: ease of use, performance, scalability.
  • Profiling code to identify bottlenecks (computation vs. communication).
▲ Return to Table of Contents

Topic 11: Heterogeneous Agents Models with Machine Learning

UPDATED 2026Slide deck: Lec_2026_11_ML_HA_models.pdf

Conceptual Content

🛠️ Hands-On Session: Solving Aiyagari and Krusell-Smith Models

Objective:

Implement and compare stationary and global solution methods for heterogeneous-agent models, from canonical Aiyagari to Krusell-Smith with aggregate shocks.

Learning Outcome:

Students will be able to compute SRCEs, diagnose distributional dynamics, train DeepHAM-style value/policy approximations, and implement Euler-equation-based DEQN training with cloud simulation.

Activities:
  • Build the canonical Aiyagari loop: policy solution, stationary distribution, and market-clearing interest rate.
  • Check uniqueness/convergence assumptions and numerical robustness of the stationary solver.
  • Extend to Krusell-Smith and treat the distribution (or moments) as evolving state variables.
  • Train DeepHAM (value + policy networks) and track learning stability across iterations.
  • Train DEQN by minimizing Euler residuals with cloud simulation over many parallel economies.
  • Compare DeepHAM and DEQN on accuracy, speed, and scalability in high-dimensional settings.
▲ Return to Table of Contents

Topic 12: Heterogeneous-Agent OLG Models (Classic & ML Methods)

Conceptual Content

🛠️ Hands-On Session: Stationary and Dynamic OLG Models

Objective:

Solve a stationary OLG model with idiosyncratic risk using traditional methods, then apply ML techniques to extend the model to include aggregate uncertainty with bonds and government policy.

Learning Outcome:

Students will be able to implement backward induction for lifecycle problems, compute stationary distributions across ages and wealth levels, solve for general equilibrium prices, implement neural networks with embedded market clearing conditions, and apply homotopy methods for training stability in complex models.

Activities:
  • Setting up a stationary OLG model: demographics, lifecycle income, retirement.
  • Implementing backward induction: solving from terminal age backwards.
  • Computing transition matrix across ages, incorporating survival probabilities.
  • Forward iteration to find stationary distribution over (age, wealth, productivity).
  • Market clearing: iterating on interest rate and wages until equilibrium.
  • Analyzing lifecycle patterns: consumption, saving, wealth accumulation.
  • Extending to include aggregate shocks: productivity and potentially policy shocks.
  • Designing neural network architecture with age-conditioning.
  • Implementing market clearing layer that determines prices endogenously.
  • Custom loss function: weighted combination of Euler errors and market clearing errors.
  • Using Fisher-Burmeister function for complementarity constraints (non-negative consumption).
  • Implementing homotopy training: starting from simpler model, gradually adding complexity.
  • Pre-training on fixed prices, then allowing endogenous price determination.
  • Validating ML solution against traditional methods in stationary case.
  • Simulating transition dynamics following aggregate shocks.
▲ Return to Table of Contents

Topic 13: Asset Pricing with Machine Learning

Conceptual Content

🛠️ Hands-On Session: Replicating GKX (2020) with Neural Networks

Objective:

Implement a deep learning pipeline to predict excess stock returns using high-dimensional firm characteristic data, directly replicating the methodology of Gu, Kelly, and Xiu (2020).

Learning Outcome:

Students will be able to preprocess financial panel data, design a Feedforward Neural Network using PyTorch to handle hundreds of predictors, avoid "look-ahead bias" during training, and construct a long-short portfolio to benchmark ML performance against standard Fama-French models.

Activities:
  • Data Management: Handling the "Factor Zoo"—preprocessing 90+ firm characteristics and macro state variables.
  • The Baseline: Running standard OLS and Penalized Regression (Elastic Net) to establish a performance floor.
  • Network Design: Building a 3-layer Neural Network in PyTorch with ReLU activations and Dropout for regularization.
  • Training Strategy: Implementing a rolling-window training scheme to respect the time-series nature of finance (no future data in training set).
  • Portfolio Construction: Sorting stocks by predicted return deciles and calculating the realized Sharpe Ratio of the Long (Top 10%) minus Short (Bottom 10%) strategy.
  • Analysis: Visualizing which characteristics drive the Neural Network's predictions (Variable Importance).
▲ Return to Table of Contents

Topic 14: Reinforcement Learning

Conceptual Content

🛠️ Hands-On Session: Actor-Critic for Dynamic Optimization

Objective:

Implement a complete actor-critic algorithm to solve a dynamic economic optimization problem, understanding the interplay between policy and value learning, and applying this to optimal consumption-saving or policy design problems.

Learning Outcome:

Students will be able to formulate economic problems as MDPs, implement actor and critic neural networks, design appropriate reward functions that capture economic objectives, implement policy gradient updates with baseline subtraction, diagnose and address training instabilities, and compare RL-based solutions with traditional DP approaches.

Activities:
  • Formulating a consumption-saving problem as an MDP: state (wealth, shocks), actions (consumption), rewards (utility).
  • Implementing the critic network to estimate value functions.
  • Implementing the actor network to parameterize stochastic policies.
  • Designing the training loop: collecting experience, computing returns, updating networks.
  • Computing advantage estimates for variance reduction.
  • Implementing policy gradient with baseline (actor update).
  • Implementing TD learning for critic update.
  • Handling exploration: entropy regularization or stochastic policies.
  • Monitoring training: returns, policy entropy, loss trajectories.
  • Diagnosing issues: high variance, poor convergence, suboptimal policies.
  • Comparing with VFI solution: accuracy, computation time, ease of implementation.
  • Extending to continuous action spaces (if time permits).
  • Application: designing optimal tax policies as an RL problem.
▲ Return to Table of Contents

Topic 15: Mean Field Games (MFG) in Continuous Time

Conceptual Content

🛠️ Hands-On Session: Finite-Difference Solver for HJB and MFG System

Objective:

Implement a finite-difference solver using the upwind scheme for a simple HJB equation, then extend to solve a complete mean field game system by iteratively coupling HJB and KFE equations.

Learning Outcome:

Students will be able to discretize continuous-time HJB equations using finite differences, implement the upwind scheme for drift terms, solve KFE for distribution evolution, couple HJB and KFE in a fixed-point algorithm, compute stationary mean field equilibria, and understand the connection between individual optimization and aggregate outcomes in large populations.

Activities:
  • Setting up a simple continuous-time consumption-saving problem (Merton problem).
  • Discretizing the state space (wealth) using finite-difference grid.
  • Deriving the HJB equation with controlled drift and diffusion.
  • Implementing the upwind scheme: choosing forward/backward differences by drift sign.
  • Solving the HJB equation iteratively (value function iteration in continuous time).
  • Extracting optimal policy (consumption) from value function derivatives.
  • Implementing the KFE to compute stationary distribution.
  • Understanding matrix transpose relationship between HJB and KFE operators.
  • Solving KFE as a system of linear equations with normalization.
  • Extending to mean field game: adding aggregate effects (e.g., interest rate depends on aggregate wealth).
  • Implementing fixed-point iteration: solve HJB → extract policy → solve KFE → update aggregate → repeat.
  • Monitoring convergence: policy functions, distributions, and prices.
  • Computing stationary equilibrium and analyzing wealth distribution.
  • Implementing transition dynamics (if time permits): backward-forward shooting.
▲ Return to Table of Contents

Topic 16: Large Language Models

Conceptual Content

🛠️ Hands-On Session: Fine-Tuning BERT for Economic Text Analysis

Objective:

Use the Hugging Face Transformers library to fine-tune a pre-trained BERT model for sentiment analysis of central bank communications, learning the complete pipeline from data preparation to model deployment.

Learning Outcome:

Students will be able to access and load pre-trained transformer models from Hugging Face, prepare text data for transformer training (tokenization, padding, batching), fine-tune models on custom economic datasets, evaluate model performance with appropriate metrics, apply trained models to new texts for economic analysis, and integrate text-based features into economic research.

Activities:
  • Introduction to Hugging Face ecosystem: models, datasets, tokenizers.
  • Loading a pre-trained BERT model and tokenizer.
  • Preparing a dataset: FOMC statements, central bank speeches, or financial news.
  • Creating sentiment labels (manual annotation or using distant supervision).
  • Tokenizing texts: handling special tokens, attention masks, padding.
  • Creating PyTorch DataLoaders for training and validation.
  • Setting up the fine-tuning loop: optimizer, learning rate scheduler, loss function.
  • Training the model: monitoring loss, accuracy, and validation metrics.
  • Implementing early stopping and model checkpointing.
  • Evaluating model performance: confusion matrix, F1 score, ROC curves.
  • Applying the fine-tuned model to classify new texts.
  • Extracting sentiment time series from historical documents.
  • Analyzing relationship between text-based sentiment and economic outcomes (market reactions, policy changes).
  • Visualizing attention weights to interpret model decisions.
  • Discussing integration into economic models: sentiment as a state variable or shock.
  • Extension (if time permits): comparing BERT with simpler methods (word counts, dictionaries).
▲ Return to Table of Contents

References

Acknowledgments

Acknowledgments: I gratefully acknowledge insightful discussions with Dr. Yaolang Zhong (University of Tokyo), Dr. Marlon Azinovic-Yang (UNC Chapel Hill), Dr. Shenghao Zhu, Dr. Yucheng Yang, and Dr. Jiequn Han, among others, as well as teaching experiences at the universities listed below.

▲ Return to Table of Contents