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
€32.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Malta

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Redeem a companion digital copy on all Print orders
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Malta

Premium delivery 7 - 10 business days

€32.95
(Includes tracking information)

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
€18.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
€189.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
€264.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 111.97
Python for Finance
€36.99
Mastering R for Quantitative Finance
€41.99
Introduction to R for Quantitative Finance
€32.99
Total 111.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 the digital copy I get with my Print order? Chevron down icon Chevron up icon

When you buy any Print edition of our Books, you can redeem (for free) the eBook edition of the Print Book you’ve purchased. This gives you instant access to your book when you make an order via PDF, EPUB or our online Reader experience.

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela