Professional Documents
Culture Documents
net/publication/325807494
CITATIONS READS
0 2,139
1 author:
Ji-Hai Xu
drxudotnet.com
42 PUBLICATIONS 635 CITATIONS
SEE PROFILE
Some of the authors of this publication are also working on these related projects:
Gincker.com - a new platform for graphics creation and technical analysis in finance View project
All content following this page was uploaded by Ji-Hai Xu on 17 June 2018.
UniCAD Publishing
Practical Quantitative Finance with R
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, stored in a retrieval system, or transmitted in any form or by any means without the prior 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.
Contact:
jxu@dxudotnet.com
Visit us on the website: www.drxudotnet.com
Xu, Jack
Practical Quantitative Finance with R – Solving Real-World Problems with R for Quant Analysts and Individual
Traders/ Jack Xu
– 1st ed.
p.cm.
ISBN 978-0-9793725-7-5
1. R Programming. 2. Finance. 3. Quant. 4. Time Series. 5. Quant Developer. 6. Quant Analyst. 7. Stock
Trading. 8. Algorithmic Trading. 9. Data Analysis. 10. Pricing Engines. 11. Portfolio Optimization
I. Title. II. Title. III Title: Practical Quantitative Finance with R
For my wonderful family
Contents
Introduction ............................................................................................ xv
Overview ......................................................................................................... xv
What this Book Includes ............................................................................... xvii
Is This Book for You? .................................................................................. xvii
What Do You Need to Use This Book? ....................................................... xviii
How the Book Is Organized......................................................................... xviii
Using Code Examples ..................................................................................... xx
Customer Support ........................................................................................... xx
3D Surface-Like Charts......................................................................... 88
Specialized 3D Plots ............................................................................. 91
X-Y Color Plots ........................................................................... 91
Contour Plots ............................................................................... 92
Combination Plots ....................................................................... 92
3D Parametric Surfaces ......................................................................... 93
Helicoid Surface .......................................................................... 94
Sphere Surface ............................................................................. 95
Torus Surface ............................................................................... 95
Quadric Surfaces.......................................................................... 96
Interactive 3D Plots ........................................................................................ 98
Using plot3Drgl ..................................................................................... 99
Using rgl .............................................................................................. 101
Scatter Plots ............................................................................... 102
Custom Colormap ...................................................................... 103
Surface Plots .............................................................................. 106
Overview
Welcome to Practical Quantitative Finance with R. R is not only a general-purpose statistical computing
language, but also an excellent choice for fast prototyping quant models and backtesting trading
strategies in quantitative finance. This book focuses on introducing R as the scripting environment
choice for quantitative finance application development. It will provide the basic R programming,
quantitative analysis, and mathematical tools you need to develop real-world financial applications. All
the techniques described in this book can be directly used to solve those problems that many quants face
every day. I hope this book will be useful for quant developers/analysts, individual traders, 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 and 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 or analyst?” This book will provide answer to this question and
prepare you for careers 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 successful in quantitative trading?
Most of those individuals received their advanced degrees in physics, mathematics, 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 quickly 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 well-equipped 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++. In general, C++, C#, and Java tend to be
used for application and infrastructure development. In my previous book, Practical C# and WPF for
xvi | Introduction
Financial Markets, I have chosen C# and WPF as the programming framework in developing various
business applications in financial markets. The reason for using C# in that book is that C# is relatively
easy to learn in comparison to C++. You can learn C# and use it to develop financial applications quickly.
People with a background in VBA, R, 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 contain different technologies
such as C++, VBA, Matlab, and R legacy code.
In addition to create business applications and infrastructure, we also need a script-programming
environment that allows for rapid prototyping of an idea, provides us instant feedback, and enables the
data and result visualization in an efficient manner. In this regard, R, Python, and Matlab provide the
scripting environment and can be used to prototype quant models. All of these three are high-level
languages with capabilities such as time series analysis, linear/matrix/vectorization computation, and
fast prototyping for trading strategies. They all have strong communities developing code for numerical
analysis and quantitative finance. R is especially strong in the finance community. In my work as a quant,
I have used all of these three script languages extensively for prototyping quant models and strategy
backtesting. You can use any one of them as long as you are comfortable with it. In this book, I will
choose R as our scripting environment, mainly because R is a free open-source language, and has strong
packages in quantitative finance, as well as efficient data visualization power.
The main advantage of R is that it is free, extremely flexible and extensible. R is not only free, but also
open source. You can see the source code, and change it as per your own requirements. People across
different disciplines around world reviewed the core of the R system and contributed to make it better.
You can use R to perform data processing and analysis and to produce a variety of graphics. R has a
substantial collection of packages, which are written by experts in quantitative finance. That is why,
whether you are a quant analyst/developer, or individual trader, you should find a set of functions that
serve your purpose. The graphic system in R is one of the most powerful tools in this era, and you have
full control over every part of graphics produced in R. R is now becoming one of the platforms to
implement and prototype the research work, quant models, and trading strategies. You should be able to
find an R package suitable for the most recent developments in quantitative finance.
I write this book with the intention of providing a complete and comprehensive explanation of R
programming and usage of the relevant R packages in quantitative finance. The book pays special
attention to creating various business applications and reusable R libraries that can be directly used in
real-world finance applications. Much of this book contains original work based on my own
programming experience when I was prototyping quant models, pricing framework, and trading
strategies in quantitative financial field.
Practical Quantitative Finance with R provides everything you need to create your own advanced
applications and reusable packages in quantitative finance using R. It shows you how to use R and
relevant R packages to create a variety of financial applications that range from simple market data
collection, data visualization, and quantitative analysis to pricing equity options and complex fixed
income instruments, machine learning, trading strategy development, and portfolio optimization. I will
try my best to introduce you to R programming in quantitative finance in a simple way – simple enough
to be easily followed by a quant or individual trader who has basic prior experience in developing
business applications using R.
Introduction | xvii
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, trading strategy development, asset allocation, and
portfolio optimization. At the same time, I will not spend too much time discussing programming style,
execution speed, and code vectorization/optimization, because a plethora of books and tutorial
information out there already deal with these topics. Most of the example programs you will find in this
book omit error handlings. This makes the code easier to understand by focusing only on the key
concepts and practical applications.
direction. It demonstrates how to use the common indicators from the TTR package and extract the output
results from the indicators.
Chapter 5, 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
demonstrates how to use the open source quant libraries to price various exotic options, including barrier
options.
Chapter 6, Pricing Fixed-Income Instruments
This chapter discusses pricing for the fixed-income instruments, including interest rates, bonds, and
credit default swaps, as well as various related topics, such as cash flows, term structures, yield curves,
discount factors, and zero-coupon bonds. It also presents the detailed procedures on how to use QuantLib
to price these complex financial instruments.
Chapter 7, Linear Analysis
This chapter represents the most fundamental analysis approach in quantitative finance based on linear
analysis. It demonstrates how to develop different business applications using the linear regression,
principal component analysis (PCA), and correlation.
Chapter 8, Time Series Analysis
This chapter introduces some common modeling techniques for time series analysis, including the
autoregressive moving average (ARMA), the autoregressive integrated moving average (ARIMA), and
the volatility modeling generalized autoregressive conditional heteroscedasticity (GARCH). It also
examines the stationarity of a time series using different approaches, such as augmented Dickey-Fuller
(ADF) unit root test and Johansen test.
Chapter 9, Machine Learning
This chapter discusses the advanced quantitative analysis techniques: machine learning. Machine-
learning 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 concentrates on the supervised
learning and covers several commonly used machine-learning algorithms in finance, including the K-
nearest neighbors, random forest, support vector machines, and neural networks.
Chapter 10, 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.
It also discusses a long-short based backtesting framework and a useful backtesting package named
quantstrat, which allow us to examine the historical performance of trading strategies for single stock
trading, stock pairs trading, and trading for multi-asset portfolios.
Chapter 11, Portfolio Optimization
This chapter presents introduction to portfolio optimization. Expected return and risk are the most
important parameters with regard to optimal portfolios. The goal of portfolio optimization is to find the
best asset allocation strategy that maximizes portfolio’s return and minimizes its risk. This chapter
discusses portfolio optimization using several different techniques, including, Markowitz’s classical
mean-variance method, mean-CVaR (conditional risk at risk), and the portfolioAnalytics package.
xx | Introduction
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 jxu@DrXuDotNet.com. 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.