Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Introduction to R for Quantitative Finance
Introduction to R for Quantitative Finance

Introduction to R for Quantitative Finance: R is a statistical computing language that's ideal for answering quantitative finance questions. This book gives you both theory and practice, all in clear language with stacks of real-world examples. Ideal for R beginners or expert alike.

eBook
R$80 R$196.99
Paperback
R$245.99
Subscription
Free Trial
Renews at R$50p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Introduction to R for Quantitative Finance

Chapter 2. Portfolio Optimization

By now we are familiar with the basics of the R language. We know how to analyze data, call its built-in functions, and apply them to the selected problems in a time series analysis. In this chapter we will use and extend this knowledge to discuss an important practical application: portfolio optimization, or in other words, security selection. This section covers the idea behind portfolio optimization: the mathematical models and theoretical solutions. To improve programming skills, we will implement an algorithm line by line using real data to solve a real-world example. We will also use the pre-written R packages on the same data set.

Imagine that we live in a tropical island and have only USD 100 to invest. Investment possibilities on the island are very limited; we can invest our entire fund into either ice creams or umbrellas. The payoffs that depend on the weather are as follows:

weather

ice cream

umbrella

sunny

120

90

rainy

90

120

Suppose...

Mean-Variance model


The Mean-Variance model by Markowitz (Markowitz, H.M. (March 1952)) is practically the ice-cream/umbrella business in higher dimensions. For the mathematical formulation, we need some definitions.

They are explained as follows:

  • By asset , we mean a random variable with finite variance.
  • By portfolio, we mean the combination of assets: , where , and . The combination can be affine or convex. In the affine case, there is no extra restriction on the weights. In the convex case, all the weights are non-negative.
  • By optimization, we mean a process of choosing the best coefficients (weights) so that our portfolio meets our needs (that is, it has a minimal risk on the given expected return or has the highest expected return on a given level of risk, and so on).

Let be the random return variables with a finite variance, be their covariance matrix, and .

We will focus on the following optimization problems:

It is clear that is the variance of the portfolio and is the expected...

Solution concepts


In the last 50 years, many great algorithms have been developed for numerical optimization and these algorithms work well, especially in case of quadratic functions. As we have seen in the previous section, we only have quadratic functions and constraints; so these methods (that are implemented in R as well) can be used in the worst case scenarios (if there is nothing better).

However, a detailed discussion of numerical optimization is out of the scope of this book. Fortunately, in the special case of linear and quadratic functions and constraints, these methods are unnecessary; we can use the Lagrange theorem from the 18th century.

Theorem (Lagrange)

If and , (where ) have continuous partial derivatives and is a relative extreme point of f(x) subject to the constraint where .

Then, there exist the coefficients such that

In other words, all of the partial derivatives of the function are 0 (Bertsekas Dimitri P. (1999)).

In our case, the condition is also sufficient. The...

Working with real data


It is useful to know that portfolio optimization is totally integrated in various R packages that we will discuss later. However, it's better to walk before we run; so let's start with a simple self-made R function that we would also itemize line by line as follows:

minvariance <- function(assets, mu = 0.005) {
    return  <- log(tail(assets, -1) / head(assets, -1))
    Q       <- rbind(cov(return), rep(1, ncol(assets)),
               colMeans(return))
    Q       <- cbind(Q, rbind(t(tail(Q, 2)), matrix(0, 2, 2)))
    b       <- c(rep(0, ncol(assets)), 1, mu)
    solve(Q, b)
}

This is a direct implementation of the algorithm that we discussed in the Theorem (Lagrange) section.

For demonstration purposes, we have fetched some IT stock prices from a Quandl superset (http://www.quandl.com/USER_1KR/1KT), which is a public service providing an easy access to a large amount of quant data. Although the URL points to a downloadable comma-separated values (CSV...

Tangency portfolio and Capital Market Line


What happens when a riskless asset is added to the model? If and X is any risky portfolio, then and obviously, . This means that those portfolios form a straight line on the mean-standard deviation plane. Any portfolio on this line is available by investing into R and X. It is clear that the best choice for X is the point where this line is tangent to Efficient Frontier. This tangency point is called the market portfolio or tangency portfolio, and the tangent of Efficient Frontier of risky assets at this point is called Capital Market Line (CML), which consists of the efficient portfolios of all the assets in this case. The last question that we address regarding the mean-variance model is how the market portfolio (or equivalently, the CML) can be determined.

We can easily modify the variance minimization code to accomplish this. First of all, if we add a riskless asset, a full-zero row and column is added to the covariance matrix (where n is...

Noise in the covariance matrix


When we optimize a portfolio, we don't have the real covariance matrix and the expected return vector (that are the inputs of the mean-variance model); we use observations to estimate them, so Q, r, and the output of the model are also random variables.

Without going into the details, we can say that this leads to surprisingly great uncertainty in the model. In spite of the strong law of large numbers, optimal portfolio weights sometimes vary between . Fortunately, if we have a few years' data (daily returns), the relative error of the measured risk is only 20-25 %.

When variance is not enough


Variance as a risk measure is convenient, but has some drawbacks. For instance, when using variance, positive changes in the return can be considered as the increase of risk. Therefore, more sophisticated risk measures have been developed.

For example, see the following short demo about various methods applied against the previously described IT_return assets for a quick overview about the options provided by the fPortfolio package:

> Spec <- portfolioSpec()
> setSolver(Spec) <- "solveRshortExact"
> setTargetReturn(Spec) <- mean(colMeans(IT_return))
> efficientPortfolio(IT_return, Spec, 'Short')
> minvariancePortfolio(IT_return, Spec, 'Short')
> minriskPortfolio(IT_return, Spec)
> maxreturnPortfolio(IT_return, Spec)

These R expressions return different portfolio weights computed by various methods not discussed in this introductory chapter. Please refer to the package bundled documentation, such as ?portfolio, and the relevant articles...

Summary


This chapter covered portfolio optimization. After presenting the main idea, we introduced the Markowitz model and its mathematical formulation. We discussed the methods for possible solutions and implemented a simple algorithm to demonstrate how these methods work on real data. We have also used pre-written R packages to solve the same problem. We broadly discussed other important subjects like the market portfolio, the uncertainty in the estimation of the covariance matrix, and the risk measures beyond variance. We hope that this was a useful first run on the topic and you are encouraged to study it further or check out the next chapter, which is about a related subject—asset pricing models.

Left arrow icon Right arrow icon

Key benefits

  • Use time series analysis to model and forecast house prices
  • Estimate the term structure of interest rates using prices of government bonds
  • Detect systemically important financial institutions by employing financial network analysis

Description

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.

Who is this book for?

If you are looking to use R to solve problems in quantitative finance, then this book is for you. A basic knowledge of financial theory is assumed, but familiarity with R is not required. With a focus on using R to solve a wide range of issues, this book provides useful content for both the R beginner and more experience users.

What you will learn

  • How to model and forecast house prices and improve hedge ratios using cointegration and model volatility
  • How to understand the theory behind portfolio selection and how it can be applied to real-world data
  • How to utilize the Capital Asset Pricing Model and the Arbitrage Pricing Theory
  • How to understand the basics of fixed income instruments
  • You will discover how to use discrete- and continuous-time models for pricing derivative securities
  • How to successfully work with credit default models and how to model correlated defaults using copulas
  • How to understand the uses of the Extreme Value Theory in insurance and fi nance, model fitting, and risk measure calculation

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 22, 2013
Length: 164 pages
Edition : 1st
Language : English
ISBN-13 : 9781783280940
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 22, 2013
Length: 164 pages
Edition : 1st
Language : English
ISBN-13 : 9781783280940
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
R$50 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
R$500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts
R$800 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just R$25 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total R$ 825.97
Introduction to R for Quantitative Finance
R$245.99
Mastering R for Quantitative Finance
R$306.99
Python for Finance
R$272.99
Total R$ 825.97 Stars icon

Table of Contents

9 Chapters
Time Series Analysis Chevron down icon Chevron up icon
Portfolio Optimization Chevron down icon Chevron up icon
Asset Pricing Models Chevron down icon Chevron up icon
Fixed Income Securities Chevron down icon Chevron up icon
Estimating the Term Structure of Interest Rates Chevron down icon Chevron up icon
Derivatives Pricing Chevron down icon Chevron up icon
Credit Risk Management Chevron down icon Chevron up icon
Extreme Value Theory Chevron down icon Chevron up icon
Financial Networks Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.2
(20 Ratings)
5 star 35%
4 star 0%
3 star 30%
2 star 15%
1 star 20%
Filter icon Filter
Top Reviews

Filter reviews by




NazHus Jan 30, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is ideal for those who are looking to use R to solve financial and statistical problems. However basic knowledge of financial theory is a needed. The authors do a great job on applying R to financial scenarios. Concepts are covered in a clear and concise manner. Perfect for beginners and Intermediates.
Amazon Verified review Amazon
Amazon Customer May 20, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
excellent
Amazon Verified review Amazon
Mauricio E. Ruiz Font Feb 05, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
El autor aclara que no se necesita saber R, pero eso no quiere decir que el libro vaya a empezar dando una introducción, se aprende sobre la lectura. no esperes encontrar un capitulo de introducción a R.
Amazon Verified review Amazon
D. Wong Jan 05, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really enjoyed this book. After working through the problems several times I realized how powerful R was and how many tools that are at my disposal. I think the author gives a great spread of very common financial calculations with repeatable examples. I am not am professional in any way but really felt it was good for someone who had a basic knowledge of quantitative finance and was looking to see how to apply that in R.Overall I think i got a great deal out of this book and it gives me much more confidence in working with R. Espeically for people just getting into either quant finance or working in RUsing the kindle version, i did have some annoying problems with the code. Because of 2 things. First off there are + signs on every line which is how its outputted in R, which you must remove. Also the kindle cut/paste function always gives the copyright and location. Which you have to delete out of every time you cut and paste. Its not really the authors fault just a quirk of the kindle cut and paste system. I did not subtract a star for this because of the kindle interface, however i can see where someone else would.
Amazon Verified review Amazon
David O'Brien Jan 13, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have a lot of experience with R, but am just starting to get into quantitative finance, as such, I found it very difficult to comprehend a lot of the chapters. Typically each page would have at least 1 or 2 terms that I would end up having to google. So you can imagine that the going was pretty slow. But the book is designed for people with some finance background.Even though I didn't get as much as I was hoping to initially, I think it's going to be a very handy resource for me to have. When I'm going to do an analysis covered by this book, I'm going to look at the examples as a primer to get going on the task. One of the hardest parts about R is finding the right function or package for a specific task. This book lays everything out there for me. And even if I'm going alter the analysis somehow, it's a huge time saver to have all the main functions in one place with cool examples.I think this book is perfect for someone who is familiar with finance and wants to switch languages to R, or maybe for finance students who don't know a statistical language (with maybe another resource for the basics of R). I'm going to take a free coursera course in finance and then come back to this book. Once I have more background, the book should be a good primer for new ideas for me.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.