Practical C# and WPF For Financial Markets

83 downloads 0 Views 880KB Size Report
Advanced C#, WPF, and MVVM Programming for Quant Developers/Analysts and Individual Traders ...... MACD and RSI Indicators . ... Stochastic Indicator . ..... However, the capability to convert trading ideas into trading strategies and the ...
Practical C# and WPF For Financial Markets Advanced C#, WPF, and MVVM Programming for Quant Developers/Analysts and Individual Traders

Practical C# and WPF For Financial Markets Advanced C#, WPF, and MVVM Programming for Quant Developers/Analysts and Individual Traders

Jack Xu, PhD

UniCAD Publishing

Practical C# and WPF for Financial Markets Copyright © 2016 by Jack Xu, PhD Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1UC Editor: Tyler Xu All rights reserved. No part of the contents of this book and corresponding example source code may be reproduced or transmitted in any form or by any means without the written permission of the author. The author has made every effort in the preparation of this book to ensure the accuracy of the information; however, this book is sold without warranty, either express or implied. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained in the book.

Published by UniCAD Publishing. New York, USA ISBN-13: 978-0-9793725-5-1 ISBN-10: 0-9793725-5-0 Publisher’s Cataloging-in-Publication Data Xu, Jack Practical C# and WPF for Financial Markets – Advanced C#, WPF, and MVVM Programming for Quant Developers/Analysts and Individual Traders/ Jack Xu – 1st ed. p.cm. ISBN 978-0-9793725-5-1 1. C# Programming. 2. Finance. 3. Quant. 4. Windows Presentation Foundation. 5. Quant Developer. 6. MVVM 7. Quant Analyst. 8. Stock Trading. 9. Option Trading. 10. SQL Database. 11. Pricing Engines. I. Title. II. Title. III Title: Practical C# and WPF Programming for Financial Markets

For my wonderful family

Contents Introduction .......................................................................................... xiii Overview ........................................................................................................ xiii What this Book Includes ................................................................................ xiv Is This Book for You? .................................................................................... xv What Do You Need to Use This Book? .......................................................... xv How the Book Is Organized........................................................................... xvi Structure of Sample Projects......................................................................... xvii Using Code Examples .................................................................................. xviii Customer Support ........................................................................................ xviii

Chapter 1 Overview of C# and WPF Programming ............................ 1 New Features in WPF ....................................................................................... 1 XAML basics .................................................................................................... 2 Why Is XAML Needed? ......................................................................... 2 Creating XAML Files ............................................................................. 3 Code-Behind Files ................................................................................... 3 Your First WPF Program .................................................................................. 4 Properties in XAML ................................................................................ 4 Event Handlers in Code-Behind Files ..................................................... 6 Code-Only Example ................................................................................ 7 XAML-Only Example ............................................................................ 9

Chapter 2 Introduction to MVVM ....................................................... 11 Open-Source MVVM Tool Kits ..................................................................... 12 Caliburn.Micro ................................................................................................ 13 Bootstrapper Class ................................................................................ 13 Modify App.xaml File ........................................................................... 15 Why Fields Not Updated ................................................................................ 15 Right Way for Data Binding ........................................................................... 19 Using Dependency Properties ......................................................................... 22 Using Naming Convention ............................................................................. 25

viii | Contents

Using Collection ............................................................................................. 28 Communication between View Models .......................................................... 32

Chapter 3 Database ................................................................................ 43 Local Database ................................................................................................ 44 Sample Database ................................................................................... 46 SQL Queries .......................................................................................... 47 GROUP BY Clause ..................................................................... 47 Pivot Operation ............................................................................ 49 Aggregate Functions .................................................................... 53 Database Development .......................................................................... 54 ADO.NET Entity Framework ......................................................................... 59 Creating Entity Data Model .................................................................. 60 Working with Entity Data ..................................................................... 63

Chapter 4 Market Data ......................................................................... 71 Market Data from Yahoo ................................................................................ 71 EOD Stock Data .................................................................................... 71 Stock Quotes ......................................................................................... 73 Download Market Data from Yahoo..................................................... 79 Store Market Data ........................................................................................... 82 Add Tickers to Database ....................................................................... 83 Add Stock Data to Database ................................................................. 89 Market Data from Google ............................................................................... 96 EOD and Minute-Bar Data for Stocks .................................................. 97 Real-Time Stock Quotes ..................................................................... 102 Download Market Data from Google ................................................. 107 Option Chain Data............................................................................... 111 Market Data from Quandl ............................................................................. 117 Quandl API.......................................................................................... 118 Adjusted Stock EOD Data .................................................................. 119 Other Market Data ............................................................................... 122 ISDA Rates from Markit............................................................................... 124 ISDA Interest Rate API ....................................................................... 125 Download Interest Rates ..................................................................... 129 Market Data from Bloomberg....................................................................... 131 Bloomberg API ................................................................................... 132 Download Market Data from Bloomberg ........................................... 138

Chapter 5 Data Visualization .............................................................. 143

Contents | ix

2D Chart Control .......................................................................................... 144 Simple Line Charts .............................................................................. 144 Line Chart with Multiple Lines ........................................................... 146 Line Charts with Two Y Axes ............................................................. 148 Stock Charts ........................................................................................ 152 3D Chart Control .......................................................................................... 158 3D Line Charts .................................................................................... 158 3D Surface-Like Charts....................................................................... 160 3D Specialized Charts ......................................................................... 167 MS Chart Control.......................................................................................... 178 WPF Compatible MS Chart Control ................................................... 178 Helper Class ........................................................................................ 185 Simple MS Charts ............................................................................... 189 Stock Charts ........................................................................................ 193 Real-Time Stock Charts ...................................................................... 201

Chapter 6 Linear Analysis .................................................................. 207 Simple Linear Regression ............................................................................. 207 Implementation ................................................................................... 208 R-Squared ............................................................................................ 209 What are Alpha and Beta?................................................................... 211 Simple Regression Applications ......................................................... 211 Simple 2D PCA ............................................................................................ 218 Implementation ................................................................................... 219 Simple PCA applications .................................................................... 221 Comparing Linear Regression and PCA ....................................................... 224 Multiple Linear Regressions ......................................................................... 230 Helper Class ........................................................................................ 231 Multiple Regression Applications ....................................................... 233 Multiple PCA ................................................................................................ 239 Implementation ................................................................................... 239 Multiple PCA Applications ................................................................. 241

Chapter 7 Technical Indicators .......................................................... 249 Indicators in MsChart Control ...................................................................... 249 Helper Class .................................................................................................. 252 Indicator Chart with Two Chart Areas ................................................ 252 Indicator Chart with Three Chart Areas .............................................. 256 Technical Indicator Applications .................................................................. 261 Understand Technical Indicators .................................................................. 269

x | Contents

Moving Average Based Indicators ...................................................... 269 Envelope and Bollinger Band Indicators ............................................ 273 MACD and RSI Indicators .................................................................. 273 On Balance Volume Indicator ............................................................. 275 Accumulation/Distribution Indicator .................................................. 278 Williams %R Indicator ........................................................................ 278 Stochastic Indicator ............................................................................. 279 Commodity Channel Index Indicator .................................................. 281

Chapter 8 Machine Learning .............................................................. 285 K-Nearest Neighbors (KNN) Classifier ........................................................ 285 KNN Model for Stock Data ................................................................ 286 KNN Model Applications ................................................................... 287 Confusion Matrix ................................................................................ 298 Support Vector Machine ............................................................................... 301 SVM for Classification ....................................................................... 302 SVM for Regression ............................................................................ 310 Artificial Neural Networks ........................................................................... 312 Introduction to Neural Networks ........................................................ 313 Neural Networks for Classification ..................................................... 314 Neural Network for Regression .......................................................... 329 Simple Example ......................................................................... 330 Stock Price Prediction ............................................................... 342 Save and Reuse Network ........................................................... 357

Chapter 9 Options Pricing .................................................................. 361 Introduction to Options ................................................................................. 361 Option Payoffs .................................................................................... 362 Option Value ....................................................................................... 362 Pricing European Options ............................................................................. 363 Black-Scholes Model .......................................................................... 363 Generalized Black-Scholes Model ...................................................... 364 Implementation ................................................................................... 365 Black-Scholes Greeks ......................................................................... 373 Delta........................................................................................... 373 Gamma....................................................................................... 376 Theta .......................................................................................... 377 Rho............................................................................................. 380 Vega ........................................................................................... 383 Implied Volatility ................................................................................ 384

Contents | xi

Pricing American Options ............................................................................ 391 BAW Approximation .......................................................................... 391 Implementation ................................................................................... 392 Applying BAW Approximation .......................................................... 395 Pricing Barrier Options ................................................................................. 399 Standard Barrier Option Formulas ...................................................... 400 Implementation ................................................................................... 402 Barrier Option Applications ................................................................ 408 Pricing European Options Using QuantLib .................................................. 412 Dates, Calendars, and Day Counters in QuantLib .............................. 412 Term Structures in QuantLib .............................................................. 414 Helper Class ........................................................................................ 414 Using Pricing Engines ......................................................................... 419 Pricing American Options Using QuantLib.................................................. 424 Helper Class ........................................................................................ 424 Using Pricing Engines ......................................................................... 427 Pricing Exotic Options using QuantLib ........................................................ 431 Barrier Options .................................................................................... 432 Bermudan Options .............................................................................. 438 Pricing American Options in Real-World .................................................... 443 Term Structure for Interest Rates ........................................................ 444 Dividend Yield Curve ......................................................................... 445 Volatility Smile ................................................................................... 446 American Options Pricing ................................................................... 447

Chapter 10 Pricing Fixed-Income Instruments ................................ 453 Simple Bonds Pricing ................................................................................... 453 Discounting Factors ............................................................................ 454 Pricing Bonds with Flat Rates ............................................................. 455 Compounding Frequency Conventions ............................................... 461 Pricing Bonds with a Simple Rate Curve ............................................ 463 Yield to Maturity ................................................................................. 465 Zero-Coupon Yield Curve ............................................................................ 466 Treasury Zero-Coupon Yield Curve ................................................... 467 Interbank Zero-Coupon Yield Curve .................................................. 476 Credit Spread Term Structures ............................................................ 480 Bonds with Embedded Options .................................................................... 484 Callable Bonds .................................................................................... 485 Convertible Bonds ............................................................................... 492 CDS Pricing .................................................................................................. 496

xii | Contents

Hazard Rate and Default Probability .................................................. 497 Risky Annuities and Risky Durations ................................................. 505 CDS Pricing Engine ............................................................................ 506

Chapter 11 Trading Strategies and Backtesting ............................... 517 Trading Strategy Identification ..................................................................... 517 Trading Signals ............................................................................................. 519 Stock Data ........................................................................................... 520 Signals from Moving Average ............................................................ 522 Signals from Linear Regression .......................................................... 524 Signals from RSI ................................................................................. 525 Signals from Williams %R.................................................................. 527 Backtesting System Implementation ............................................................ 529 P&L Computation ............................................................................... 529 Risk Measures ..................................................................................... 533 Backtesting System Applications ................................................................. 536 Backtesting for US Stocks .................................................................. 536 Optimization ........................................................................................ 549 Pairs Trading ................................................................................................. 562 Pairs Identification .............................................................................. 562 Signals for Pairs Trading ..................................................................... 564 Market Neutral .................................................................................... 566 P&L for Pairs Trading ......................................................................... 567 Backtesting for Pairs Trading ....................................................................... 568 Backtesting for Stock Pairs ................................................................. 568 Optimization ........................................................................................ 580

Index ...................................................................................................... 593

Introduction

Overview Welcome to Practical C# and WPF for Financial Markets. This book will provide all the tools you need to develop professional financial applications using the C#, the Windows Presentation Foundation (WPF), and the Model-View-View Model (MVVM) pattern based on the .NET Framework. I hope that this book will be useful for quant developers, quant analysts, individual traders, .NET programmers, and students of all skill levels. In recent years, quantitative finance has been an attractive field due to the intellectual challenge and high remuneration. Many scientists, engineers, and students wish to change their careers to become a quant developer/analyst in investment banks or hedge fund firms. Most of them have 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 and analyst?” This book will provide answer to this question and prepare you with solid technical skills in quantitative analysis and development. On the other hand, more and more individuals want to become independent (“retail”) quantitative traders who are looking to start their own quantitative or algorithmic trading business. The most common issue they are facing is what kind of background do they need in order to be success in quantitative trading? Most of those individuals received their advanced degrees in physics, math, engineering, or computer science. This kind of training in hard sciences will give them an edge in quantitative analysis and pricing complex derivative instruments. However, the capability to convert trading ideas into trading strategies and the programming skill in implementing the automatic trading system are equally important. This book will prepare you with all the necessary analysis and programming techniques to become a wellequipped individual quant trader. So what programming languages are most commonly used in quantitative finance? No doubt about it, C++ is traditionally associated with finance applications for pricing complex derivative securities, and much of the older financial infrastructure is also based on C++. C# and .NET Framework are a relatively new technology comparing to C++. This book will choose C# and WPF as our programming framework in developing various business applications in financial markets. The reason for using C# in this book is that C# is relatively easy to learn comparing to C++. Scientists, engineers, students, quants, and traders can learn C# and use it to develop financial applications quickly.

xiv | Introduction People with a background in VBA, R, Python, Matlab, or Java will find the transition to C# much easier than the transition to C++. Furthermore, in many cases developers’ productivity levels are much higher than those achieved with C++. It is also possible to create interoperable .NET applications that contains different technologies such as C++ and VBA legacy code. The two key features in WPF, data binding and MVVM pattern, can further enhance developers’ productivity. The data binding provides a simple and consistent way for .NET applications to present and interact with data. It has several advantages over traditional models, including a broad range of properties that inherently support data binding, flexible UI (user interface) representation of data, and clean separation of business logic from UI. The MVVM pattern is the most used architecture for WPF applications. MVVM introduces three layers of separation of application code, namely, Model, View, and ViewModel. View holds the actual UI; ViewModel holds the collection of properties, commands, and property changed notifications; while Model holds business data, business logic, and business rule. You will gain several advantages of using MVVM pattern, including 1) proper separation of the view and the data. The data is not stored in view and the view is just for presenting the data; 2) clean testable and manageable code; and 3) no code-behind so the presentation layer and the logic are loosely coupled. I write this book with the intention of providing a complete and comprehensive explanation of C# and WPF programming in quantitative finance. This book pays special attention to creating various business applications and reusable .NET libraries that can be used directly in real-world finance applications. Much of this book contains the original work based on my own programming experience when I was developing business applications for quantitative analysis in financial field. Practical C# and WPF for Financial Markets provides everything you need to create your own advanced applications in quantitative finance and reusable packages using C# and WPF based on MVVM pattern. It shows you how to use C# and WPF to create a variety of financial applications that range from simple database, market data API, data visualization, quantitative analysis to pricing equity options and complex fixed income instruments, machine learning, and trading strategy development. I will try my best to introduce you to C# and WPF programming in quantitative finance in a simple way – simple enough to be easily followed by a quant or .NET developer who has 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 www.drxudotnet.com, provide you with: 

A complete, in-depth instruction to practical quantitative finance programming with C#, WPF, and MVVM. 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 in the sample code listings that you will find useful in your quant development. These classes include charting libraries, various quantitative analysis models, pricing engines for options and fixed income instruments, machine learning for trading strategy development and back-testing,

Introduction | xv and the other useful utility classes. You can extract these classes and plug them into your own business applications.

Is This Book for You? You do not have to be an experienced quant developer/analyst or .NET developer to use this book. I designed this book to be useful to people of all levels of .NET programming experience and financial background. In fact, I believe that if you have some prior experience with quantitative analysis/ development and programming language C++, Java, R, Python, VBA, C#, or Windows Forms, you will be able to sit down in front of your computer, start up Microsoft Visual Studio Community 2013, follow the examples provided in this book, and quickly become proficient with quantitative application development. For those of you who are already experienced quant analyst/developer or .NET programmers, I believe this book has much to offer as well. A great deal of the information in this book about .NET programming in quantitative finance is not available in other tutorial and reference books. In addition, 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 program code that will enable you to do just about anything related to quantitative finance application development using C# and WPF. Perhaps you are a scientist, an engineer, a mathematician, or a student, rather than a professional quant developer/analyst or .NET programmer; nevertheless, this book is still a good bet for you. In fact, my own background is in theoretical physics, a field involving extensive physical modeling, numerical calculations, and graphical representations of calculated data. I devoted my effort to this field for many years, starting from undergraduate up to PhD. My first computer experience was with Fortran. Later on, I had programming experience with Basic, C, C++, R, Python, and Matlab. I always tried to find an ideal development tool that would allow me not only to generate data easily (computation capability) but also to represent data graphically (graphics and chart power). The C# and Microsoft Visual Studio .NET development environment made it possible to develop such integrated applications. Ever since Microsoft .NET 1.0 came out, I have been in love with the C# language, and able to use this tool successfully to create powerful business applications for quantitative analysis. Quant analysts/developers, individual quant traders, and .NET developers can use the majority of the example programs in this book routinely. Throughout the book, I emphasize the usefulness of .NET programming to real-world quantitative finance applications. If you follow the instructions presented in this book closely, you will easily be able to develop various practical business applications in quantitative finance, from linear analysis, machine learning to pricing engines, and trading strategy development. At the same time, I will not spend too much time discussing the programming style, execution speed, and code optimization, because a plethora of books out there already deals with these topics. Most of the example programs you will find in this book omit error handlings, which makes the code easier to understand by focusing only on the key concepts and practical applications.

What Do You Need to Use This Book? You will need no special equipment to make the best use of this book and understand the algorithms. To run and modify the sample programs, you will need a computer capable of running either Windows 7, 8, or 10. The software installed on your computer should include Visual Studio 2013 (Community version is fine), the .NET 4.5 standard edition or higher, and SQL Server Express 2012 or higher. If you have Visual Studio 2012, .NET 4.0, and SQL Server Express 2008 or older versions, you can also run

xvi | Introduction most of the sample code with few modifications. Please remember, however, that this book is intended for Visual Studio 2013, .NET 4.5, and SQL Server Express 2014, and that all of the example programs were created and tested on this platform, so it is best to run the sample code on the same platform.

How the Book Is Organized This book is organized into eleven chapters, each of which covers a different topic about quantitative finance applications using C# and WPF. The following summaries of each chapter should give you an overview of the book’s content: Chapter 1, Overview of C# and WPF Programming This chapter introduces the basics of WPF and reviews some of the general aspects of WPF programming, including XAML files used to define user interfaces. Chapter 2, Introduction to MVVM This chapter introduces processes for implementing the MVVM pattern in WPF applications; including data binding with the property-changed notifications, command binding, and observable collections. It also reviews some free open-source MVVM tool kits, and shows why we use Caliburn.Micro in this book. Chapter 3, Database This chapter introduces the SQL Server Data Tool (SSDT) and LocalDB, which are built-in features and shipped as part of the core product of Visual Studio 2013. It shows you how to create simple database and how to interact with the data. It also reviews ADO.NET Entity Framework that allows developers without extensive knowledge about SQL to interrogate the database, create complex queries, and generate classes with the help of a user-friendly interface. Chapter 4, Market Data This chapter contains the step-by-step procedures on how to interact with market data providers’ API and retrieve the free market data from online data source. These market data include the end of the day (EOD) stock data, intraday data, interest rate data, foreign exchange rate data, and option chain data. It also discusses how to use the Bloomberg terminal’s API to interact with market data. Chapter 5, Data Visualization Data visualization plays a critical role in quantitative finance and trading. Quant analysts and traders need to monitor the real-time changes in market and trading signals visually on their screen. In this chapter, I will show you how to use a chart control library I created to display the market data. I will also discuss how to convert the Windows Forms version of the MSChart control into a WPF and MVVM compatible user control and how to use this control in developing quantitative finance applications. Chapter 6, Linear Analysis This chapter presents the most fundamental analysis approach in quantitative finance based on linear analysis. I will discuss how to develop different business applications using the linear regression, principal component analysis (PCA), and correlation. Chapter 7, Technical Indicators This chapter discusses various technical indicators, which are often used in quantitative analysis. A technical indicator is just a mathematical calculation based on historic market data, which is used to

Introduction | xvii predict market direction. I will show you how to use the FinancialFormula object in the MSChart control to display different indicators on your screen and how to extract the output results from the indicators. Chapter 8, Machine Learning This chapter discusses the advanced quantitative analysis techniques: machine learning. Machinelearning technique has become one of the most promising fields in quantitative finance. It is widely used in quantitative finance for predicting the future stock prices. This chapter will concentrate on the supervised learning and covers several commonly used machine-learning algorithms in finance, including the K-nearest neighbors, support vector machines, and neural networks. Chapter 9, Options Pricing This chapter covers the Black-Scholes formula used for options pricing. It shows several different implementations for calculating the price and Greeks of the European and American options. It also discusses how to use the open source quant libraries, such as QuantLib, to price various options, including barrier options, Bermudan options, and other exotic options. Chapter 10, Pricing Fixed-Income Instruments This chapter demonstrates how to price the fixed-income instruments, including interest rates, bonds, and credit default swaps. It also discusses various related topics, such as cash flows, term structures, yield curves, discount factors, and zero-coupon bonds. I will provide the detailed procedures on how to use the open-source QuantLib library to price these complex financial instruments. Chapter 11, Trading Strategies and Backtesting This chapter presents several trading strategies using the simple quantitative analysis techniques, including the moving average and linear regression, as well as the commonly used technical indicators. I will also present a long-short based backtesting framework, which allows you to examine the historical performance of your trading strategies for single stock trading and stock pairs trading.

Structure of Sample Projects In this book, I will use example code projects to illustrate the detailed implementations for various business applications in quantitative finance. The following figure show how the sample projects are structured. From the left panel, you can see that this book contains eleven chapters. You can click the chapter button to access the sample projects in the corresponding chapter. Here, I have clicked the “Chapter 1” button and its background (black) and foreground (white) change colors, indicating the Chapter 1 is selected. At the same time, the TabControl on the right panel will show all of the available sample projects in Chapter 1 accordingly. You can then access the different projects in Chapter 1 by clicking different tabs. This way, you can access whatever sample project you like.

xviii | Introduction

Using Code Examples You may use the code in this book in your own applications and documentation. You do not need to contact the author for permission unless you are reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing the example code listings does require permission. Incorporating a significant amount of example code from this book into your applications and documentation also requires permission. Integrating the example code from this book into commercial products is not allowed without written permission of the author.

Customer Support I am always interested in hearing from readers, and enjoy learning of your thoughts on this book. You can send me comments by e-mail to [email protected]. I also provide updates, bug fixes, and ongoing support via my website: www.DrXuDotNet.com

You can also obtain the complete source code for all of examples in this book from the foregoing website.