Practical Quantitative Finance with Python
About this Book
Unlock the power of Python to master the world of quantitative finance! Whether you're an aspiring quant developer, an independent trader, or a seasoned programmer looking to transition into finance, this comprehensive guide has everything you need to build sophisticated financial applications.
Practical Quantitative Finance with Python delivers a hands-on approach to mastering modern financial modeling, quantitative analysis, and trading strategy development using Python's most powerful libraries, including NumPy, Pandas, SciPy, and cutting-edge machine learning tools.
This book is perfect for:
- Quant developers and analysts aiming to enhance their technical skills.
- Independent traders looking to build automated trading systems.
- Python programmers seeking to enter the lucrative field of quantitative finance.
- Students and professionals from math, physics, or engineering backgrounds eager to learn financial application development.
Inside, you’ll discover:
- A complete, step-by-step guide to building financial applications using Python.
- Real-world examples and reusable Python libraries for market data APIs, data visualization, option pricing, fixed-income instruments, machine learning, and trading strategies.
- Practical techniques to convert trading ideas into actionable strategies.
- In-depth explanations that cater to all experience levels, from beginners to advanced users.
Written by an industry expert, this book demystifies complex quantitative finance concepts and equips you with the skills to develop powerful business applications. Whether you're building pricing engines, algorithmic trading models, or financial data analytics tools, Practical Quantitative Finance with Python is your essential guide to success.
Start your journey today and transform your financial ideas into real-world applications!
Table of Contents
Contents v Introduction 1 Overview 1 What this Book Includes 2 Is this Book for You? 3 How this Book Is Organized 3 Use Code Examples 5 Customer Support 5 1 Setting Up Development Tools 7 1.1 Install Python 7 1.2 Install Visual Studio Code 10 1.3 Run Python Applications 10 1.4 Python Basics 12 1.4.1 Data Types 13 1.4.2 Functions 15 1.4.3 Control Flows 17 1.4.4 NumPy 20 1.4.5 Enums 23 1.4.6 Series 23 1.4.7 DataFrames 25 2 Database 27 2.1 Python Database API 27 2.2 Database Creation 29 2.2.1 Create Database Tables 29 2.2.2 Check Database 31 2.3 Seed Data 32 2.3.1 Helper Functions 32 2.3.2 Seed Data for Symbol 33 2.3.3 Seed Data for Price 34 2.3.4 Seed Data for IndexData 35 2.4 CRUD Operations 36 2.4.1 PyQt5 GUI 36 2.4.2 Insert Operation 39 2.4.3 Read Operation 42 2.4.4 Update and Delete Operations 45 3 Market Data 51 3.1 Market Data from Yahoo Finance 51 3.1.1 Market Data 52 3.1.2 Download Market Data 53 3.1.3 Save Market Data to Database 58 3.1.4 Stock Quote 65 3.2 Market Data from Alpaca 68 3.2.1 Client Classes 70 3.2.2 Stock Data 71 3.2.3 Intraday Stock Data 75 3.2.4 Data Streaming 78 3.3 Market Data from Charles Schwab 81 3.3.1 Initialize API 81 3.3.2 Stock Data 86 3.3.3 Intraday Stock Data 90 3.3.4 Data Streaming 92 3.4 ISDA Rates from IHS Markit 98 4 Data Visualization 105 4.1 Line Charts 105 4.1.1 Simple Line Charts 105 4.1.2 Multiple-Line Charts 109 4.1.3 Line Charts with Two Y-Axes 111 4.2 Specialized 2D Charts 114 4.2.1 Area Charts 114 4.2.2 Multiple-Area Charts 115 4.2.3 Bar Charts 117 4.2.4 Pie Charts 123 4.2.5 Polar Charts 126 4.3 3D Charts 130 4.3.1 3D Line Charts 130 4.3.2 3D Surface Charts 132 4.4 Stock Charts 140 4.4.1 Candlestick Charts 140 4.4.2 Candlestick and Volume Charts 143 4.4.3 Candlestick with Category 147 5 Linear Analysis 151 5.1 Simple Linear Regression 151 5.1.1 Implementation 152 5.1.2 R-Squared 153 5.1.3 What are Alpha and Beta? 154 5.1.4 SLR for Index Data 154 5.1.5 Data Splitting 158 5.1.6 SLR with Data Splitting for Index Data 160 5.1.7 SLR Results for Stocks 165 5.2 Simple 2D PCA 172 5.2.1 Implementation 172 5.2.2 PCA for Index Data 174 5.2.3 PCA for Stocks 178 5.2.4 Compare SLR and 2D PCA 182 5.3 Multiple Linear Regressions 184 5.3.1 Implementation 184 5.3.2 MLR for Index Data 186 5.3.3 MLR Results for Stocks 190 5.4 Multiple PCA 192 5.4.1 Implementation 192 5.4.2 MPCA for Index Data 195 5.4.3 MPCA Results for Stocks 198 6 Technical Indicators 203 6.1 Overlap Indicators 203 6.1.1 Install TA-Lib 204 6.1.2 Implementation 204 6.1.3 Moving Average Based Indicators 208 6.1.4 Bollinger Band Indicator 211 6.1.5 SAR Indicator 213 6.2 Momentum Indicators 214 6.2.1 Implementation 215 6.2.2 ADX Indicator 220 6.2.3 APO Indicator 221 6.2.4 Aroon Indicator 223 6.2.5 BOP Indicator 225 6.2.6 CCI Indicator 226 6.2.7 MACD Indicator 228 6.2.8 RSI Indicator 229 6.2.9 Stochastic Indicator 231 6.2.10 Williams %R Indicator 233 6.3 Volume Indicators 234 6.3.1 AD Indicator 234 6.3.2 OBV Indicator 236 6.4 Volatility Indicators 237 6.4.1 TR Indicator 237 6.4.2 ATR Indictor 238 6.4.3 NATR Indicator 239 7 Machine Learning 243 7.1 Data Preparation 243 7.1.1 Implementation 244 7.1.2 Check ML Data 247 7.2 Classification 251 7.2.1 Implementation 251 7.2.2 Decision Tree Classifier 256 7.2.3 Confusion Matrix 258 7.2.4 Random Forest Classifier 259 7.2.5 Extra Trees Classifier 260 7.2.6 KNN Classification 262 7.2.7 SVM Classifier 263 7.2.8 Gradient Boosting Classifier 265 7.3 Regression 267 7.3.1 Implementation 267 7.3.2 Decision Tree Regressor 273 7.3.3 AdaBoost Regressor 275 7.3.4 Random Forest Regressor 276 7.3.5 Limitation 278 7.4 Neural Networks 279 7.4.1 Introduction to Neural Networks 279 7.4.2 Data Normalization 282 7.4.3 Neural Networks for Classification 283 7.4.4 Neural Networks for Regression 289 8 Option Pricing 299 8.1 Introduction to Options 299 8.1.1 Option Payoffs 300 8.1.2 Option Value 300 8.2 Pricing European Options 301 8.2.1 Black-Scholes Model 301 8.2.2 Generalized Black-Scholes Model 302 8.2.3 Implementation 302 8.2.4 Black-Scholes Greeks 304 8.2.5 Results for Price and Greeks 310 8.2.6 Results for Implied Volatility 319 8.3 Pricing American Options 325 8.3.1 BAW Approximation 325 8.3.2 Implementation 326 8.3.3 BAW Results 330 8.4 Pricing Barrier Options 335 8.4.1 Standard Barrier Options Formulas 335 8.4.2 Implementation 337 8.4.3 Barrier Option Results 342 9 Option Pricing Using QuantLib 349 9.1 Introduction to QuantLib 349 9.1.1 Dates, Calendars, and Day Counters 349 9.1.2 Term Structures 351 9.2 European Options 352 9.2.1 Helper Functions 353 9.2.2 Price and Greeks Results 356 9.2.3 Helper Functions for Implied Volatility 362 9.2.4 Implied Volatility Results 364 9.3 American Options 368 9.3.1 Helper Functions 368 9.3.2 American Option Results 372 9.4 Barrier Options 377 9.4.1 Helper Functions 377 9.4.2 Barrier Option Results 378 9.5 Bermudan Options 384 9.5.1 Helper Functions 384 9.5.2 Bermudan Option Results 386 9.6 American Options in Real-World 391 9.6.1 Term Structure for Interest Rates 392 9.6.2 Dividend Yield Curve 394 9.6.3 Volatility Smile 395 9.6.4 Helper Functions 396 9.6.5 Real-World Option Results 398 10 Pricing Fixed-Income Instruments 403 10.1 Pricing Simple Bonds 403 10.1.1 Discounting Factors 404 10.1.2 Pricing Bonds with Flat Rates 405 10.1.3 Simple Bond Results 408 10.1.4 Compounding Frequency Conventions 411 10.1.5 Pricing Bonds with a Rate Curve 412 10.1.6 Yield To Maturity 416 10.2 Zero-Coupon Yield Curve 416 10.2.1 Treasury Zero-Coupon Yield Curve 417 10.2.2 Interbank Zero-Coupon Yield Curve 427 10.2.3 Credit Spread Term Structures 432 10.3 Bonds with Embedded Options 441 10.3.1 Callable Bonds 441 10.3.2 Convertible Bonds 445 10.4 CDS Pricing 451 10.4.1 Hazard Rate and Default Probability 451 10.4.2 Risky Annuities and Risky Durations 458 10.4.3 CDS Present Values 458 10.4.4 CDS Prices 467 11 Trading Strategies and Backtesting 475 11.1 Trading Strategy Identification 476 11.2 Get Started with Backtrader 478 11.2.1 Initialize Cerebro Engine 478 11.2.2 Add Market Data 479 11.2.3 Create Strategy 481 11.2.4 Strategy Performance 484 11.2.5 Order Size 486 11.3 Crossover Strategies 487 11.3.1 Two-SMA Crossover 487 11.3.2 Long-Only Strategy 488 11.3.3 Risk Measure 491 11.3.4 Short Only Strategy 495 11.3.5 With Additional Indicators 497 11.4 Z-Score Strategies 501 11.4.1 MA-Based Z-Scores 502 11.4.2 RSI-Based Z-Scores 507 11.4.3 PPO-Based Z-Score 509 11.5 Strategy Optimization 513 11.5.1 Crossover Strategy Optimization 514 11.5.2 Z-score Strategy Optimization 517 11.6 Stock Screener 519 Index 523
Introduction
        Overview
        What This Book Includes
        Is This Book for You
        How This Book is Organized
        Using Code Examples
Overview
Welcome to Practical Quantitative Finance with Python! This book provides all the tools you need to develop modern financial applications using Python. I hope it will prove useful for quant developers, quant analysts, individual traders, Python programmers, and students of all skill levels.
In recent years, quantitative finance has become an attractive field due to its intellectual challenges and high remuneration. Many scientists, engineers, and students aspire to transition into careers as quant developers or analysts in investment banks or hedge funds. Most of these individuals have strong backgrounds in mathematics, statistical analysis, physics modeling, and programming but lack the knowledge and experience specific to quantitative finance. A common question they ask is, “What do I need to prepare myself to become a quant developer or analyst?” This book aims to answer this question, equipping you with solid technical skills in quantitative analysis and development.
On the other hand, especially in the aftermath of the COVID-19 pandemic, more individuals are pursuing careers as independent (“retail”) quantitative traders, seeking to start their own quantitative or algorithmic trading businesses. This path offers the flexibility of working from home and setting your own hours. However, the most frequent question these individuals face is, “What kind of background do I need to be successful in quantitative trading?” Many of these aspiring traders have advanced degrees in physics, math, engineering, or computer science. Such training provides an edge in quantitative analysis and pricing complex derivative instruments. Yet, the ability to convert trading ideas into actionable strategies and the programming skills required to implement an automated trading system are equally vital. This book will provide you with the necessary analytical and programming techniques to succeed as an individual quantitative trader.
So, which programming language is most commonly used in quantitative finance? Traditionally, C++ has been the go-to language for pricing complex derivative securities, and much of the older financial infrastructure is built on it. However, Python has surged in popularity in quantitative finance, thanks to its ease of use, powerful tools, and vibrant community.
Python offers extensive libraries for numerical and science computing. For instance, NumPy provides powerful array and matrix operations, essential for numerical computations in finance; Pandas offers data structures like DataFrames for efficient data manipulation and analysis, which are crucial for working with financial time series data; and SciPy contains a wide range of scientific computing tools, including optimization, integration, and statistical functions used in financial modeling.
Additionally, Python dominates the machine learning space with libraries like scikit-learn, TensorFlow, and PyTorch, which are increasingly applied in finance for tasks such as algorithmic trading, risk management, and fraud detection.
Python’s clear and concise syntax makes it relatively easy to learn and use, even for those with limited programming experience. This reduces development time and allows quants to rapidly prototype and test models. Moreover, Python’s massive and active community provides ample resources, tutorials, and support, making it easier to find solutions and learn from others.
In summary, Python’s combination of powerful libraries, ease of use, strong community support, and versatility makes it an ideal language for quantitative finance. It enables quants to efficiently develop, test, and deploy complex financial models and applications. Therefore, this book will use Python as the programming language to develop various applications for financial markets.
I wrote this book with the intention of providing a complete and comprehensive explanation of modern application development in quantitative finance using Python. This book places special emphasis on creating various business applications and reusable Python libraries that can be directly applied in real-world finance scenarios. Much of the content is based on my own programming experience developing business applications for quantitative analysis in the financial industry.
Practical Quantitative Finance with Python equips you with everything you need to create your own advanced applications in quantitative finance and reusable packages using Python. It demonstrates how Python can be used to build a wide range of financial applications, from simple databases and market data APIs to data visualization, quantitative analysis, equity option pricing, complex fixed-income instruments, machine learning, and trading strategy development.
I will do my best to introduce you to modern application development in quantitative finance in a straightforward manner—simple enough to be easily followed by a quant or Python programmer with basic prior experience in developing business applications in finance.
What This Book Includes
This book and its sample code listings, which are available for download at my website at https://drxudotnet.com, provide you with
- A complete, in-depth instruction to modern web application development in quantitative finance with Python. After reading this book and running the example programs, you will be able to create various sophisticated business applications in quantitative finance using Python.
- Ready-to-run example programs that allow you to explore the quantitative finance programming techniques and understand how the algorithms work. You can modify the code examples or add new features to them to form the basis of your own projects. Some of the example code listings provided in this book are already sophisticated programming packages in quantitative finance that you can use directly in your own real-world business applications.
- Many classes and functions in the sample code listings that you will find useful in your quant development. These classes and functions include charting libraries, various quantitative analysis models, pricing engines for options and fixed income instruments, machine learning for trading strategy development and back-testing, and the other useful utility classes. You can extract these classes and functions and plug them into your own business applications.
Is This Book for You
You do not need to be an experienced quant developer/analyst or Python developer to use this book. I designed it to be useful to people of all levels of Python programming experience and financial backgrounds. In fact, if you have some prior experience with quantitative analysis/development and programming languages such as C++, Java, R, Python, VBA, C#, or JavaScript, you will be able to sit down at your computer, start Visual Studio Code, follow the examples provided in this book, and quickly become proficient in quantitative application development.
For those of you who are already experienced quant analysts/developers or Python programmers, I believe this book has much to offer as well. A great deal of the information in this book about Python programming in quantitative finance is not available in other tutorials and reference books. Additionally, you can use most of the example programs in this book directly in your own real-world application development. This book will provide you with a level of detail, explanation, instruction, and sample code that will enable you to do just about anything related to quantitative finance application development using Python.
Quant analysts/developers, individual quant traders, and Python programmers can routinely use the majority of the example programs in this book. Throughout, I emphasize the usefulness of the application development for real-world quantitative finance problems. If you follow the instructions in this book closely, you will be able to develop various practical business applications in quantitative finance, from linear analysis and machine learning to pricing engines and trading strategy development.
At the same time, I will not spend too much time discussing programming style, execution speed, and code optimization, as many books already cover these topics extensively. Most of the example programs in this book omit error handling to make the code easier to understand by focusing solely on key concepts and practical applications.
How This Book Is Organized
This book is structured into eleven chapters, each exploring a distinct topic related to quantitative finance applications using Python. Below is a summary of each chapter to provide an overview of the book’s contents:
Chapter 1, Setting up Development Tools
This chapter covers the basics of Python, including how to set up the tools, packages, and development environment required for building a Python application with the Visual Studio Code IDE.
Chapter 2, Database
This chapter introduces SQLite and Python database API. It demonstrates how to create simple database and how to interact with the data in Python applications through data services.
Chapter 3, Market Data
This chapter explains how to interact with market data providers’ API and retrieve free market data from online sources. This includes end of the day (EOD) stock data, intraday data, real-time stock price quotes, and interest rate data.
Chapter 4, Data Visualization
Data visualization plays a critical role in quantitative finance and trading. Quant analysts and traders need to visually monitor real-time changes in the market and trading signals on their screens. This chapter illustrates how to use the Plotly library to create various charts and display the market data in a Blazor application.
Chapter 5, Linear Analysis
This chapter presents fundamental analysis approaches in quantitative finance based on linear analysis. It covers how to develop various business applications using linear regression, principal component analysis (PCA), and correlation.
Chapter 6, Technical Indicators
This chapter discusses various technical indicators commonly used in quantitative analysis. A technical indicator is a mathematical calculation based on historic market data, used to predict market direction. I will show you how to convert various indicators provided in TA-Lib library into data services and how to apply them to your Python applications.
Chapter 7, Machine Learning
This chapter covers the advanced quantitative analysis techniques, specifically machine learning. Machine-learning technique has become one of the most promising fields in quantitative finance, widely used in predicting future stock prices. This chapter will focus on supervised learning and present several commonly used machine-learning algorithms in finance, including decision trees, K-nearest neighbors, support vector machines, and neural networks.
Chapter 8, Option Pricing
This chapter discusses the Black-Scholes formula used for options pricing. It presents several different implementations for calculating the price and Greeks of European and American options, as well as barrier options. You will gain a better understanding of how the algorithm works in pricing options through coding exercises.
Chapter 9, Option Pricing Using QuantLib
This chapter demonstrates how to use the open-source library QuantLib to calculate the price and Greeks of European and American options. It also discusses how to use this library to price other options, including barrier options, Bermudan options, and real-world options.
Chapter 10, Pricing Fixed-Income Instruments
This chapter demonstrates how to price fixed-income instruments, including interest rates, bonds, and credit default swaps. It also covers related topics such as cash flows, term structures, yield curves, discount factors, and zero-coupon bonds. Detailed procedures are provided on how to use the QuantLib library to price these complex financial instruments.
Chapter 11, Trading Strategies and Backtesting
This chapter presents several trading strategies using simple quantitative analysis techniques, including crossovers and z-score based on commonly used technical indicators. It also covers a how to use the Backtrader framework to backtest the historical performance of your strategies in stock trading.
Using Code Examples
You may use the code in this book in your own applications and documentation without needing to contact the author for permission, unless you are reproducing a significant portion of the code. For instance, writing a program that utilizes several code segments from this book does not necessitate permission. However, selling or distributing the example code listings requires permission. If you plan to integrate a substantial amount of example code from this book into your applications and documentation, you will also need permission. Integrating the example code from this book into commercial products is prohibited without written permission from the author.