Introduction to R for Quantitative Finance - Gergely Daróczi - E-Book

Introduction to R for Quantitative Finance E-Book

Gergely Daróczi

0,0
31,19 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Introduction to R for Quantitative Finance will show you how to solve real-world quantitative fi nance problems using the statistical computing language R. The book covers diverse topics ranging from time series analysis to fi nancial networks. Each chapter briefl y presents the theory behind specific concepts and deals with solving a diverse range of problems using R with the help of practical examples.This book will be your guide on how to use and master R in order to solve quantitative finance problems. This book covers the essentials of quantitative finance, taking you through a number of clear and practical examples in R that will not only help you to understand the theory, but how to effectively deal with your own real-life problems.Starting with time series analysis, you will also learn how to optimize portfolios and how asset pricing models work. The book then covers fixed income securities and derivatives such as credit risk management.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 179

Veröffentlichungsjahr: 2013

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Introduction to R for Quantitative Finance
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Time Series Analysis
Working with time series data
Linear time series modeling and forecasting
Modeling and forecasting UK house prices
Model identification and estimation
Model diagnostic checking
Forecasting
Cointegration
Cross hedging jet fuel
Modeling volatility
Volatility forecasting for risk management
Testing for ARCH effects
GARCH model specification
GARCH model estimation
Backtesting the risk model
Forecasting
Summary
2. Portfolio Optimization
Mean-Variance model
Solution concepts
Theorem (Lagrange)
Working with real data
Tangency portfolio and Capital Market Line
Noise in the covariance matrix
When variance is not enough
Summary
3. Asset Pricing Models
Capital Asset Pricing Model
Arbitrage Pricing Theory
Beta estimation
Data selection
Simple beta estimation
Beta estimation from linear regression
Model testing
Data collection
Modeling the SCL
Testing the explanatory power of the individual variance
Summary
4. Fixed Income Securities
Measuring market risk of fixed income securities
Example – implementation in R
Immunization of fixed income portfolios
Net worth immunization
Target date immunization
Dedication
Pricing a convertible bond
Summary
5. Estimating the Term Structure of Interest Rates
The term structure of interest rates and related functions
The estimation problem
Estimation of the term structure by linear regression
Cubic spline regression
Applied R functions
Summary
6. Derivatives Pricing
The Black-Scholes model
The Cox-Ross-Rubinstein model
Connection between the two models
Greeks
Implied volatility
Summary
7. Credit Risk Management
Credit default models
Structural models
Intensity models
Correlated defaults – the portfolio approach
Migration matrices
Getting started with credit scoring in R
Summary
8. Extreme Value Theory
Theoretical overview
Application – modeling insurance claims
Exploratory data analysis
Tail behavior of claims
Determining the threshold
Fitting a GPD distribution to the tails
Quantile estimation using the fitted GPD model
Calculation of expected loss using the fitted GPD model
Summary
9. Financial Networks
Representation, simulation, and visualization of financial networks
Analysis of networks’ structure and detection of topology changes
Contribution to systemic risk – identification of SIFIs
Summary
A. References
Time series analysis
Portfolio optimization
Asset pricing
Fixed income securities
Estimating the term structure of interest rates
Derivatives Pricing
Credit risk management
Extreme value theory
Financial networks
Index

Introduction to R for Quantitative Finance

Introduction to R for Quantitative Finance

Copyright © 2013 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: November 2013

Production Reference: 1151113

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK..

ISBN 978-1-78328-093-3

www.packtpub.com

Cover Image by Suresh Mogre (<[email protected]>)

Credits

Authors

Gergely Daróczi

Michael Puhle

Edina Berlinger

Péter Csóka

Dániel Havran

Márton Michaletzky

Zsolt Tulassay

Kata Váradi

Agnes Vidovics-Dancs

Reviewers

Dr. Hari Shanker Gupta

Ronald Hochreiter

Acquisition Editor

Akram Hussain

Lead Technical Editor

Mohammed Fahad

Technical Editors

Venu Manthena

Adrian Raposo

Amit Singh

Copy Editors

Alisha Aranha

Tanvi Gaitonde

Sayanee Mukherjee

Aditya Nair

Kirti Pai

Shambhavi Pai

Lavina Pereira

Project Coordinator

Sherin Padayatty

Proofreader

Lucy Rowland

Indexer

Priya Subramani

Graphics

Ronak Dhruv

Abinash Sahu

Production Coordinator

Kirtee Shingan

Cover Work

Kirtee Shingan

About the Authors

Gergely Daróczi is a Ph.D. candidate in Sociology with around eight years' experience in data management and analysis tasks within the R programming environment. Besides teaching Statistics at different Hungarian universities and doing data analysis jobs for several years, Gergely has founded and coordinated a UK-based online reporting startup company recently. This latter software or platform as a service which is called rapporter.net will potentially provide an intuitive frontend and an interface to all the methods and techniques covered in the book. His role in the book was to provide R implementation of the QF problems and methods.

I am more than grateful to the members of my little family for their support and understanding, even though they missed me a lot while I worked on the R parts of this book. I am also really thankful to all the co-authors who teach at the Corvinus University of Budapest, Hungary, for providing useful content for this co-operation.

Michael Puhle obtained a Ph.D. in Finance from the University of Passau in Germany. He worked for several years as a Senior Risk Controller at Allianz Global Investors in Munich, and as an Assistant Manager at KPMG's Financial Risk Management practice, where he was advising banks on market risk models. Michael is also the author of Bond Portfolio Optimization published by Springer Publishing.

Edina Berlinger has a Ph.D. in Economics from the Corvinus University of Budapest. She is an Associate Professor, teaching corporate finance, investments, and financial risk management. She is the Head of Department for Finance of the university and is also the Chair of the Finance Sub committee the Hungarian Academy of Sciences. Her expertise covers student loan systems, risk management, and, recently, network analysis. She has led several research projects in student loan design, liquidity management, heterogeneous agent models, and systemic risk.

Péter Csóka is an Associate Professor at the Department of Finance, Corvinus University of Budapest, and a research fellow in the Game Theory Research Group, Centre For Economic and Regional Studies, Hungarian Academy of Sciences. He received his Ph.D. in Economics from Maastricht University in 2008. His research topics include risk measures, risk capital allocation, game theory, corporate finance, and general equilibrium theory. He is currently focused on analyzing risk contributions for systemic risk and for illiquid portfolios. He has papers published in journals such as Mathematical Methods of Operational Research, European Journal of Operational Research, Games and Economic Behaviour, and Journal of Banking and Finance. He is the Chair of the organizing committee of the Annual Financial Market Liquidity Conference in Budapest.

Daniel Havran is a Post Doctoral Fellow at the Institute of Economics, Centre for Economic and Regional Studies, Hungarian Academy of Sciences. He also holds a part-time Assistant Professorship position at the Corvinus University of Budapest, where he teaches Corporate Finance (BA and Ph.D. levels), and Credit Risk Management (MSc) courses. He obtained his Ph.D. in Economics at Corvinus University of Budapest in 2011. His research interests are corporate cash, funding liquidity management, and credit derivatives over-the-counter markets.

Márton Michaletzky obtained his Ph.D. degree in Economics in 2011 from Corvinus University of Budapest. Between 2000 and 2003, he has been a Risk Manager and Macroeconomic Analyst with Concorde Securities Ltd. As Capital Market Transactions Manager, he gained experience in an EUR 3 bn securitization at the Hungarian State Motorway Management Company. In 2012, he took part in the preparation of an IPO and the private placement of a Hungarian financial services provider. Prior to joining DBH Investment, he was an assistant professor at the Department of Finance of CUB.

Zsolt Tulassay works as a Quantitative Analyst at a major US investment bank, validating derivatives pricing models. Previously, Zsolt worked as an Assistant Lecturer at the Department of Finance at Corvinus University, teaching courses on Derivatives, Quantitative Risk Management, and Financial Econometrics. Zsolt holds MA degrees in Economics from Corvinus University of Budapest and Central European University. His research interests include derivatives pricing, yield curve modeling, liquidity risk, and heterogeneous agent models.

Kata Váradi is an Assistant Professor at the Department of Finance, Corvinus University of Budapest since 2013. Kata graduated in Finance in 2009 from Corvinus University of Budapest, and was awarded a Ph.D. degree in 2012 for her thesis on the analysis of the market liquidity risk on the Hungarian stock market. Her research areas are market liquidity, fixed income securities, and networks in healthcare systems. Besides doing research, she is active in teaching as well. She teaches mainly Corporate Finance, Investments, Valuation, and Multinational Financial Management.

Agnes Vidovics-Dancs is a Ph.D. candidate and an Assistant Professor at the Department of Finance, Corvinus University of Budapest. Previously, she worked as a Junior Risk Manager in the Hungarian Government Debt Management Agency. Her main research areas are government debt management in general, especially sovereign crises and defaults.

About the Reviewers

Dr. Hari Shanker Gupta is a Quantitative Research Analyst working in the area of Algorithming Trading System Development. Prior to this, he was a Post Doctoral Fellow at Indian Institute of Science (IISc), Bangalore, India. Hari has pursued his Ph.D. from Department of Mathematics, IISc, in the field of Applied Mathematics and Scientific Computation in the year 2010. Hari had completed his M.Sc. in Mathematics from Banaras Hindu University (B.H.U.), Varanasi, India. During M.Sc., Hari was awarded four gold medals for his outstanding performance in B.H.U., Varanasi.

Hari has published five research papers in reputed journals in the field of Mathematics and Scientific Computation. He has experience of working in the areas of mathematics, statistics, and computations. These include the topics: numerical methods, partial differential equation, mathematical finance, stochastic calculus, data analysis, finite difference, and finite element method. He is very comfortable with the mathematics software, Matlab; the statistics programming language, R, and, the programming language, C, and has been recently working on the Python platform.

Ronald Hochreiter is an Assistant Professor at the Department of Finance, Accounting and Statistics, at the WU Vienna University of Economics and Business. He obtained his Ph.D. in Computational Management Science at the University of Vienna in 2005. He is an avid R user and develops R packages mainly for optimization modeling purposes as well as for applications in Finance. A summary of his R projects can be found at http://www.hochreiter.net/R/, and some of his tutorials on Financial Engineering with R are online at http://www.finance-r.com/.

www.PacktPub.com

Support files, eBooks, discount offers and more

You might want to visit www.PacktPub.com for support files and downloads related to your book.

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

http://PacktLib.PacktPub.com

Do you need instant solutions to your IT questions? PacktLib is Packts online digital book library. Here, you can access, read and search across Packt's entire library of books. 

Why Subscribe?

Fully searchable across every book published by PacktCopy and paste, print and bookmark contentOn demand and accessible via web browser

Free Access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.

Preface

Introduction to R for Quantitative Finance will show you how to solve real-world quantitative finance problems using the statistical computing languages R and QF. In this book, we will cover diverse topics ranging from Time Series Analysis to Financial Networks. Each chapter will briefly present the theory and deal with solving a specific problem using R.

What this book covers

Chapter 1, Time Series Analysis (Michael Puhle), explains working with time series data in R. Furthermore, you will learn how to model and forecast house prices, improve hedge ratios using cointegration, and model volatility.

Chapter 2, Portfolio Optimization (Péter Csóka, Ferenc Illés, Gergely Daróczi), covers the theoretical idea behind portfolio selection and shows how to apply this knowledge to real-world data.

Chapter 3, Asset Pricing Models (Kata Váradi, Barbara Mária Dömötör, Gergely Daróczi), builds on the previous chapter and presents models for the relationship between asset return and risk. We'll cover the Capital Asset Pricing Model and the Arbitrage Pricing Theory.

Chapter 4, Fixed Income Securities (Márton Michaletzky, Gergely Daróczi), deals with the basics of fixed income instruments. Furthermore, you will learn how to calculate the risk of such an instrument and construct portfolios that will be immune to changes in interest rates.

Chapter 5, Estimating the Term Structure of Interest Rates (Tamás Makara, Gergely Daróczi), introduces the concept of a yield curve and shows how to estimate it using prices of government bonds.

Chapter 6, Derivatives Pricing (Ágnes Vidovics-Dancs, Gergely Daróczi), explains the pricing of derivatives using discrete and continuous time models. Furthermore, you will learn how to calculate derivatives risk measures and the so-called "Greeks".

Chapter 7, Credit Risk Management (Dániel Havran, Gergely Daróczi), gives an introduction to the credit default models and shows how to model correlated defaults using copulas.

Chapter 8, Extreme Value Theory (Zsolt Tulassay), presents possible uses of Extreme Value Theory in insurance and finance. You will learn how to fit a model to the tails of the distribution of fire losses. Then we will use the fitted model to calculate Value-at-Risk and Expected Shortfall.

Chapter 9, Financial Networks (Edina Berlinger, Gergely Daróczi), explains how financial networks can be represented, simulated, visualized, and analyzed in R. We will analyze the interbank lending market and learn how to systemically detect important financial institutions.

What you need for this book

All the code examples provided in this book should be run in the R console that is to be installed first on a computer. You can download the software for free and find the installation instructions for all major operating systems at http://r-project.org. Although we will not cover advanced topics such as how to use R in Integrated Development Environments, there are awesome plugins for Emacs, Eclipse, vi, or Notepad++ besides other editors, and we can also highly recommend trying 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 R Archive Network. To install a package, use the install.packages command in the R console, shown as follows:

> install.packages('zoo')

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

> library(zoo)

You can find free introductory articles and manuals on the R homepage, but this book is targeted towards beginners, so no additional R knowledge is assumed from the reader.

Who this book is for

The book is aimed at readers who wish to use R to solve problems in quantitative finance. Some familiarity with finance is assumed, but we generally provide the financial theory as well. Familiarity with R is not assumed. Those who want to get started with R may find this book useful as we don't give a complete overview of the R language but show how to use parts of it to solve specific problems. Even if you already use R, you will surely be amazed to see the wide range of problems that it can be applied to.

Conventions

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

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "we will employ some methods from the forecast package"

A block of R code (usually a function's body) is set as follows:

logreturn <- function(x) { log(tail(x, -1) / head(x, -1)) }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

logreturn <- function(x) { log(tail(x, -1) / head(x, -1)) }

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

> pi[1] 3.141593

Where ">" shows that the R console is waiting for commands to be evaluated. Multiline expressions are started with the same symbol on the first line, but all the rest lines have a "+" sign at the beginning to show that the last R expression is still to be finished.

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "clicking the Next button moves you to the next screen".

Note

Warnings or important notes appear in a box like this.

Tip

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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via 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 on www.packtpub.com/authors.

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 for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Errata

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 would 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 http://www.packtpub.com/submit-errata, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyright 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 <[email protected]> with a link to the suspected pirated material.

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

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Time Series Analysis

Time series analysis is concerned with the analysis of data collected over time. Adjacent observations are typically dependent. Time series analysis hence deals with techniques for the analysis of this dependence.

The objective of this chapter is to introduce some common modeling techniques by means of specific applications. We will see how to use R to solve these real-world examples. We begin with some thoughts about how to store and process time series data in R. Afterwards, we deal with linear time series analysis and how it can be used to model and forecast house prices. In the subsequent section, we use the notion of cointegration to improve on the basic minimal variance hedge ratio by taking long-run trends into consideration. The chapter concludes with a section on how to use volatility models for risk management purposes.

Working with time series data

The native R classes suitable for storing time series data include vector, matrix, data.frame, and ts objects. But the types of data that can be stored in these objects are narrow; furthermore, the methods provided by these representations are limited in scope. Luckily, there exist specialized objects that deal with more general representation of time series data: zoo, xts, or timeSeries objects, available from packages of the same name.

It is not necessary to create time series objects for every time series analysis problem, but more sophisticated analyses require time series objects. You could calculate the mean or variance of time series data represented as a vector in R, but if you want to perform a seasonal decomposition using decompose, you need to have the data stored in a time series object.