Springer Texts in Business and Economics
Springer Texts in Business and Economics
2123
Clifford S. Ang
Compass Lexecon
Chicago, Illinois
USA
This book is sold with the understanding that neither the publisher nor the author is engaged in
rendering legal, accounting, investment, or other professional services or advice by publishing
this book. The models and techniques presented in this book are for information purposes only.
Each individual’s situation is unique and the reader should consult a professional to ensure
that any situation has been evaluated carefully and appropriately. The publisher and author
make no warranty, expressed or implied, from the use or application of any of the contents of
this book. This book also relies on third-party software, data, and packages and neither the
author nor the publisher warrant the accessibility, reliability, and accuracy of such third-party
data and packages.
Any opinions contained herein are solely those of the author and are not the opinions of
Compass Lexecon or its other employees.
This is a financial modeling book aimed at the relative beginner to R. The student
does not need to have prior financial modeling background, but having gone through
a corporate finance and investments course would be helpful. The goal of this text
is for the student to be able to obtain raw data, manipulate and analyze that data,
implement financial models, and generate the output required for the analysis.
There are three main features of this book. First, we use a R as the program of
choice because it is free and has a large on-line community that can provide support
to programmers of all levels. This means that the student can gain familiarity with
software that is being used by many people and does not cost the students anything to
acquire and update. In contrast, many texts use commercial software that the student
has to end up paying hundreds, if not thousands, of dollars in acquisition or renewal
costs to use after they get out of school.
Second, the examples in the book only use real-world data available for free to
the student for their personal use. We will primarily use data obtained from Yahoo
Finance and the Federal Reserve Electronic Database. Unlike typical textbook ex-
amples in which students see sample data that are sanitized for a particular purpose,
real-world data comes in a generic format that will likely not be suited for a specific
analysis. Although by using traditional textbook examples the student may be able
to say that they have learned to “analyze” data or “implemented” models, the lack of
experience using real world data will likely make the student feel challenged when
applying such analyses in practice.
Finally, the discussion in this text handholds the student through every step of
the way. The examples take the student from obtaining the raw data to manipulating
that data to performing the analysis and ends by showing how to generate a typical
output for that particular analysis. In addition, we also present intermediate output,
so students can quickly identify which portion of their code contains the error and
should get them back on track sooner.
Now that I have discussed what this book is about, let me briefly go through
what you will not see in this book. First, although this book teaches students how
to program in R, this is not a technical programming book. As such, I will be loose
with programming terminology. I will also sacrifice efficiency in writing code. The
primary reason is that the data used in our examples is relatively small, so the entire
vii
viii Preface
code runs in a matter of seconds. Therefore, we would not make any practical gains
from writing efficient code and the student may end up losing the intuition gained
by laying out each step.
Next, unlike some financial modeling books, this text will not come with program
codes available for download. In my opinion, giving the student an option to copy
and paste code will defeat the purpose of learning how to program. Programming
is one of those skills that students cannot learn without spending a decent amount
of time getting their hands dirty. This text shows the students all the code and also
shows them the intermediate output. As such, the very design of the book is to help
the student not get lost along the way. This book goes almost all the way to the end
but essentially stops short of typing the code for the student.
This book is broken up into nine chapters. Each chapter is pretty much self contained.
It is recommended that two packages are installed at the start of each chapter. These
are quantmod and xts. I also suggest to write code using the R Editor, so each
chapter’s code can be saved in one file. Although you can skip around to different
chapters, I recommend going through the chapters linearly as I likely will provide
fuller explanations the first time certain techniques are used or issues appear.
Chapter 1 is about security prices and introduces the student to basic data ma-
nipulation techniques. In addition, we show examples of how to perform technical
analysis in R.
In Chaps. 2 and 3, we demonstrates how to calculate returns for individual
securities and portfolios. Specifically, we show how to calculate arithmetic re-
turns, logarithmic returns, price returns, total returns, daily returns, weekly returns,
and monthly returns. We also go through the construction of equal-weighted and
value-weighted portfolio returns with quarterly rebalancing.
Chapter 4 deals with risk, which is the other side of the risk-return trade-off. We
show how to measure individual security risk and portfolio risk using variance or
standard deviation as the risk measure. We also implement other measures of risk,
namely Value-at-Risk or VaR, Expected Shortfall, and the risk measures developed
by Parkinson, Garman-Klass, Rogers, Satchell, & Yoon, and Yang & Zhang.
In Chap. 5, we analyze factor models, which are models that explain the variation
in expected stock returns using various proxies. We demonstrate how to imple-
ment the most popular of these models, which is the Capital Asset Pricing Model
(CAPM), as well as a commonly-used alternative model developed by Eugene Fama
and Kenneth French (i.e., the Fama-French Three Factor Model). We end this chap-
ter with a discussion of a widely-used application of factor models called the “event
study,” which empirically analyzes the reaction of securities to the disclosure of
value-relevant information.
To achieve higher returns, we have to take on more risk. In Chap. 6, we demon-
strate how to calculate various commonly-used risk-adjusted portfolio performance
Preface ix
measures, namely the Sharpe Ratio, Roy’s Safety First, Treynor Ratio, Sortino Ra-
tio, and the Information Ratio. These risk-adjusted return measures allow us to rank
different investments by their risk-return profile.
Chapter 7 discusses mean-variance optimization based on the work of Harry
Markowitz. The basic idea is for us to find portfolios that provide the highest ex-
pected return for a given level of risk. We demonstrate the intuition of identifying
mean-variance efficient portfolios and the construction of the mean-variance efficient
frontier through a simple two-asset example. We then show how to use quadratic pro-
gramming to extend the two-asset portfolio to a multi-asset portfolio. We end the
chapter by showing how allowing short selling impacts the calculation of the efficient
frontier.
In Chap. 8, we cover fixed income securities. We first show how to analyze eco-
nomic and fixed income market data. Then, we demonstrate how to implement basic
fixed income valuation models as well as the calculation of duration and convexity.
We end the book in Chap. 9 with showing how to analyze options data. We first
go through the implementation of the Black-Scholes-Merton options pricing model
(OPM) and the related Greeks. Then, we demonstrate how to implement the Binomial
OPM.
Acknowledgments
Writing a book is a major undertaking and I would like to express my gratitute to the
many people without whose support and assistance this book would not have been
possible.
To my wife and kids, thank you for all the support and sacrifices you have
made during the past several months as I work on programming and writing and
re-programming and re-writing.
I would like to thank Nick Philipson and Nitza Jones-Sepulveda at Springer for
helping turn my vision into a reality. Nick and Nitza have been invaluable each step
of the way and has made producing this book a pleasure.
I am grateful to Dexter Agcaoili at AXA Philippines, Elijah Brewer at DePaul,
Jian Cai at Fordham, Adam Fleck, CFA at Morningstar, Merritt Lyon at Compass
Lexecon, Andria van der Merwe at Compass Lexecon, Vince Warther at Chicago
Booth & Compass Lexecon, and Marie Winters, CFA at Northern Trust for their
feedback and ideas, as well as comments on earlier versions of the manuscript.
To Nassrin Berns at CSI and Victoria Schreiber at Interactive Data, thank you
for working with me to obtain approval for use of your firms’ data in this book.
The historical end-of-day data data for Amazon.com (AMZN), IBM (IBM), Netflix
(NFLX), S&P 500 Index (GSPC), SPDR S&P 500 ETF (SPY), SPDR S&P 600 Small
Cap ETF (SLY), SPDR MSCI ACWI ex-US ETF (CWI), SPDR Barclays Aggregate
Bond ETF (LAG), SPDR Barclays High Yield Bond ETF (JNK), Tesla (TSLA), and
Yahoo (YHOO) obtained from Yahoo Finance are provided by Commodity Systems,
Inc. (CSI). Amazon.com options data obtained from Yahoo Finance are provided
by Interactive Data Real-Time Services. I would also like to thank S&P Dow Jones
Indices LLC, Moody’s, CBOE, and Professor Kenneth French at Dartmouth for
allowing me to use their data.
Lastly, I am indebted to the various people that have posted code on R blogs
and websites whose names I no longer am able to recall. These individuals provide
assistance and service to R programmers of all levels and many of the codes and
techniques I use are likely an amalgamation of the various things I have seen on
these sites.
xi
xii Acknowledgments
Supplemental Website
1 Prices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Importing Daily Stock Price Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2 Importing Price Data from Yahoo Finance . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Checking the Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.1 Plotting the Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.2 Checking the Dimension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3.3 Outputting Summary Statistics . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.3.4 Checking the Ticker Symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4 Basic Data Manipulation Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.4.1 Keeping and Deleting One Row . . . . . . . . . . . . . . . . . . . . . . . . 16
1.4.2 Keeping First and Last Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
1.4.3 Keeping Contiguous Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
1.4.4 Keeping First Three Rows and Last Row . . . . . . . . . . . . . . . . . 19
1.4.5 Keeping and Deleting One Column . . . . . . . . . . . . . . . . . . . . . 20
1.4.6 Keeping Non-Contiguous Columns . . . . . . . . . . . . . . . . . . . . . 21
1.4.7 Keeping Contiguous Columns . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.4.8 Keeping Contiguous and Non-Contiguous Columns . . . . . . . 22
1.4.9 Subsetting Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.4.10 Subsetting Using Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.4.11 Converting Daily Prices to Weekly and Monthly Prices . . . . . 25
1.5 Comparing Capital Gains of Multiple Securities Over Time . . . . . . . 28
1.5.1 Alternative Presentation of Normalized Price Chart . . . . . . . . 37
1.6 Technical Analysis Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
1.6.1 Trend: Simple Moving Average Crossover . . . . . . . . . . . . . . . 41
1.6.2 Volatility: Bollinger Bands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
1.6.3 Momentum: Relative Strength Index . . . . . . . . . . . . . . . . . . . . 47
1.7 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
3 Portfolio Returns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.1 Constructing Portfolio Returns (Long Way) . . . . . . . . . . . . . . . . . . . . . 79
3.2 Constructing Portfolio Returns (Matrix Algebra) . . . . . . . . . . . . . . . . . 82
3.3 Constructing Benchmark Portfolio Returns . . . . . . . . . . . . . . . . . . . . . 83
3.3.1 Equal-Weighted Portfolio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.3.2 Value-Weighted Portfolio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.3.3 Normalized EW and VW Portfolio Price Chart . . . . . . . . . . . . 109
3.3.4 Saving Benchmark Portfolio Returns into a CSV File . . . . . . 110
3.4 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
9 Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
9.1 Obtaining Options Chain Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
9.2 Black-Scholes-Merton Options Pricing Model . . . . . . . . . . . . . . . . . . 311
9.3 Black-Scholes-Merton OPM Function . . . . . . . . . . . . . . . . . . . . . . . . . 315
9.4 Put-Call Parity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
9.5 The Greeks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
9.6 Implied Volatility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
9.7 Gauging Market Risk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
9.8 Binomial OPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
9.8.1 The Long Way . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
9.8.2 Binomial Model Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
9.9 Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349