Page
1
Quantitative Risk Management Using Python An Essential Guide for Managing Market, Credit, and Model Risk — Peng Liu
Page
2
Quantitative Risk Management Using Python
Page
3
Peng Liu Quantitative Risk Management Using Python An Essential Guide for Managing Market, Credit, and Model Risk
Page
4
Peng Liu Santorini Singapore, Singapore ISBN-13 (pbk): 979-8-8688-1529-4 ISBN-13 (electronic): 979-8-8688-1530-0 https://doi.org/10.1007/979-8-8688-1530-0 Copyright © 2025 by Peng Liu This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Celestin Suresh John Development Editor: James Markham Coordinating Editor: Gryffin Winkler Cover image by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, New York, NY 10004. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer- sbm.com, or visit www.springeronline.com. Apress Media, LLC is a Delaware LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paper- back, or audio rights, please e-mail www.bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub (https://github.com/Apress). For more detailed information, please visit https://www. apress.com/gp/services/source-code. If disposing of this product, please recycle the paper
Page
5
This book is dedicated to my family, particularly my wife, Zheng, and my children, Jiayu, Jiaran, and Jiaxin. Jiayu comes first this time, as his older sisters already declared victory in my other books.
Page
6
Contents About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi About the Technical Reviewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix 1 Introduction to Quantitative Risk Management . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.1 Understanding Different Types of Risk in Financial Markets . . . . . . . . 5 1.1.1 Market Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.1.2 Credit Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 1.1.3 Liquidity Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.1.4 Operational Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 1.1.5 Model Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 1.1.6 Legal and Regulatory Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.1.7 Systemic Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 1.1.8 Environmental, Social, and Governance (ESG) Risk . . . . . . . . . 20 1.1.9 A Summary of Common Risk Types . . . . . . . . . . . . . . . . . . . . . . . . . . 21 1.2 Common Financial Instruments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 1.2.1 Low-Risk Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 1.2.2 Moderate-Risk Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 1.2.3 High-Risk Assets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 1.2.4 Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 1.2.5 A Summary of Financial Instruments by Risk Level . . . . . . . . . 27 1.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2 Fundamentals of Risk and Return in Finance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.1 Understanding Return. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 2.2 Understanding Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 2.3 Risk-Return Trade-Off . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 2.4 Measuring Return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 2.4.1 Absolute Return. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 2.4.2 Percentage Return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 2.4.3 Logarithmic Return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 vii
Page
7
viii Contents 2.4.4 Total Return vs. Price Return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 2.4.5 Annualized Returns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 2.4.6 Single-Period vs. Multi-Period Returns . . . . . . . . . . . . . . . . . . . . . . . 41 2.5 Measuring Risk. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 2.5.1 Annualization of Risk Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 2.5.2 Difference in Volatility Calculated Using Daily vs. Monthly Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 2.6 Measuring Risk-Adjusted Return . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 2.6.1 Sharpe Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 2.6.2 Sortino Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.6.3 Treynor Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 2.6.4 Evaluating Performance Measures in Portfolio Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 2.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 3 Managing Credit Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 3.1 Expected and Unexpected Credit Loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 3.1.1 Unexpected Loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 3.1.2 Stress Loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 3.2 Probability of Default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 3.2.1 Logistic Regression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 3.2.2 Decision Trees and Random Forests . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 3.2.3 Other Machine Learning Classifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 3.3 Loss Given Default. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 3.4 Exposure at Default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 3.5 Expected Credit Loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 3.5.1 Capital Regulation Using Risk-Weighted Asset . . . . . . . . . . . . . . . 79 3.6 Building a PD Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82 3.6.1 Data Processing and Exploration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 3.6.2 Dealing with Outliers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 3.6.3 Dealing with Missing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 3.6.4 Dealing with Categorical Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 3.6.5 Train-Test Split . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 3.6.6 Developing Logistic Regression Model . . . . . . . . . . . . . . . . . . . . . . . 88 3.6.7 Model Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 3.6.8 ROC Curve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90 3.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 4 Managing Market Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 4.1 Variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 4.1.1 Unbiasedness in Sample Variance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 4.1.2 Variance in Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 4.1.3 Limitations of Variance As a Risk Measure . . . . . . . . . . . . . . . . . . . 101 4.2 Maximum Drawdown (Max Drawdown) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 4.2.1 Distinctive Features of Maximum Drawdown. . . . . . . . . . . . . . . . . 108 4.2.2 Calculating Max Drawdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Page
8
Contents ix 4.3 Value at Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 4.3.1 Historical Simulation Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 4.3.2 Variance-Covariance (Parametric) Approach. . . . . . . . . . . . . . . . . . 115 4.3.3 Monte Carlo Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 4.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 5 Risk Management Using Financial Derivatives. . . . . . . . . . . . . . . . . . . . . . . . . . . 125 5.1 Hedging with Futures Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 5.1.1 Hedging Mechanism Using Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 5.1.2 Optimal Hedge Ratio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 5.1.3 Scenario Analysis at Maturity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 5.1.4 Consideration of Basis Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 5.1.5 Implementing the Dynamic Hedging Strategy . . . . . . . . . . . . . . . . 134 5.2 Hedging with Option Contracts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 5.2.1 Protective Put Strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 5.2.2 Implementing the Protective Put Strategy . . . . . . . . . . . . . . . . . . . . . 147 5.2.3 Covered Call Strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152 5.2.4 Implementing the Covered Call Strategy . . . . . . . . . . . . . . . . . . . . . . 157 5.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161 6 Static and Dynamic Hedging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 6.1 Dynamic Hedging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166 6.1.1 Dynamic Delta Hedging Strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 6.1.2 Continuous Rebalancing and Gamma Hedging . . . . . . . . . . . . . . . 168 6.1.3 Dynamic Hedging in Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170 6.2 Static Hedging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 6.2.1 Static Hedging for a Forward Contract . . . . . . . . . . . . . . . . . . . . . . . . 177 6.2.2 Static Hedging for a European Put Option . . . . . . . . . . . . . . . . . . . . 182 6.2.3 Static Hedging for Digital Option. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 6.2.4 Static Hedging with Constant Volatility . . . . . . . . . . . . . . . . . . . . . . . 191 6.2.5 Static Hedging with Changing Volatility . . . . . . . . . . . . . . . . . . . . . . 194 6.2.6 Static Hedging of Digital Call Option in Action . . . . . . . . . . . . . . 196 6.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 7 Managing Model Risk in Finance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 7.1 Model Risk Due to Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202 7.1.1 Data Risks in Financial Machine Learning . . . . . . . . . . . . . . . . . . . . 205 7.1.2 Mitigation Strategies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211 7.2 Model Risk Due to Model Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 7.2.1 Model Bias and Approximation Error . . . . . . . . . . . . . . . . . . . . . . . . . 215 7.2.2 Mitigation Strategies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 7.3 Model Risk Due to Cost Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 7.3.1 Mitigation Strategies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
Page
9
x Contents 7.4 Model Risk Due to Optimization Procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . 221 7.4.1 Estimation Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 7.4.2 Mitigation Strategies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 7.5 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Page
10
About the Author Peng Liu is an Assistant Professor of Quantitative Finance (Practice) at Singapore Management University and an adjunct researcher at the National University of Singapore. He holds a Ph.D. in statistics from the National University of Singapore and has over ten years of working experience across the banking, technology, and hospitality industries. Peng is the author of Bayesian Optimization (Apress, 2023) and Quantitative Trading Strategies Using Python (Apress, 2023). xi
Page
11
About the Technical Reviewer Sonal Raj is an engineer, mathematician, data sci- entist, and Python evangelist from India, who has carved a niche in the financial services domain. He is a Goldman Sachs and D.E. Shaw alumnus who currently serves as Vice President and heads the Data Management and Research division for a leading high-frequency trading firm. Sonal holds a dual master’s degree in Com- puter Science and Business Administration and is a former research fellow of the Indian Institute of Science. His areas of research range from image processing, real-time graph computations to elec- tronic trading algorithms. Sonal is the author of the titles Graph Data Analytics (BPB, 2024), The Pythonic Way (BPB, 2021), and Neo4j High Per- formance (Packt, 2015), among others. During his career, Sonal has been instrumental in designing low latency trading algorithms, trading strategies, market signal models, and components of electronic trading systems. He is also a community speaker and a Python and data science mentor to young minds in the field. When not engrossed in reading fiction or playing symphonies, he spends far too much time watching rockets lift off. He is a loving son, husband, and a custodian of his personal library. xiii
Page
12
Foreword It is a sincere privilege to introduce Quantitative Risk Management Using Python by Peng Liu. Working with Peng at an international bank, I had the opportunity to witness his keen interest in risk management and his thoughtful approach to navigating complex financial challenges. In my roles as his supervisor and friend, I learned a lot from his technical insights and was quietly encouraged by his steady pursuit of excellence. Peng’s transition from the world of corporate risk management to academia is a journey marked by his passion for both understanding and teaching the intricate dynamics of financial risk. In this book, he bridges the gap between abstract risk theories and their tangible applications using Python. His ability to demystify subjects ranging from market, credit, and model risk to sophisticated hedging strategies makes this work an indispensable resource for practitioners, researchers, and students alike. I believe readers will truly benefit from the clarity, depth, and accessible style of this book. Its thoughtful presentation of complex risk management concepts makes them both understandable and relevant to real-world challenges, offering a reliable guide for both experienced professionals and those new to the field. Hong Kong Matteo Crippa April 2025 xv
Page
13
Preface I must confess: the main reason I decided to write this book was to better understand the topics myself and hopefully teach them in a university course without sounding completely lost. When I transitioned from working as a risk management professional at an international bank to academia in 2022, I quickly realized that knowing how to manage risk is one thing; teaching it is an entirely different beast. Over time—and especially with the rapid pace of change brought about by large language models and other breakthroughs in AI—I have come to realize that risk management is more important than ever. Not just in financial institutions, but also in everyday life. So, this book became my way of learning by doing, in the hope that it might also help others, whether you are just starting out or navigating mid-career challenges. The chapters cover a range of topics that I believe are essential for developing a solid foundation in risk management. From the classic risk-return trade-off to the use of futures and options for hedging and eventually the weeds of static and dynamic hedging strategies, there is something for everyone here. You will also find practical ways to measure and manage market risk, a solid introduction to credit risk, and a full chapter dedicated to model risk, which is becoming increasingly relevant as machine learning gains ground in finance. Throughout, I have tried to strike a balance between theory and practice, using Python to make the concepts more accessible and applicable. We will not hope to turn readers into quants overnight, but rather to give you the tools and intuition to approach quantitative risk management with confidence and maybe even enjoy it along the way. I hope you find this book helpful and have fun reading and learning along the way! Singapore, Singapore Peng Liu April 2025 xvii
Page
14
Introduction In an increasingly complex financial landscape, effective risk management is a critical skill for professionals navigating the dynamic world of finance. This book intends to provide a comprehensive and practical approach to understanding and applying risk management techniques using Python. The book serves as an essential resource for finance professionals, academics, and students looking to deepen their knowledge of quantitative risk management. It bridges theoretical concepts with hands-on Python implementations, equipping readers with the tools needed to assess, mitigate, and manage financial risks effectively. Whether you are involved in investment management, banking, financial analytics, or fintech and beyond, this book offers valuable insights into the intricate mechanisms that drive market, credit, and model risk. What YouWill Learn The book systematically introduces key aspects of financial risk management, beginning with foundational principles and advancing to sophisticated techniques for managing risk in various financial contexts. Readers will gain expertise in – Fundamentals of Risk and Return: Understanding different types of financial risk, the role of diversification in portfolio management, and the trade-off between risk and return – Credit Risk Management: Assessing and managing risks associated with default and counterparty credit exposure – Market Risk Management: Identifying, measuring, and mitigating risks stem- ming from market fluctuations – Risk Management Using Financial Derivatives: Exploring how derivatives such as options and futures can be leveraged to manage risk – Static and Dynamic Hedging Strategies: Applying hedging techniques to minimize exposure and protect investment positions – Model Risk Management: Evaluating risks in the development and deployment of machine learning models within the financial sector xix
Page
15
xx Introduction Who Should Read This Book? This book is designed for finance professionals, quantitative analysts, risk managers, students, and academics seeking a structured and practical guide to risk management using Python. Whether you are an industry practitioner looking to enhance your risk modeling skills or a student aiming to build a solid foundation in quantitative finance, this book provides the necessary knowledge and tools to navigate financial risks with confidence. Why This Book? – Hands-On Python Applications: Demonstrates real-world Python implementa- tions across credit risk, market risk, and portfolio management – Comprehensive Coverage: Covers fundamental concepts as well as advanced topics in financial risk management – Practical Focus: Bridges the gap between theoretical models and their applica- tion in financial decision-making With its blend of theory, practice, and programming,Quantitative Risk Management Using Python is a valuable guide for mastering financial risk management in today’s evolving financial landscape.
Page
16
1Introduction to Quantitative Risk Management Financial risk means potential loss in the world of finance. If you invest, risk is everywhere and sometimes is considered even more important than financial return. The flavor of financial risk ranges from day-to-day fluctuations in stock prices, also called volatility, to broader, more unpredictable shocks caused by global events. Common types of financial risk include market risk (price fluctuations), credit risk (borrower defaults), and liquidity risk (difficulty in asset liquidation). These risks are not just abstract ideas; they bring about real challenges that can impact investment portfolios, financial institutions, and even the entire financial system as a whole. For example, a recent study by Marani et al. (2021) analyzed disease outbreaks over the past four centuries and revealed that extreme pandemics are more fre- quent than previously assumed. The research estimates an annual probability of approximately 2% for a pandemic with an impact similar to COVID-19, suggesting that an individual born in the year 2000 would have about a 38% chance of experiencing such an event by now. Furthermore, the study indicates that a pandemic of comparable scale could be expected within the next 59 years. Such an extreme pandemic can disrupt markets, causing volatility, liquidity shortages, and systemic failures. This unpredictability makes it essential that financial professionals have a solid understanding of risk dynamics. Pandemics such as COVID-19 have had undeniably profound effects on our daily lives, reshaping economies, healthcare systems, and social norms, transforming practices like remote work from niche to mainstream. For instance, the S&P 500 plummeted by approximately 34% from its peak in February 2020 to its trough in March 2020 (see Figure 1-1), and the world economy decreased by 3.5% in 2020. In light of these far-reaching impacts, countries and companies are increasingly prioritizing supply chain resilience, emphasizing the importance of diversifying suppliers and establishing alternative sources to mitigate the risk of primary supply disruptions. To properly manage supply chain risk in case of another pandemic, the overall supply chain system needs to have both adaptability and redundancy, which seems to move in the opposite direction against lean management. © Peng Liu 2025 P. Liu, Quantitative Risk Management Using Python, https://doi.org/10.1007/979-8-8688-1530-0_1 1
Page
17
2 1 Introduction to Quantitative Risk Management Figure 1-1 The S&P 500 plummeted by over 30% from its peak in February 2020 to its trough in March 2020 See Listing 1-1 used to generate Figure 1-1. 1 import yfinance as yf 2 import matplotlib.pyplot as plt 3 4 # Define the ticker symbol for S&P 500 ETF 5 ticker = ’^GSPC’ 6 7 # Fetch data from January 1, 2020, to April 1, 2020 8 sp500 = yf.download(ticker, start=’2020-01-01’, end=’2020-04-01’) 9 10 # Plot the closing prices 11 plt.figure(figsize=(8, 5)) 12 plt.plot(sp500.index, sp500[’Close’], label=’S&P 500’, color=’ blue’) 13 plt.title(’S&P 500 Performance (Jan - Mar 2020)’) 14 plt.xlabel(’Date’) 15 plt.ylabel(’Closing Price (USD)’) 16 plt.legend() 17 plt.grid(True) 18 plt.xticks(rotation=45) 19 plt.tight_layout() 20 plt.show() Listing 1-1 S&P 500 price curve But why does risk exist in the first place? Given the inherent uncertainty in the world around us, risk exists because the future is unpredictable and driven by complex interactions between human behavior, environmental changes, and
Page
18
1 Introduction to Quantitative Risk Management 3 Figure 1-2 Calculating the relative frequency as the empirical probability of S&P trending up or down in this period biological evolution. This uncertainty means that we cannot accurately forecast when or where a pandemic might occur, its severity, or its specific impacts. And, as a result, the outcome is a random event. Therefore, quantifying and managing such uncertainty and randomness is the central theme of risk management. The most effective tool for characterizing the randomness of uncertain events is the probability distribution, which captures all possible outcomes and assigns a probability to each. For example, when predicting the likelihood of rain tomorrow, we might assign a probability of 70% to the event of rain. This implies a 30% chance that it will not rain, as the probabilities of all possible outcomes must sum to one. Referring to our previous S&P 500 daily price curve in Figure 1-1, we can calculate the relative frequency of the next day’s price moving up or down by counting the occurrences of each outcome and turning the absolute count into relative frequency. These frequencies allow us to approximate the probability that the market is trending upward or downward the following day. As illustrated in Figure 1-2, the relative frequency, which serves as an empirical probability measure, indicates a 51% likelihood that the S&P 500 closing price would decrease during the period from January to March 2020. Although it is impossible to predict with absolute certainty whether the index will rise or fall on any given day, this approach provides a quantified perspective on the most probable outcome among all possibilities.
Page
19
4 1 Introduction to Quantitative Risk Management See Listing 1-2 used to generate Figure 1-2. 1 # Calculate daily percentage change 2 sp500[’Daily Change’] = sp500[’Close’].diff() 3 4 # Calculate relative frequency of going up or down 5 total_days = len(sp500[’Daily Change’].dropna()) 6 up_days = len(sp500[sp500[’Daily Change’] > 0]) 7 down_days = len(sp500[sp500[’Daily Change’] < 0]) 8 9 up_frequency = up_days / total_days 10 down_frequency = down_days / total_days 11 12 # Prepare data for the bar chart 13 categories = [’Up Days’, ’Down Days’] 14 frequencies = [up_frequency , down_frequency] 15 16 # Plot the bar chart 17 plt.figure(figsize=(6, 4)) 18 bars = plt.bar(categories , frequencies , color=[’green’, ’red’]) 19 plt.title(’Relative Frequency of S&P 500 Daily Changes (Jan - Mar 2020)’) 20 plt.ylabel(’Relative Frequency’) 21 plt.ylim(0, 1) 22 plt.grid(axis=’y’, linestyle=’--’, alpha=0.7) 23 24 # Add exact values as legend 25 for bar, freq in zip(bars, frequencies): 26 plt.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.02, 27 f"{freq:.2f}", ha=’center’, va=’bottom’, fontsize =10) 28 29 plt.tight_layout() 30 plt.show() Listing 1-2 Calculating the relative frequency of going up or down This book, Quantitative Risk Management Using Python, provides a clear and structured guide to the diverse risks that are analyzed and managed in modern financial markets. We will attempt to quantify and manage these risks from multiple perspectives, including financial data, statistical techniques, and mathematical mod- els, ultimately supporting more informed and risk-aware decision-making. At times, effectively managing risk can be even more critical than pursuing high financial returns, especially when dealing with large-scale portfolios. Beyond conceptual and theoretical discussions, we also place a strong emphasis on practical implementation using Python, hoping that readers gain both a robust theoretical framework and the hands-on skills needed to navigate real-world challenges. In the following sections of this chapter, we will first discover key categories of financial risk, including market, credit, and liquidity risk, and then learn common financial instruments and their use in risk management. We aim to build a good
Page
20
1.1 Understanding Different Types of Risk in Financial Markets 5 foundational understanding of the risk landscape and a practical set of quantitative tools to help you navigate the world of financial risk management with confidence. 1.1 Understanding Different Types of Risk in Financial Markets To start, let us take a closer look at what financial markets are about and the different types of risk involved. In financial markets, retail investors, wholesale institutions, and even central governments engage in financial transactions such as buying and selling certain financial instruments, such as stocks, bonds, commodities, and derivatives. These activities promote price discovery, in that they reflect the aggregate beliefs of market participants and provide a way to approximate each instrument’s “fair value” through the dynamics of supply and demand toward market equilibrium. Although some traders seek arbitrage profits by exploiting temporary deviations from the fair value of an asset (which could be due to sudden shocks), others prioritize maximizing returns, minimizing risk, or a combination of both objectives. For example, retail investors can hope to achieve high returns by investing in long- term growth stocks, whereas large institutions often employ low-risk strategies to preserve capital with steady returns and minimal volatility. Consequently, trading activities can vary substantially based on an investor’s goals, resources, and market outlook. In general, market participants have different intentions and employ varying strategies within financial markets. These activities also come with various risks that can pose significant challenges if not properly managed. For example, market risk captures the potential losses due to fluctuations in market prices. Examples include a sudden drop in stock prices after the market observes a negative earnings report or a massive sell-off triggered following an announcement of a political policy (think about how the real estimate market reacts when the government introduces a new policy). If you are not prepared, market risk can lead to substantial losses in your investment portfolio since it will likely fluctuate on the downside (everyone likes upside fluctuation). Besides, there is credit risk, which comes into play when a borrower fails to repay the debt. This risk is particularly significant for banks and bond investors, who are often regulated to report and manage risk exposure should a default event occur. Lastly, liquidity risk says that an investor might not be able to buy or sell an asset quickly as they hope, or even if it is possible, such a fast trade comes with a significant price change (think about selling a property at a fairly low price when in urgent need of cash), potentially leading to losses or missed opportunities. Beyond these, there are other risks, such as operational risk, which deals with failures in internal processes or systems in companies; legal risk, which involves potential losses from lawsuits or changes in regulations; systemic risk, which is the risk of a collapse in the entire financial system; and model risk, which presents the potential loss due to misspecification of the model assumption or incorrect model estimation. The challenges of managing these risks are further compounded by the