Learning Quantitative Finance with R - Dr. Param Jeet - E-Book

Learning Quantitative Finance with R E-Book

Dr. Param Jeet

0,0
39,59 €

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

Mehr erfahren.
Beschreibung

The role of a quantitative analyst is very challenging, yet lucrative, so there is a lot of competition for the role in top-tier organizations and investment banks. This book is your go-to resource if you want to equip yourself with the skills required to tackle any real-world problem in quantitative finance using the popular R programming language.

You'll start by getting an understanding of the basics of R and its relevance in the field of quantitative finance. Once you've built this foundation, we'll dive into the practicalities of building financial
models in R. This will help you have a fair understanding of the topics as well as their implementation, as the authors have presented some use cases along with examples that are easy to understand and correlate.

We'll also look at risk management and optimization techniques for algorithmic trading. Finally, the book will explain some advanced concepts, such as trading using machine learning, optimizations, exotic options, and hedging.

By the end of this book, you will have a firm grasp of the techniques required to implement basic quantitative finance models in R.

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

EPUB
MOBI

Seitenzahl: 261

Veröffentlichungsjahr: 2017

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

Learning Quantitative Finance with R
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
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. Introduction to R
The need for R
How to download/install R
How to install packages
Installing directly from CRAN
Installing packages manually
Data types
Vectors
Lists
Matrices
Arrays
Factors
DataFrames
Importing and exporting different data types
How to read and write a CSV format file
XLSX
Web data or online sources of data
Databases
How to write code expressions
Expressions
Constant expression
Arithmetic expression
Conditional expression
Functional call expression
Symbols and assignments
Keywords
Naming variables
Functions
Calling a function without an argument
Calling a function with an argument
How to execute R programs
How to run a saved file through R Window
How to source R script
Loops (for, while, if, and if...else)
if statement
if...else statement
for loop
while loop
apply()
sapply()
Loop control statements
break
next
Questions
Summary
2. Statistical Modeling
Probability distributions
Normal distribution
norm
pnorm
qnorm
rnorm
Lognormal distribution
dlnorm
plnorm
qlnorm
rlnorm
Poisson distribution
Uniform distribution
Extreme value theory
Sampling
Random sampling
Stratified sampling
Statistics
Mean
Median
Mode
Summary
Moment
Kurtosis
Skewness
Correlation
Autocorrelation
Partial autocorrelation
Cross-correlation
Hypothesis testing
Lower tail test of population mean with known variance
Upper tail test of population mean with known variance
Two-tailed test of population mean with known variance
Lower tail test of population mean with unknown variance
Upper tail test of population mean with unknown variance
Two tailed test of population mean with unknown variance
Parameter estimates
Maximum likelihood estimation
Linear model
Outlier detection
Boxplot
LOF algorithm
Standardization
Normalization
Questions
Summary
3. Econometric and Wavelet Analysis
Simple linear regression
Scatter plot
Coefficient of determination
Significance test
Confidence interval for linear regression model
Residual plot
Normality distribution of errors
Multivariate linear regression
Coefficient of determination
Confidence interval
Multicollinearity
ANOVA
Feature selection
Removing irrelevant features
Stepwise variable selection
Variable selection by classification
Ranking of variables
Wavelet analysis
Fast Fourier transformation
Hilbert transformation
Questions
Summary
4. Time Series Modeling
General time series
Converting data to time series
zoo
Constructing a zoo object
Reading an external file using zoo
Advantages of a zoo object
Subsetting the data
Merging zoo objects
Plotting zoo objects
Disadvantages of a zoo object
xts
Construction of an xts object using as.xts
Constructing an xts object from scratch
Linear filters
AR
MA
ARIMA
GARCH
EGARCH
VGARCH
Dynamic conditional correlation
Questions
Summary
5. Algorithmic Trading
Momentum or directional trading
Pairs trading
Distance-based pairs trading
Correlation based pairs trading
Co-integration based pairs trading
Capital asset pricing model
Multi factor model
Portfolio construction
Questions
Summary
6. Trading Using Machine Learning
Logistic regression neural network
Neural network
Deep neural network
K means algorithm
K nearest neighborhood
Support vector machine
Decision tree
Random forest
Questions
Summary
7. Risk Management
Market risk
Portfolio risk
VaR
Parametric VaR
Historical VaR
Monte Carlo simulation
Hedging
Basel regulation
Credit risk
Fraud detection
Liability management
Questions
Summary
8. Optimization
Dynamic rebalancing
Periodic rebalancing
Walk forward testing
Grid testing
Genetic algorithm
Questions
Summary
9. Derivative Pricing
Option pricing
Black-Scholes model
Cox-Ross-Rubinstein model
Greeks
Implied volatility
Bond pricing
Credit spread
Credit default swaps
Interest rate derivatives
Exotic options
Questions
Summary

Learning Quantitative Finance with R

Learning Quantitative Finance with R

Copyright © 2017 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: March 2017

Production reference: 1210317

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham 

B3 2PB, UK.

ISBN 978-1-78646-241-1

www.packtpub.com

Credits

Authors

Dr. Param Jeet

Prashant Vats

Copy Editor

Safis Editing

Reviewer

Manuel Amunategui

Project Coordinator

Shweta H Birwatkar

Commissioning Editor

Amey Varangaonkar

Proofreader

Safis Editing

Acquisition Editor

Varsha Shetty

Indexer

Mariammal Chettiyar

Content Development Editor

Amrita Noronha

Graphics

Tania Dutta

Technical Editor

Akash Patel

Production Coordinator

Arvindkumar Gupta

About the Authors

Dr. Param Jeet is a Ph.D. in mathematics from one of India's leading technological institute in Madras (IITM), India. Dr. Param Jeet has a couple of mathematical research papers published in various international journals. Dr. Param Jeet has been into the analytics industry for the last few years and has worked with various leading multinational companies as well as consulted few of companies as a data scientist.

I would like to thank my parents, S. Dhayan Singh &  Jeet Kaur, who always supported me in every phase of my life, my wife, Manpreet Kaur, who every time put herself  behind me with full energy and encourage me to write book, my little boy, Kavan Singh, whose innocence and little smile always cherished me to work and all family members. I also would like to thanks my Doctorate thesis advisor, Prof. Satyajit Roy, all the mentors I've had over the years, colleagues and friends without their help this book would not have been possible. With all these, I would like to share my knowledge with everyone who is keen to learn quantitative finance using R.  

Prashant Vats is a masters in mathematics from one of India’s leading technological institute, IIT Mumbai. Prashant has been into analytics industry for more than 10 years and has worked with various leading multinational companies as well as consulted few of companies as data scientist across several domain.

I would like to thank my parents, Late Devendra K. Singh &  Sushila Sinha, who allowed me to follow my dreams and  have always supported me throughout my career. I would like to thank my wife, Namrata for standing beside me  in all phases of my life and supporting  me to write this book, my little boy, Aahan Vats whose smile always inspires  me . I also would like to thank all the mentors I've had over the years, co-workers and friends without their help this book would not have been possible. With all these, I would like to share my knowledge with everyone who is keen to learn quantitative finance using R.  

About the Reviewer

Manuel Amunategui is an applied data scientist. He has implemented enterprise predictive solutions for many industries, including healthcare, finance, and sales. Prior to that, he worked as a quantitative developer on Wall Street for 6 years for one of the largest equity-options market-making firms, and as a software developer at Microsoft for 4 years.

He holds master degrees in Predictive Analytics from Northwestern University and in International Administration from the School for International Training.

He is currently the VP of Data Science at SpringML, a startup focused on offering advanced and predictive CRM analytics advice, dashboards, and automation. SpringML’s clients include Google Cloud Platform, Chevron, Yamaha, Tesoro, and Salesforce.

He is a data science advocate, blogger/vlogger (amunategui.github.io) and a trainer on Udemy.com and O’Reilly Media.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com.

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.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

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

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at http://www.amazon.com/dp/1786462419.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Preface

Learning Quantitative Finance with R explains practical examples of quantitative finance in the statistical language R. This book has been written with the intention of passing knowledge to people who are interested in learning quantitative finance with R. In this book, we have covered various topics, ranging from basic level to advance level. In particular, we have covered statistical, time series, and wavelet analysis along with their applications in algorithmic trading. We have also done our best to explain some applications of machine learning, risk management, optimization, and option pricing in this book.

What this book covers

Chapter 1, Introduction to R, explains basic commands in R. It starts with the installation of R and its packages and moves on to data types, DataFrames, and loops. This chapter also covers how to write and call functions and how to import data files of various formats into R. This chapter is meant to provide a basic understanding of R.

Chapter 2, Statistical Modeling, talks about the exploratory analysis like common distribution, correlation, measure of central tendencies, outlier detection to better understand the data. It also talks about sampling and standardization/ Normalization of the data which helps in preparing the data for analysis. Further this chapter also deals with hypothesis testing and parameter estimation.

Chapter 3, Econometric and Wavelet Analysis, covers simple and multivariate linear regression models, which are the backbone of every analysis. An explanation of ANOVA and feature selection adds flavor to this chapter. We also build a few models using wavelets analysis.

Chapter 4, Time Series Modeling, in this chapter the author presents the examples to convert data in time series using ts, zoo and xts which works as the base for forecasting models. Then the author talks about various forecasting techniques like AR, ARIMA, GARCH,VGARCH etc. and its execution in R along with examples.

Chapter 5, Algorithmic Trading, contains some live examples from the algorithmic trading domain, including momentum trading and pair trading using various methods. CAPM, multifactor model, and portfolio construction are also covered in this chapter.

Chapter 6, Trading Using Machine Learning, shows how to model a machine learning algorithm using capital market data. This covers supervised and unsupervised algorithms. 

Chapter 7, Risk Management, in this chapter the author discusses the techniques to measure market and portfolio risk. He also captures the common methods used for calculation of VAR. He also gives examples of the best practices used in banking domain for measuring credit risk.

Chapter 8, Optimization, in this chapter the author demonstrates examples of optimization techniques like dynamic rebalancing, walk forward testing, grid testing, genetic algorithm in financial domain.

Chapter 9, Derivative Pricing, use cases of R in derivative pricing. It covers vanilla option pricing along with exotic options, bonds pricing, credit spread and credit default swaps. This chapter is complex in nature and require people to have some basic understanding of derivatives.

What you need for this book

First of all, you should make sure that R is installed on your machine. All the examples in this book have been implemented in R and can be executed on the R console.  R is an open source platform and can be installed free of charge for any operating system from https://www.r-project.org/. Installation guidelines are also found on this website. Once you have R on your machine, you can straightaway go to chapter 1 and  start. Each chapter explains about the required packages, shows how to install packages, and and tells the reader how to load them into the workspace.

Who this book is for

This book is written with the intent to pass knowledge to people who are interested in learning R and its application in analytics. However, we have covered examples from finance.  This book covers basic to complex finance examples, along with varying degrees of complexity of R coding. This book does not expect you to have prior R programming knowledge, however this expects you to have little bit knowledge of mathematical analytical concepts. Even if you are well versed with R, this book can still be of great help to you as it explains various live examples from the data analytics industry, in particular, capital markets.

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: The quantmod package is used quite a few times."

A block of code is set as follows:

>getSymbols("^DJI",src="yahoo") >dji<- DJI[,"DJI.Close"]

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

corr<- rollapply(data,252,correlation ,by.column=FALSE)

For any R command we have used >, which means this command has been written on the command prompt, as  >, implies command prompt.

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 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 [email protected], 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 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 this book 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.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learning-Quantitative-Finance-with-R. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

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 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 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 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 https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

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 [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

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

Chapter 1.  Introduction to R

In this chapter, we will be discussing basic R concepts. This will serve as the background for upcoming chapters. We are not going to discuss each and every concept in detail for R. This chapter is meant for people who do not have any knowledge of the R language or beginners who are looking to pursue a career in quantitative finance or want to use R for quantitative financial analysis. This chapter can give you a start in learning how to write programs in R, and for writing complex programs, you can explore other books.

This chapter covers the following topics:

The need for RHow to download/install RHow to install packagesData typesImport and export of different data typesHow to write code expressionsFunctionsHow to execute R programsLoops (for, while, if, and if...else)

The need for R

There are so many statistical packages which can be used for solving problems in quantitative finance. But R is not a statistical package but it is a language. R is a flexible and powerful language for achieving high-quality analysis.

To use R, one does not need to be a programmer or computer-subject expert. The knowledge of basic programming definitely helps in learning R, but it is not a prerequisite for getting started with R.

One of the strengths of R is its package system. It is vast. If a statistical concept exists, chances are that there is already a package for it in R. There exist many functionalities that come built in for statistics / quantitative finance.

R is extendable and provides plenty of functionalities which encourage developers in quant finance to write their own tools or methods to solve their analytical problems.

The graphing and charting facilities present in R are unparalleled. R has a strong relationship with academia. As new research gets published, the likelihood is that a package for the new research gets added, due to its open source nature, which keeps R updated with the new concepts emerging in quant finance.

R was designed to deal with data, but when it came into existence, big data was nowhere in the picture. Additional challenges dealing with big data are the variety of data (text data, metric data, and so on), data security, memory, CPU I/O RSC requirements, multiple machines, and so on. Techniques such as map-reducing, in-memory processing, streaming data processing, down-sampling, chunking, and so on are being used to handle the challenges of big data in R.

Furthermore, R is free software. The development community is fantastic and easy to approach, and they are always interested in developing new packages for new concepts. There is a lot of documentation available on the Internet for different packages of R.

Thus, R is a cost-effective, easy-to-learn tool. It has very good data handling, graphical, and charting capabilities. It is a cutting-edge tool as, due to its open nature, new concepts in finance are generally accompanied by new R packages. It is demand of time for people pursuing a career in quantitative finance to learn R.

How to download/install R

In this section, we are going to discuss how to download and install R for various platforms: Windows, Linux, and Mac.

Open your web browser and go to the following link: https://cran.rstudio.com/.

From the given link, you can download the required version according to the available operating system.

For the Windows version, click on Download R for Windows, and then select the base version and download Download R 3.3.1 for Windows for your Windows operating system, click on it, and select your favorite language option. Now click through the installer and it will take you through various options, such as the following:

Setup Wizard.License Agreement.Select folder location where you want to install.Select the component. Select the option according to the configuration of your system; if you do not know the configuration of your system, then select all the options.If you want to customize your setup, select the option.Select the R launch options and desktop shortcut options according to your requirements.

R download and installation is complete for Windows.

Similarly, you click on your installer for Linux and Mac and it will take you through various options of installation.

How to install packages

R packages are a combination of R functions, compiled code, and sample data, and their storage directory is known as a library. By default, when R is installed, a set of packages gets installed and the rest of the packages you have to add when required.

A list of commands is given here to check which packages are present in your system:

>.libPaths()

The preceding command is used for getting or setting the library trees that R knows about. It gives the following result:

"C:/Program Files/R/R-3.3.1/library"

After this, execute the following command and it will list all the available packages:

>library()

There are two ways to install new packages.

Installing directly from CRAN

CRAN stands for Comprehensive R Archive Network. It is a network of FTP web servers throughout the globe for storing identical, up-to-date versions of code and documentation for R.

The following command is used to install the package directly from the CRAN web page. You need to choose the appropriate mirror:

>install.packages("Package")

For example, if you need to install the ggplot2 or forecast package for R, the commands are as follows:

>install.packages("ggplot2")>install.packages("forecast")

Installing packages manually

Download the required R package manually and save the ZIP version at your designated location (let's say /DATA/RPACKAGES/) on the system.

For example, if we want to install ggplot2, then run the following command to install it and load it to the current R environment. Similarly, other packages can also be installed:

>install.packages("ggplot2", lib="/data/Rpackages/")>library(ggplot2, lib.loc="/data/Rpackages/")

Importing and exporting different data types

In R, we can read the files stored from outside the R environment. We can also write the data into files which can be stored and accessed by the operating system. In R, we can read and write different formats of files, such as CSV, Excel, TXT, and so on. In this section, we are going to discuss how to read and write different formats of files.

The required files should be present in the current directory to read them. Otherwise, the directory should be changed to the required destination.

The first step for reading/writing files is to know the working directory. You can find the path of the working directory by running the following code:

>print (getwd())

This will give the paths for the current working directory. If it is not your desired directory, then please set your own desired directory by using the following code:

>setwd("")

For instance, the following code makes the folder C:/Users the working directory:

>setwd("C:/Users")

How to read and write a CSV format file

A CSV format file is a text file in which values are comma separated. Let us consider a CSV file with the following content from stock-market data:

Date

Open

High

Low

Close

Volume

Adj Close

14-10-2016

2139.68

2149.19

2132.98

2132.98

3.23E+09

2132.98

13-10-2016

2130.26

2138.19

2114.72

2132.55

3.58E+09

2132.55

12-10-2016

2137.67

2145.36

2132.77

2139.18

2.98E+09

2139.18

11-10-2016

2161.35

2161.56

2128.84

2136.73

3.44E+09

2136.73

10-10-2016

2160.39

2169.6

2160.39

2163.66

2.92E+09

2163.66

To read the preceding file in R, first save this file in the working directory, and then read it (the name of the file is Sample.csv) using the following code:

>data<-read.csv("Sample.csv") >print(data)

When the preceding code gets executed, it will give the following output:

Date Open High Low Close Volume Adj.Close 1 14-10-2016 2139.68 2149.19 2132.98 2132.98 3228150000 2132.98 2 13-10-2016 2130.26 2138.19 2114.72 2132.55 3580450000 2132.55 3 12-10-2016 2137.67 2145.36 2132.77 2139.18 2977100000 2139.18 4 11-10-2016 2161.35 2161.56 2128.84 2136.73 3438270000 2136.73 5 10-10-2016 2160.39 2169.60 2160.39 2163.66 2916550000 2163.66

Read.csv