Book Image

Mastering R for Quantitative Finance

Book Image

Mastering R for Quantitative Finance

Overview of this book

Table of Contents (20 chapters)
Mastering R for Quantitative Finance
About the Authors
About the Reviewers


Mastering R for Quantitative Finance is a sequel of our previous volume titled Introduction to R for Quantitative Finance, and it is intended for those willing to learn to use R's capabilities for building models in Quantitative Finance at a more advanced level. In this book, we will cover new topics in empirical finance (chapters 1-4), financial engineering (chapters 5-7), optimization of trading strategies (chapters 8-10), and bank management (chapters 11-13).

What this book covers

Chapter 1, Time Series Analysis (Tamás Vadász) discusses some important concepts such as cointegration (structural), vector autoregressive models, impulse-response functions, volatility modeling with asymmetric GARCH models, and news impact curves.

Chapter 2, Factor Models (Barbara Dömötör, Kata Váradi, Ferenc Illés) presents how a multifactor model can be built and implemented. With the help of a principal component analysis, five independent factors that explain asset returns are identified. For illustration, the Fama and French model is also reproduced on a real market dataset.

Chapter 3, Forecasting Volume (Balázs Árpád Szűcs, Ferenc Illés) covers an intraday volume forecasting model and its implementation in R using data from the DJIA index. The model uses turnover instead of volume, separates seasonal components (U shape) from dynamic components, and forecasts these two individually.

Chapter 4, Big Data – Advanced Analytics (Júlia Molnár, Ferenc Illés) applies R to access data from open sources, and performs various analyses on a large dataset. For illustration, K-means clustering and linear regression models are applied to big data.

Chapter 5, FX Derivatives (Péter Medvegyev, Ágnes Vidovics-Dancs, Ferenc Illés) generalizes the Black-Scholes model for derivative pricing. The Margrabe formula, which is an extension of the Black-Scholes model, is programmed to price stock options, currency options, exchange options, and quanto options.

Chapter 6, Interest Rate Derivatives and Models (Péter Medvegyev, Ágnes Vidovics-Dancs, Ferenc Illés) provides an overview of interest rate models and interest rate derivatives. The Black model is used to price caps and caplets; besides this, interest rate models such as the Vasicek and CIR model are also presented.

Chapter 7, Exotic Options (Balázs Márkus, Ferenc Illés) introduces exotic options, explains their linkage to plain vanilla options, and presents the estimation of their Greeks for any derivative pricing function. A particular exotic option, the Double-No-Touch (DNT) binary option, is examined in more details.

Chapter 8, Optimal Hedging (Barbara Dömötör, Kata Váradi, Ferenc Illés) analyzes some practical problems in hedging of derivatives that arise from discrete time rearranging of the portfolio and from transaction costs. In order to find the optimal hedging strategy, different numerical-optimization algorithms are used.

Chapter 9, Fundamental Analysis (Péter Juhász, Ferenc Illés) investigates how to build an investment strategy on fundamental bases. To pick the best yielding shares, on one hand, clusters of firms are created according to their past performance, and on the other hand, over-performers are separated with the help of decision trees. Based on these, stock-selection rules are defined and backtested.

Chapter 10, Technical Analysis, Neural networks, and Logoptimal Portfolios (Ágnes Tuza, Milán Badics, Edina Berlinger, Ferenc Illés) overviews technical analysis and some corresponding strategies, like neural networks and logoptimal portfolios. Problems of forecasting the price of a single asset (bitcoin), optimizing the timing of our trading, and the allocation of the portfolio (NYSE stocks) are also investigated in a dynamic setting.

Chapter 11, Asset and Liability Management (Dániel Havran, István Margitai) demonstrates how R can support the process of asset and liability management in a bank. The focus is on data generation, measuring and reporting on interest rate risks, liquidity risk management, and the modeling of the behavior of non-maturing deposits.

Chapter 12, Capital Adequacy (Gergely Gabler, Ferenc Illés) summarizes the principles of the Basel Accords, and in order to determinate the capital adequacy of a bank, calculates value-at-risk with the help of the historical, delta-normal, and Monte-Carlo simulation methods. Specific issues of credit and operational risk are also covered.

Chapter 13, Systemic Risk (Ádám Banai, Ferenc Illés) shows two methods that can help in identifying systemically important financial institutions based on network theory: a core-periphery model and a contagion model.

Gergely Daróczi has also contributed to most chapters by reviewing the program codes.

What you need for this book

All the codes examples provided in this book should be run in the R console that is to be installed first on your computer. You can download the software for free and find the installation instructions for all major operating systems at Although we will not cover advanced topics such as how to use R in Integrated Development Environment, there are awesome plugins for Emacs, Eclipse, vi, or Notepad++ besides other editors, and we also highly recommend that you try RStudio, which is a free and open source IDE dedicated to R.

Apart from a working R installation, we will also use some user-contributed R packages that can be easily installed from the Comprehensive A Archive Network. To install a package, use the install.packages command in the R console, shown as follows:

> install.packages('Quantmod')

After installation, the package should also be loaded first to the current R session before usage:

> library (Quantmod)

You can find free introductory articles and manuals on the R home page.

Who this book is for

This book is targeted to readers who are familiar with the basic financial concepts and who have some programming skills. However, even if you know the basics of Quantitative Finance, or you already have some programming experience in R, this book provides you with new revelations. In case you are already an expert in one of the topics, this book will get you up and running quickly in the other. However, if you wish to take up the rhythm of the chapters perfectly, you need to be on an intermediate level in Quantitative Finance, and you also need to have a reasonable knowledge in R. Both of these skills can be attained from the first volume of the sequel: Introduction to R for Quantitative Finance.


In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Any command-line input or output is written as follows:

#generate the two time series of length 1000
set.seed(20140623)         #fix the random seed
N <- 1000                  #define length of simulation
x <- cumsum(rnorm(N))      #simulate a normal random walk
gamma <- 0.7               #set an initial parameter value
y <- gamma * x + rnorm(N)  #simulate the cointegrating series
plot(x, type='l')          #plot the two series

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Another useful visualization exercise is to look at the Density on log-scale."


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.


If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.