Quantitative Finance with C# .NET Blazor
About this Book
Unleash the power of .NET Blazor to build cutting-edge financial applications with “Quantitative Finance with C# .NET Blazor”. This comprehensive guide walks you through the entire process, from setting up your development environment to implementing complex trading strategies.
Learn to:
- Master .NET Blazor Grasp the fundamentals of building dynamic web applications using .NET Blazor and Visual Studio.
- Harness Data Efficiently manage market data, from fetching real-time quotes to storing historical data using SQLite and Entity Framework Core.
- Visualize Insights Create compelling data visualizations with QuickGrid and Plotly.Blazor to uncover hidden patterns and trends.
- Apply Quantitative Techniques: Dive into linear analysis, technical indicators, and machine learning to make informed financial decisions.
- Price Financial Instruments Understand the intricacies of option pricing using the Black-Scholes model and the QuantLib library.
- Model Fixed-Income Explore the world of bonds, interest rates, and credit default swaps with practical examples.
- Backtest trading Strategies Develop and refine trading strategies using a robust backtesting framework.
Whether you're a seasoned quant developer or a curious developer eager to explore quantitative finance, this book provides the knowledge and tools to excel in the world of quantitative finance.
Start building your financial future today!
Table of Contents
Contents v Introduction 1 Overview 1 What this Book Includes 2 Is this Book for You? 3 What Do You Need to Use this Book? 4 How this Book Is Organized 4 Use Code Examples 5 Customer Support 6 1 Introduction to .NET Blazor 7 1.1 Install Visual Studio and .NET SDK 7 1.2 Blazor Render Modes 8 1.3 Create the Blazor Project 8 1.3.1 Create a New Application 8 1.3.2 Structure of the Project 10 1.3.3 Run the Project 12 1.4 Set up Navigation 13 1.4.1 Change Layout 13 1.4.2 Update Home Page 14 1.4.3 Update Navigation Menu 15 1.5 Use QuickGrid 17 1.5.1 Customer Model 18 1.5.2 QuickGrid Implementation 19 1.5.3 Test QuickGrid 20 1.5.4 Pagination 22 2 Database and Entity Framework Core 25 2.1 Install SQLite and Tools 25 2.2 Data Model 26 2.2.1 Connection String 26 2.2.2 Define Model Data Types 26 2.2.3 Define Data Context 27 2.2.4 Check Database 29 2.3 Add Seed Data 30 2.3.1 Helpers Class 30 2.3.2 SeedData Class 32 2.3.3 Add Stock Tickers to Database 33 2.3.4 Add Stock Prices to Database 34 2.3.5 Add Index Data to Database 34 2.3.6 Check Database 35 2.4 Data Service 35 2.4.1 Service Class 35 2.4.2 Display Stock Data 39 2.4.3 Display Stock Price Data 41 2.4.4 Display Index Data 44 2.5 CRUD Operations 46 2.5.1 Create Operation 46 2.5.2 Update and Delete Operations 49 3 Market Data 55 3.1 Market Data from Yahoo Finance 55 3.1.1 Stock Data 56 3.1.2 Download Market Data 57 3.1.3 Save Market Data to Database 60 3.1.4 Stock Quote 65 3.2 Market Data from Fynance 70 3.2.1 Stock Data 70 3.2.2 Download Market Data 71 3.2.3 Intraday Stock Data 73 3.3 Market Data from Alpha Vantage 76 3.3.1 Create API Key Service 76 3.3.2 EOD Stock Data 77 3.3.3 Intraday Stock Data 81 3.3.4 Stock Quotes 85 3.4 ISDA Rates from IHS Markit 87 3.4.1 ISDA Interest Rate API 88 3.4.2 Email Service 91 3.4.3 Test ISDA Interest Rate API 92 4 Data Visualization 97 4.1 Line Charts 98 4.1.1 Simple Line Charts 98 4.2 Multiple-Line Charts 101 4.3 Line Charts with Two Y-Axes 103 4.4 Specialized 2D Charts 107 4.4.1 Area Charts 107 4.4.2 Multiple-Area Charts 109 4.4.3 Bar Charts 113 4.4.4 Pie Charts 120 4.4.5 Polar Charts 123 4.5 3D Charts 126 4.5.1 3D Line Charts 126 4.5.2 3D Surface Charts 129 4.6 Stock Charts 141 4.6.1 Candlestick Charts 141 4.6.2 Candlestick and Volume Charts 144 4.6.3 Candlestick with Category 149 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 Data Service 154 5.1.5 SLR Results for Index Data 156 5.1.6 SLR Results for Stocks 161 5.2 Simple 2D PCA 167 5.2.1 Implementation 169 5.2.2 Data Service 170 5.2.3 2D PCA Results for Index Data 171 5.2.4 2D PCA Results for Stocks 176 5.2.5 Compare SLR and 2D PCA 181 5.3 Multiple Linear Regressions 183 5.3.1 Implementation 183 5.3.2 Data Service 186 5.3.3 MLR Results for Index Data 187 5.3.4 MLR Results for Stocks 191 5.4 Multiple PCA 196 5.4.1 Implementation 196 5.4.2 Data Service 197 5.4.3 MPCA Results for Index Data 198 5.4.4 MPCA Results for Stocks 202 6 Technical Indicators 209 6.1 Implementation 209 6.1.1 Helper Class 210 6.1.2 Data Service 220 6.2 Chart Templates 226 6.2.1 Template for Overlay Indicators 226 6.2.2 Template for Oscillator-Based Indicators 231 6.3 Overlap Indicators 237 6.3.1 Moving Average Based Indicators 237 6.3.2 Bollinger Band Indicator 241 6.3.3 SAR Indicator 243 6.4 Momentum Indicators 246 6.4.1 ADX Indicator 247 6.4.2 APO Indicator 249 6.4.3 Aroon Indicator 251 6.4.4 BOP Indicator 254 6.4.5 CCI Indicator 256 6.4.6 MACD Indicator 258 6.4.7 RSI Indicator 261 6.4.8 Stochastic Indicator 263 6.4.9 Williams %R Indicator 266 6.5 Volume Indicators 268 6.5.1 AD Indicator 268 6.5.2 OBV Indicator 270 6.6 Volatility Indicators 273 6.6.1 TR Indicator 273 6.6.2 ATR Indictor 275 6.6.3 NATR Indicator 277 7 Machine Learning 281 7.1 Data Preparation 281 7.1.1 Implementation 283 7.1.2 Data Service 288 7.1.3 Helper Functions 289 7.1.4 Original ML Data 292 7.1.5 Processed ML Data 294 7.2 KNN Classification 298 7.2.1 Implementation 299 7.2.2 Template for Classification 300 7.2.3 KNN Results 304 7.2.4 Confusion Matrix 306 7.3 Support Vector Machine 308 7.3.1 SVM For Classification 308 7.3.2 SVM for Regression 312 7.4 Artificial Neural Networks 321 7.4.1 Introduction to Neural Networks 321 7.4.2 Helper Class 323 7.4.3 Neural Networks for Classification 325 7.4.4 Neural Networks for Regression 334 8 Option Pricing 345 8.1 Introduction to Options 345 8.1.1 Option Payoffs 346 8.1.2 Option Value 346 8.2 Pricing European Options 347 8.2.1 Black-Scholes Model 347 8.2.2 Generalized Black-Scholes Model 348 8.2.3 Implementation 348 8.2.4 Black-Scholes Greeks 351 8.2.5 Display Results 357 8.3 Pricing American Options 374 8.3.1 BAW Approximation 374 8.3.2 Implementation 375 8.3.3 BAW Results 379 8.4 Pricing Barrier Options 383 8.4.1 Standard Barrier Options Formulas 383 8.4.2 Implementation 385 8.4.3 Barrier Option Results 392 9 Option Pricing Using QuantLib 397 9.1 Introduction to QuantLib 397 9.1.1 Dates, Calendars, and Day Counters 397 9.1.2 Term Structures 399 9.2 European Options 400 9.2.1 Helper Class 400 9.2.2 Price and Greeks Results 404 9.2.3 Helper Functions for Implied Volatility 409 9.2.4 Implied Volatility Results 410 9.3 American Options 412 9.3.1 Helper Functions 413 9.3.2 American Option Results 416 9.4 Barrier Options 421 9.4.1 Helper Functions 421 9.4.2 Barrier Option Results 423 9.5 Bermudan Options 427 9.5.1 Helper Functions 427 9.5.2 Bermudan Option Results 430 9.6 American Options in Real-World 434 9.6.1 Term Structure for Interest Rates 434 9.6.2 Dividend Yield Curve 436 9.6.3 Volatility Smile 437 9.6.4 Helper Functions 438 9.6.5 Real-World Option Results 440 10 Pricing Fixed-Income Instruments 445 10.1 Pricing Simple Bonds 445 10.1.1 Discounting Factors 446 10.1.2 Pricing Bonds with Flat Rates 447 10.1.3 Simple Bond Results 450 10.1.4 Compounding Frequency Conventions 452 10.1.5 Pricing Bonds with a Rate Curve 453 10.1.6 Yield To Maturity 457 10.2 Zero-Coupon Yield Curve 457 10.2.1 Treasury Zero-Coupon Yield Curve 458 10.2.2 Interbank Zero-Coupon Yield Curve 467 10.2.3 Credit Spread Term Structures 472 10.3 Bonds with Embedded Options 482 10.3.1 Callable Bonds 482 10.3.2 Convertible Bonds 487 10.4 CDS Pricing 492 10.4.1 Hazard Rate and Default Probability 493 10.4.2 Risky Annuities and Risky Durations 501 10.4.3 CDS Present Values 501 10.4.4 CDS Prices 509 11 Trading Strategies and Backtesting 515 11.1 Trading Strategy Identification 515 11.2 Crossover Trading Signals 517 11.2.1 Trading Strategy Objects 518 11.2.2 Two-MA Crossover 519 11.2.3 Two-MA Crossover with NATR Filter 530 11.3 Z-Score Trading Signals 541 11.3.1 MA-Based Z-Scores 542 11.3.2 RSI-Based Z-Scores 547 11.3.3 PPO-Based Z-Score 549 11.4 Backtesting System 553 11.4.1 P&L Calculation 553 11.4.2 Risk Measure 556 11.4.3 Backtesting for MA Crossover Strategies 559 11.4.4 Backtesting for Z-Score Strategies 568 Index 573
Introduction
        Overview
        What This Book Includes
        Is This Book for You
        What Do You Need to Use This Book
        How This Book is Organized
        Using Code Examples
Overview
Welcome to “Quantitative Finance with C# .NET Blazor”. This book provides all the tools you need to develop modern financial web applications using .NET Blazor. I hope that this book will be useful for quant developers, quant analysts, individual traders, .NET programmers, web developers, and students of all skill levels.
In recent years, quantitative finance has become an attractive field due to the intellectual challenge and high remuneration. Many scientists, engineers, and students wish to change their careers to become quant developers or analysts in investment banks or hedge fund firms. Most of them have a solid background in mathematics, statistical analysis, physics modeling, and programming, but lack knowledge and experience in quantitative finance. A question that they constantly ask is “what do I need to prepare myself to become a quant developer/analyst?” This book will provide an answer to this question and prepare you with solid technical skills in quantitative analysis and development.
On the other hand, especially after the COVID-19 pandemic, more and more individuals want to become independent (“retail”) quantitative traders who are looking to start their own quantitative or algorithmic trading business. This path offers the flexibility of working from home and flexible working hours. The most common issue they face is “what kind of background do I need to be successful in quantitative trading?” Most of these individuals have advanced degrees in physics, math, engineering, or computer science. This kind of training in hard sciences gives them an edge in quantitative analysis and pricing complex derivative instruments. However, the ability to convert trading ideas into trading strategies and the programming skill needed to implement an automated trading system are equally important. This book will prepare you with all the necessary analysis and programming techniques to become a well-equipped individual quant trader.
So, what kinds of applications – desktop or web – are more suitable in quantitative finance? Financial applications development began with desktop applications, which are used on specific machines where the applications have been installed. Generally, writing code for desktop application is relatively easier, and you have much greater control over how your application works. Another benefit is that desktop applications are always offline because they are executable programs that do not need to be accessed over the internet. In my previously published book, “Practical C# and WPF for Financial Markets”, I provided a detailed explanation of how to build desktop applications in finance using C#, WPF, MVVM, and the .NET framework.
In contrast to desktop applications, a web-based application is software that can be accessed through the internet. The software and database reside on a central server rather than on a local desktop system. Web-based applications are the better way to take advantage of today’s technology to enhance the productivity and efficiency. Web or distributed applications are mostly used on client-server networks where the user’s computer accesses information from the server or a cloud computing server. There are some obvious advantages of web applications over desktop applications. Web applications need to be installed only once, which avoids the burden in deploying in each client machine and makes software updates and maintenance much easier. They are platform-independent, adaptable for mobile application, and can be accessed from anywhere in the world.
Visual Studio offers several templates to build web applications, including Angular and React SPA templates. However, Blazor applications are still a better choice in some scenarios. First, Blazor provides a unified development experience since it allows developers to use C# across the entire stack, both on the client-side and server-side. This reduces code duplication and simplifies development compared to Angular/React templates, where separate codebases for frontend and backend exist. It also eliminates the need to learn a front-end language like JavaScript for teams already familiar with C#, allowing developers to build full-stack applications using a single language, C#.
Additionally, Blazor enables developers to create highly interactive and visually appealing user interfaces, significantly enhancing user experience. It facilitates the development of applications that can run across different platforms, increasing the reach of your web apps. Blazor can seamlessly integrate into existing .NET projects, making the development process more efficient for those already working within this ecosystem. Blazor also provides server-side rendering, which offers a quicker initial page load experience for users and improves search engine visibility as search engines can easily index rendered content.
I wrote this book with the intention of providing a complete and comprehensive explanation of modern web application development in quantitative finance using the latest technology stack: .NET 8 Blazor. This book pays special attention to creating various business applications and reusable .NET libraries that can be directly used in real-world finance applications. Much of this book contains original work based on my programming experience developing business applications for quantitative analysis in the financial field.
“Quantitative Finance with C# .NET Blazor” provides everything you need to create your own advanced web applications in quantitative finance and reusable packages using .NET Blazor. It demonstrates how to use Blazor, the latest .NET technology, to build a variety of financial applications ranging from simple databases, market data APIs, and data visualization to quantitative analysis, pricing equity options, complex fixed-income instruments, machine learning, and trading strategy development. I will do my best to introduce you to modern web application development in quantitative finance in a straightforward manner – simple enough to be easily followed by a quant or .NET/web developer with basic prior experience in developing business applications using .NET technology.
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 .NET Blazor. After reading this book and running the example programs, you will be able to create various sophisticated business applications in quantitative finance using the .NET technology.
- 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 components in the sample code listings that you will find useful in your quant development. These classes and components 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 components 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 .NET/web developer to use this book. I designed it to be useful to people of all levels of .NET/web 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 Microsoft Visual Studio Community 2022, 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 .NET programmers, I believe this book has much to offer as well. A great deal of the information in this book about .NET/web 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 .NET Blazor.
Perhaps you are a scientist, engineer, mathematician, or student, rather than a professional quant developer/analyst, .NET programmer, or web developer; nevertheless, this book is still a valuable resource for you. My own background is in theoretical physics, a field that involves extensive physical modeling, numerical calculations, and graphical representations of data. I devoted many years to this field, from undergraduate studies through to my PhD.
My first computer experience was with FORTRAN, and later, I gained programming experience with Basic, C, C++, R, Python, JavaScript, and MATLAB. I always sought an ideal development tool that would allow me not only to generate data easily (computation capability) but also to represent data graphically (graphics and charting power). The .NET framework and Microsoft Visual Studio development environment made it possible to develop such integrated applications. Since the release of Microsoft .NET 1.0, I have been passionate about the C# language and have used it successfully to create powerful business applications for quantitative analysis.
Quant analysts/developers, individual quant traders, and .NET/web developers can routinely use the majority of the example programs in this book. Throughout, I emphasize the usefulness of web 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.
What Do You Need to Use This Book?
You do not need any special equipment to make the most of this book and understand the algorithms presented. This book leverages open-source frameworks and libraries. To run and modify the sample programs, you will need a computer capable of running either Windows 10 or 11. The server-side software installed on your computer should include Visual Studio 2022 (the Community version is fine) and the .NET 8 SDK or higher.
If you have the .NET 7 SDK or an older version, you may still run most of the sample code with a few modifications. However, please remember that this book is intended for .NET 8 Blazor applications, and all of the example programs were created and tested on this platform. Therefore, it is best to run the sample code on the same platform.
How This Book Is Organized
This book is structured into eleven chapters, each exploring a distinct topic related to quantitative finance applications using .NET Blazor. Below is a summary of each chapter to provide an overview of the book’s contents:
Chapter 1, Introduction to .NET Blazor
Introduction to .NET Blazor
This chapter covers the basics of .NET Blazor, including how to set up the tools, packages, and development environment required for building a Blazor web application using .NET Blazor with the Visual Studio IDE.
Chapter 2, Database and Entity Framework Core
This chapter introduces SQLite and Entity Framework Core, which is a built-in feature included with Visual Studio. It demonstrates how to create simple database and how to interact with the data in Blazor 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.Blazor 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 Blazor 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 the 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 long-short based backtesting framework, allowing you to examine 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.