Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
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
$17.99 $25.99
Paperback
$43.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783280933
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 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
$199.99 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 $5 each
Feature tick icon Exclusive print discounts
$279.99 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Python for Finance
$48.99
Mastering R for Quantitative Finance
$54.99
Introduction to R for Quantitative Finance
$43.99
Total $ 147.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.