Package PerformanceAnalytics
Package PerformanceAnalytics
March 2, 2018
Type Package
Title Econometric Tools for Performance and Risk Analysis
Version 1.5.2
Date 2018-02-28 $Date$
Description Collection of econometric functions for
performance and risk analysis. This package aims to aid
practitioners and researchers in utilizing the latest
research in analysis of non-normal return streams. In
general, it is most tested on return (rather than
price) data on a regular scale, but most functions will
work with irregular return data as well, and increasing
numbers of functions will work with P&L or price data
where possible.
Imports methods, quadprog, zoo
Depends R (>= 3.0.0), xts (>= 0.10.0)
Suggests dygraphs, Hmisc, MASS, quantmod, gamlss, [Link],
robustbase, quantreg, gplots, testthat
License GPL-2 | GPL-3
URL [Link]
Copyright (c) 2004-2018
RoxygenNote 6.0.1.9000
NeedsCompilation yes
Author Brian G. Peterson [cre, aut, cph],
Peter Carl [aut, cph],
Kris Boudt [ctb, cph],
Ross Bennett [ctb],
Joshua Ulrich [ctb],
Eric Zivot [ctb],
Dries Cornilly [ctb],
Eric Hung [ctb],
Matthieu Lestel [ctb],
Kyle Balkissoon [ctb],
Diethelm Wuertz [ctb]
1
2 R topics documented:
R topics documented:
PerformanceAnalytics-package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
ActiveReturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
AdjustedSharpeRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
AppraisalRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
AverageDrawdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
AverageLength . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
AverageRecovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
BernardoLedoitRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
BetaCoMoments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
BurkeRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
CalmarRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
CDD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
R topics documented: 3
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
checkData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
CoMoments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
DownsideDeviation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
DownsideFrequency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
DRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
DrawdownDeviation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
DrawdownPeak . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Drawdowns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
edhec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
ETL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
EWMAMoments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
FamaBeta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
HurstIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
InformationRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Kappa . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
KellyRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
kurtosis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
lpm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
M2Sortino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
MarketTiming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
MartinRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
maxDrawdown . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
MCA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
MeanAbsoluteDeviation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Modigliani . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
MSquared . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
MSquaredExcess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
NetSelectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Omega . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
OmegaExcessReturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
OmegaSharpeRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
PainIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
PainRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
portfolio_bacon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
prices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
ProspectRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
4 R topics documented:
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Selectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
SharpeRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
ShrinkageMoments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
skewness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
SkewnessKurtosisRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
SmoothingIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
sortDrawdowns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
SortinoRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
SpecificRisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
StdDev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
StructuredMoments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
SystematicRisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
TotalRisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
TrackingError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
TreynorRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
UlcerIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
UpDownRatios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
PerformanceAnalytics-package 5
UpsideFrequency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
UpsidePotentialRatio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
UpsideRisk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
VaR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
VolatilitySkewness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
weights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
zerofill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Index 203
PerformanceAnalytics-package
Econometric tools for performance and risk analysis.
Description
PerformanceAnalytics provides an R package of econometric functions for performance and
risk analysis of financial instruments or portfolios. This package aims to aid practitioners and
researchers in using the latest research for analysis of both normally and non-normally distributed
return streams.
We created this package to include functionality that has been appearing in the academic literature
on performance analysis and risk over the past several years, but had no functional equivalent in R.
In doing so, we also found it valuable to have wrappers for some functionality with good defaults
and naming consistent with common usage in the finance literature.
In general, this package requires return (rather than price) data. Almost all of the functions will
work with any periodicity, from annual, monthly, daily, to even minutes and seconds, either regular
or irregular.
The following sections cover Time Series Data, Performance Analysis, Risk Analysis (with a sepa-
rate treatment of VaR), Summary Tables of related statistics, Charts and Graphs, a variety of Wrap-
pers and Utility functions, and some thoughts on work yet to be done.
In this summary, we attempt to provide an overview of the capabilities provided by PerformanceAnalytics
and pointers to other literature and resources in R useful for performance and risk analysis. We hope
that this summary and the accompanying package and documentation partially fill a hole in the tools
available to a financial engineer or analyst.
provides more general time series support, whereas xts provides functionality that is specifically
aimed at users in finance.
Users can easily load returns data as time series for analysis with PerformanceAnalytics by using
the [Link] function. The [Link] function loads csv files of returns data where the data
is organized as dates in the first column and the returns for the period in subsequent columns. See
[Link] and [Link] if more flexibility is needed.
The functions described below assume that input data is organized with asset returns in columns and
dates represented in rows. All of the metrics in PerformanceAnalytics are calculated by column
and return values for each column in the results. This is the default arrangement of time series data
in xts.
Some sample data is available in the managers dataset. It is an xts object that contains columns of
monthly returns for six hypothetical asset managers (HAM1 through HAM6), the EDHEC Long-
Short Equity hedge fund index, the S&P 500 total returns, and total return series for the US Treasury
10-year bond and 3-month bill. Monthly returns for all series end in December 2006 and begin at
different periods starting from January 1996. That data set is used extensively in our examples and
should serve as a model for formatting your data.
For retrieving market data from online sources, see quantmod’s getSymbols function for down-
loading prices and chartSeries for graphing price data. Also see the tseries package for the
function [Link]. Look at xts’s [Link] function to rationally coerce irregular price
data into regular data of a specified periodicity. The aggregate function has methods for tseries
and zoo timeseries data classes to rationally coerce irregular data into regular data of the correct
periodicity.
Finally, see the function [Link] for calculating returns from prices.
Performance Analysis
The literature around the subject of performance analysis seems to have exploded with the pop-
ularity of alternative assets such as hedge funds, managed futures, commodities, and structured
products. Simpler tools that may have seemed appropriate in a relative investment world seem
inappropriate for an absolute return world. Risk measurement, which is nearly inseparable from
performance assessment, has become multi-dimensional and multi-moment while trying to answer
a simple question: “How much could I lose?” Portfolio construction and risk budgeting are two
sides of the same coin: “How do I maximize my expected gain and avoid going broke?” But be-
fore we can approach those questions we first have to ask: “Is this something I might want in my
portfolio?”
With the the increasing availability of complicated alternative investment strategies to both retail
and institutional investors, and the broad availability of financial data, an engaging debate about
performance analysis and evaluation is as important as ever. There won’t be one right answer deliv-
ered in these metrics and charts. What there will be is an accretion of evidence, organized to assist a
decision maker in answering a specific question that is pertinent to the decision at hand. Using such
tools to uncover information and ask better questions will, in turn, create a more informed investor.
Performance measurement starts with returns. Traders may object, complaining that “You can’t
eat returns,” and will prefer to look for numbers with currency signs. To some extent, they have a
point - the normalization inherent in calculating returns can be deceiving. Most of the recent work
in performance analysis, however, is focused on returns rather than prices and sometimes called
"returns-based analysis" or RBA. This “price per unit of investment” standardization is important
for two reasons - first, it helps the decision maker to compare opportunities, and second, it has some
PerformanceAnalytics-package 7
It is often valuable when evaluating an investment to know whether the instrument that you are
examining follows a normal distribution. One of the first methods to determine how close the as-
set is to a normal or log-normal distribution is to visually look at your data. Both [Link]
and [Link] will quickly give you a feel for whether or not you are looking at a nor-
mally distributed return history. Differences between var and SemiVariance will help you identify
skewness in the returns. Skewness measures the degree of asymmetry in the return distribution.
Positive skewness indicates that more of the returns are positive, negative skewness indicates that
more of the returns are negative. An investor should in most cases prefer a positively skewed asset
to a similar (style, industry, region) asset that has a negative skewness.
Kurtosis measures the concentration of the returns in any given part of the distribution (as you
should see visually in a histogram). The kurtosis function will by default return what is referred
to as “excess kurtosis”, where 0 is a normal distribution, other methods of calculating kurtosis than
method="excess" will set the normal distribution at a value of 3. In general a rational investor
should prefer an asset with a low to negative excess kurtosis, as this will indicate more predictable
returns (the major exception is generally a combination of high positive skewness and high excess
kurtosis). If you find yourself needing to analyze the distribution of complex or non-smooth asset
8 PerformanceAnalytics-package
distributions, the nortest package has several advanced statistical tests for analyzing the normality
of a distribution.
Modern Portfolio Theory (MPT) is the collection of tools and techniques by which a risk-averse
investor may construct an “optimal” portfolio. It was pioneered by Markowitz’s ground-breaking
1952 paper Portfolio Selection. It also encompasses CAPM, below, the efficient market hypothesis,
and all forms of quantitative portfolio construction and optimization.
The Capital Asset Pricing Model (CAPM), initially developed by William Sharpe in 1964, provides
a justification for passive or index investing by positing that assets that are not on the efficient
frontier will either rise or fall in price until they are. The [Link] is the measure of
how much the asset’s performance differs from the risk free rate. Negative Risk Premium generally
indicates that the investment is a bad investment, and the money should be allocated to the risk
free asset or to a different asset with a higher risk premium. [Link] is the degree to which
the assets returns are not due to the return that could be captured from the market. Conversely,
[Link] describes the portions of the returns of the asset that could be directly attributed to the
returns of a passive investment in the benchmark asset.
The Capital Market Line [Link] relates the excess expected return on an efficient market port-
folio to its risk (represented in CAPM by sd). The slope of the CML, [Link], is the
Sharpe Ratio for the market portfolio. The Security Market Line is constructed by calculating the
line of [Link] over [Link]. For the benchmark asset this will be 1 over the risk
premium of the benchmark asset. The slope of the SML, primarily for plotting purposes, is given
by [Link]. CAPM is a market equilibrium model or a general equilibrium theory of the
relation of prices to risk, but it is usually applied to partial equilibrium portfolios, which can create
(sometimes serious) problems in valuation.
One extension to the CAPM contemplates evaluating an active manager’s ability to time the mar-
ket. Two other functions apply the same notion of best fit to positive and negative market returns,
separately. The [Link] is a regression for only positive market returns, which can be
used to understand the behavior of the asset or portfolio in positive or ’bull’ markets. Alternatively,
[Link] provides the calculation on negative market returns. The TimingRatio uses the
ratio of those to help assess whether the manager has shown evidence that of timing skill.
The performance premium provided by an investment over a passive strategy (the benchmark) is
provided by ActivePremium, which is the investment’s annualized return minus the benchmark’s
annualized return. A closely related measure is the TrackingError, which measures the unex-
plained portion of the investment’s performance relative to a benchmark. The InformationRatio
of an investment in a MPT or CAPM framework is the Active Premium divided by the Tracking
Error. Information Ratio may be used to rank investments in a relative fashion.
We have also included a function to compute the KellyRatio. The Kelly criterion applied to posi-
tion sizing will maximize log-utility of returns and avoid risk of ruin. For our purposes, it can also
be used as a stack-ranking method like InformationRatio to describe the “edge” an investment
would have over a random strategy or distribution.
These metrics and others such as SharpeRatio, SortinoRatio, UpsidePotentialRatio, Spear-
man rank correlation (see rcorr), etc., are all methods of rank-ordering relative performance.
Alexander and Dimitriu (2004) in “The Art of Investing in Hedge Funds” show that relative rank-
ings across multiple pricing methodologies may be positively correlated with each other and with
expected returns. This is quite an important finding because it shows that multiple methods of pre-
dicting returns and risk which have underlying measures and factors that are not directly correlated
to another measure or factor will still produce widely similar quantile rankings, so that the “buck-
ets” of target instruments will have significant overlap. This observation specifically supports the
PerformanceAnalytics-package 9
point made early in this document regarding “accretion of the evidence” for a positive or negative
investment decision.
Style Analysis
Style analysis is one way to help determine a fund’s exposures to the changes in returns of major
asset classes or other factors. PerformanceAnalytics previously had a few functions that calculate
style weights using an asset class style model as described in detail in Sharpe (1992).
These functions have been moved to R-Forge in package FactorAnalytics as part of a collab-
oration with Eric Zivot at the University of Washington. The functions combine to calculate ef-
fective style weights and display the results in a bar chart. [Link] calculates and displays
style weights calculated over a single period. [Link] calculates and displays those
weights in rolling windows through time. [Link] manages the calculation of the weights by
method, and [Link] calculates the specific constraint case that requires quadratic program-
ming. [note: these functions do not currently appear in the development codebase, but should
reappear as a supported method at some point]
There is a significant amount of academic literature on identifying and attributing sources of risk
or returns. Much of it falls into the field of “factor analysis” where “risk factors” are used to ret-
rospectively explain sources of risk, and through regression and other analytical methods predict
future period returns and risk based on factor drivers. These are well covered in chapters on factor
analysis in Zivot and Wang(2006) and also in the R functions factanal for basic factor analysis
and princomp for Principal Component Analysis. The authors feel that financial engineers and
analysts would benefit from some wrapping of this functionality focused on finance, but the capa-
bilities already available from the base functions are quite powerful. We are hopeful that our new
collaboration with Prof. Zivot will provide additional functionality in the near future.
Risk Analysis
Many methods have been proposed to measure, monitor, and control the risks of a diversified port-
folio. Perhaps a few definitions are in order on how different risks are generally classified. Market
Risk is the risk to the portfolio from a decline in the market price of instruments in the portfolio.
Liquidity Risk is the risk that the holder of an instrument will find that a position is illiquid, and
will incur extra costs in unwinding the position resulting in a less favorable price for the instrument.
In extreme cases of liquidity risk, the seller may be unable to find a buyer for the instrument at
all, making the value unknowable or zero. Credit Risk encompasses Default Risk, or the risk that
promised payments on a loan or bond will not be made, or that a convertible instrument will not
be converted in a timely manner or at all. There are also Counterparty Risks in over the counter
markets, such as those for complex derivatives. Tools have evolved to measure all these different
components of risk. Processes must be put into place inside a firm to monitor the changing risks in
a portfolio, and to control the magnitude of risks. For an extensive treatment of these topics, see
Litterman, Gumerlock, et. al.(1998). For our purposes, PerformanceAnalytics tends to focus on
market and liquidity risk.
The simplest risk measure in common use is volatility, usually modeled quantitatively with a uni-
variate standard deviation on a portfolio. See sd. Volatility or Standard Deviation is an appropriate
risk measure when the distribution of returns is normal or resembles a random walk, and may be
annualized using [Link], or the equivalent function [Link] for scaling to an
arbitrary number of periods. Many assets, including hedge funds, commodities, options, and even
most common stocks over a sufficiently long period, do not follow a normal distribution. For such
10 PerformanceAnalytics-package
common but non-normally distributed assets, a more sophisticated approach than standard devia-
tion/volatility is required to adequately model the risk.
Markowitz, in his Nobel acceptance speech and in several papers, proposed that SemiVariance
would be a better measure of risk than variance. See Zin, Markowitz, Zhao (2006). This measure is
also called SemiDeviation. The more general case is DownsideDeviation, as proposed by Sortino
and Price(1994), where the minimum acceptable return (MAR) is a parameter to the function. It is
interesting to note that variance and mean return can produce a smoothly elliptical efficient frontier
for portfolio optimization using [Link] or [Link] or fPortfolio. Use of semivari-
ance or many other risk measures will not necessarily create a smooth ellipse, causing significant
additional difficulties for the portfolio manager trying to build an optimal portfolio. We’ll leave a
more complete treatment and implementation of portfolio optimization techniques for another time.
Another very widely used downside risk measures is analysis of drawdowns, or loss from peak
value achieved. The simplest method is to check the maxDrawdown, as this will tell you the worst
cumulative loss ever sustained by the asset. If you want to look at all the drawdowns, you can
findDrawdowns and sortDrawdowns in order from worst/major to smallest/minor. The UpDownRatios
function will give you some insight into the impacts of the skewness and kurtosis of the returns, and
letting you know how length and magnitude of up or down moves compare to each other. You can
also plot drawdowns with [Link].
One of the most commonly used and cited measures of the risk/reward tradeoff of an investment or
portfolio is the SharpeRatio, which measures return over standard deviation. If you are comparing
multiple assets using Sharpe, you should use [Link]. It is important to note
that William Sharpe now recommends InformationRatio preferentially to the original Sharpe
Ratio. The SortinoRatio uses mean return over DownsideDeviation below the MAR as the risk
measure to produce a similar ratio that is more sensitive to downside risk. Sortino later enhanced
his ideas to use upside returns for the numerator and DownsideDeviation as the denominator in
UpsidePotentialRatio. Favre and Galeano(2002) propose using the ratio of expected excess
return over the Cornish-Fisher VaR to produce [Link]. TreynorRatio is also
similar to the Sharpe Ratio, except it uses [Link] in place of the volatility measure to produce
the ratio of the investment’s excess return over the beta.
One of the newer statistical methods developed for analyzing the risk of financial instruments is
Omega. Omega analytically constructs a cumulative distribution function, in a manner similar to
[Link], but then extracts additional information from the location and slope of the derived
function at the point indicated by the risk quantile that the researcher is interested in. Omega seeks
to combine a large amount of data about the shape, magnitude, and slope of the distribution into
one method. The academic literature is still exploring the best manner to use Omega in a risk
measurement and control process, or in portfolio construction.
Any risk measure should be viewed with suspicion if there are not a large number of historical
observations of returns for the asset in question available. Depending on the measure, the number
of observations required will vary greatly from a statistical standpoint. As a heuristic rule, ideally
you will have data available on how the instrument performed through several economic cycles and
shocks. When such a long history is not available, the investor or researcher has several options.
A full discussion of the various approaches is beyond the scope of this introduction, so we will
merely touch on several areas that an interested party may wish to explore in additional detail.
Examining the returns of assets with a similar style, industry, or asset class to which the asset
in question is highly correlated and shares other characteristics can be quite informative. Factor
analysis may be used to uncover specific risk factors where transparency is not available. Various
resampling (see tsbootstrap) and simulation methods are available in R to construct an artificially
PerformanceAnalytics-package 11
long distribution for testing. If you use a method such as Monte Carlo simulation or the bootstrap,
it is often valuable to use [Link] to visualize the different estimates of the risk measure
produced by the simulation, to see how small (or wide) a range the estimates cover, and thus gain
a level of confidence with the results. Proceed with extreme caution when your historical data is
lacking. Problems with lack of historical data are a major reason why many institutional investors
will not invest in an alternative asset without several years of historical return data available.
method="modified". See Uryasev(2000) and Sherer and Martin(2005) for more information on
Conditional Value at Risk and Expected Shortfall. Please note that your milage will vary; expect that
values obtained from the normal distribution may differ radically from the real situation, depending
on the assets under analysis.
Multivariate extensions to risk measures: We have extened all moments calculations to work in a
multivariate portfolio context. In a portfolio context the multivariate moments are generally to be
preferred to their univariate counterparts, so that all information is available to subsequent calcu-
lations. Both the VaR and ES functions allow calculation of metrics in a portfolio context when
weights and a portfolio_method are passed into the function call.
Marginal, Incremental, and Component VaR: Marginal VaR is the difference between the VaR of the
portfolio without the asset in question and the entire portfolio. The VaR function calculates Marginal
VaR for all instruments in the portfolio if you set method="marginal". Marginal VaR as provided
here may use traditional mean-VaR or Modified VaR for the calculation. Per Artzner,[Link].(1997)
properties of a coherent risk measure include subadditivity (risks of the portfolio should not exceed
the sum of the risks of individual components) as a significantly desirable trait. VaR measures,
including Marginal VaR, on individual components of a portfolio are not subadditive.
Clearly, a general subadditive risk measure for downside risk is required. In Incremental or Compo-
nent VaR, the Component VaR value for each element of the portfolio will sum to the total VaR of
the portfolio. Several EDHEC papers suggest using Modified VaR instead of mean-VaR in the In-
cremental and Component VaR calculation. We have succeeded in implementing Component VaR
and ES calculations that use Modified Cornish-Fisher VaR, historical decomposition, and kernel
estimators. You may access these with VaR or ES by setting the appropriate portfolio_method and
method arguments.
The [Link] function creates a chart of Value-at-Risk or Expected Shortfall esti-
mates by confidence interval for multiple methods. Useful for comparing a calculated VaR or ES
method to the historical VaR or ES, it may also be used to visually examine whether the VaR method
“breaks down” or gives nonsense results at a certain threshold.
Which VaR measure to use will depend greatly on the portfolio and instruments being analyzed. If
there is any generalization to be made on VaR measures, we agree with Bali and Gokcan(2004) who
conclude that “the VaR estimations based on the generalized Pareto distribution and the Cornish-
Fisher approximation perform best”.
develop a framework that assesses the potential diversification of an asset relative to a portfolio.
They use higher moment betas to estimate how much portfolio risk will be impacted by adding an
asset.
Higher moment betas are defined as proportional to the derivative of the covariance, coskewness and
cokurtosis of the second, third and fourth portfolio moment with respect to the portfolio weights.
A beta that is less than 1 indicates that adding the new asset should reduce the resulting portfolio’s
volatility and kurtosis, and to an increase in skewness. More specifically, the lower the beta the
higher the diversification effect, not only in terms of normal risk (i.e. volatility) but also the risk
of assymetry (skewness) and extreme events (kurtosis). See the functions for BetaCoVariance,
BetaCoSkewness, and BetaCoKurtosis.
[Link] creates a stacked column chart with time on the horizontal axis and values in
categories. This kind of chart is commonly used for showing portfolio ’weights’ through time,
although the function will plot any values by category.
We have been greatly inspired by other peoples’ work, some of which is on display at addicted-
[Link]. Particular inspiration came from Dirk Eddelbuettel and John Bollinger for their work at
[Link] Those interested in price chart-
ing in R should also look at the quantmod package.
R is a very powerful environment for manipulating data. It can also be quite confusing to a user
more accustomed to Excel or even MatLAB. As such, we have written some wrapper functions that
may aid you in coercing data into the correct forms or finding data that you need to use regularly.
To simplify the management of multiple-source data stored in R in multiple data formats, we have
provided checkData. This function will attempt to coerce data in and out of R’s multitude of mostly
fungible data classes into the class required for a particular analysis. The data-coercion function has
been hidden inside the functions here, but it may also save you time and trouble in your own code
and functions as well.
R’s built-in apply function in enormously powerful, but is can be tricky to use with timeseries
data, so we have provided wrapper functions to [Link] and [Link] to make
handling of “from inception” and “rolling window” calculations easier.
Further Work
We have attempted to standardize function parameters and variable names, but more work exists to
be done here.
Any comments, suggestions, or code patches are invited.
If you’ve implemented anything that you think would be generally useful to include, please consider
donating it for inclusion in a later version of this package.
Acknowledgments
Data series edhec used in PerformanceAnalytics and related publications with the kind permis-
sion of the EDHEC Risk and Asset Management Research Center.
[Link]
Kris Boudt was instrumental in our research on component risk for portfolios with non-normal
distributions, and is responsible for much of the code for multivariate moments and co-moments.
Jeff Ryan and Josh Ulrich are active participants in the R finance community and created xts, upon
which much of PerformanceAnalytics depends.
Prototypes of the drawdowns functionality were provided by Sankalp Upadhyay, and modified with
permission. Stephan Albrecht provided detailed feedback on the Getmansky/Lo Smoothing Index.
Diethelm Wuertz provided prototypes of modified VaR and skewness and kurtosis functions (and
is of course the maintainer of the RMetrics suite of pricing and optimization functions). He also
contributed prototypes for many other functions from Bacon’s book that were incorporated into
PerformanceAnalytics by Matthieu Lestel. Any errors are, of course, our own.
16 PerformanceAnalytics-package
Thanks to Joe Wayne Byers and Dirk Eddelbuettel for comments on early versions of these func-
tions, and to Khanh Nguyen, Tobias Verbeke, H. Felix Wittmann, and Ryan Sheftel for careful
testing and detailed problem reports.
Thanks also to our Google Summer of Code students through the years for their contributions.
Significant contributions from GSOC students to this package have come from Matthieu Lestel and
Andrii Babii so far. We expect to eventually incorporate contributions from Pulkit Mehrotra and
Shubhankit Mohan, who worked with us during the summer of 2013.
Thanks to the R-SIG-Finance community without whom this package would not be possible. We
are indebted to the R-SIG-Finance community for many helpful suggestions, bugfixes, and requests.
Author(s)
Brian G. Peterson
Peter Carl
References
Amenc, N. and Le Sourd, V. Portfolio Theory and Performance Analysis. Wiley. 2003.
Litterman, R., Gumerlock R., et. al. The Practice of Risk Management: Implementing Processes
for Managing Firm-Wide Market Risk. Euromoney. 1998.
Martellini, Lionel, and Volker Ziemann. Improved Forecasts of Higher-Order Comoments and Im-
plications for Portfolio Selection. EDHEC Risk and Asset Management Research Centre working
paper. 2007.
Ranaldo, Angelo, and Laurent Favre Sr. How to Price Hedge Funds: From Two- to Four-Moment
CAPM. SSRN eLibrary. 2005.
Murrel, P. R Graphics. Chapman and Hall. 2006.
Shumway, R. and Stoffer, D. Time Series Analysis and it’s Applications, with R examples, Springer,
2006.
ActiveReturn 17
Zin, Markowitz, Zhao A Note on Semivariance. Mathematical Finance, Vol. 16, No. 1, pp. 53-61,
January 2006
Zivot, E. and Wang, Z. Modeling Financial Time Series with S-Plus: second edition. Springer. 2006.
See Also
CRAN task view on Empirical Finance
[Link]
Grant Farnsworth’s Econometrics in R
[Link]
Collection of R charts and graphs
[Link]
Description
The return on an investment’s annualized return minus the benchmark’s annualized return.
Usage
ActiveReturn(Ra, Rb, scale = NA, ...)
Arguments
Ra return vector of the portfolio
Rb return vector of the benchmark asset
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
... any other passthru parameters to [Link] (e.g., geometric=FALSE)
Details
Active Premium = Investment’s annualized return - Benchmark’s annualized return
Also commonly referred to as ’active return’.
Author(s)
Peter Carl
18 AdjustedSharpeRatio
References
Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management, Fall 1994, 49-58.
See Also
InformationRatio TrackingError [Link]
Examples
data(managers)
ActivePremium(managers[, "HAM1", drop=FALSE], managers[, "SP500 TR", drop=FALSE])
ActivePremium(managers[,1,drop=FALSE], managers[,8,drop=FALSE])
ActivePremium(managers[,1:6], managers[,8,drop=FALSE])
ActivePremium(managers[,1:6], managers[,8:7,drop=FALSE])
Description
Adjusted Sharpe ratio was introduced by Pezier and White (2006) to adjusts for skewness and
kurtosis by incorporating a penalty factor for negative skewness and excess kurtosis.
Usage
AdjustedSharpeRatio(R, Rf = 0, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf the risk free rate
... any other passthru parameters
Details
S K −3
AdjustedSharpeRatio = SR ∗ [1 + ( ) ∗ SR − ( ) ∗ SR2 ]
6 24
where SR is the sharpe ratio with data annualized, S is the skewness and K is the kurtosis
Author(s)
Matthieu Lestel, Brian G. Peterson
[Link] 19
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.99
Pezier, Jaques and White, Anthony. 2006. The Relative Merits of Investable Hedge Fund Indices
and of Funds of Hedge Funds in Optimal Passive Portfolios. [Link]
paper/rdgicmadp/[Link]
See Also
[Link]
Examples
data(portfolio_bacon)
print(AdjustedSharpeRatio(portfolio_bacon[,1])) #expected 0.7591435
data(managers)
print(AdjustedSharpeRatio(managers['1996']))
Description
A function to calculate a function over an expanding window from the start of the timeseries. This
wrapper allows easy calculation of “from inception” statistics.
Usage
[Link](R, FUN = "mean", gap = 1, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
FUN any function that can be evaluated using a single set of returns (e.g., rolling beta
won’t work, but [Link] will)
gap the number of data points from the beginning of the series required to “train”
the calculation
... any other passthru parameters
Author(s)
Peter Carl
20 [Link]
See Also
rollapply
Examples
data(managers)
[Link](managers[,1,drop=FALSE], FUN="mean", width=36)
Description
Creates a results timeseries of a function applied over a rolling window.
Usage
[Link](R, width, trim = TRUE, gap = 12, by = 1, FUN = "mean",
...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
width number of periods to apply rolling function window over
trim TRUE/FALSE, whether to keep alignment caused by NA’s
gap numeric number of periods from start of series to use to train risk calculation
by calculate FUN for trailing width points at every by-th time point.
FUN any function that can be evaluated using a single set of returns (e.g., rolling beta
won’t work, but [Link] will)
... any other passthru parameters
Details
Wrapper function for rollapply to hide some of the complexity of managing single-column zoo
objects.
Value
A timeseries in a zoo object of the calculation results
Author(s)
Peter Carl
AppraisalRatio 21
See Also
apply
rollapply
Examples
data(managers)
[Link](managers[,1,drop=FALSE], FUN="mean", width=36)
Description
Appraisal ratio is the Jensen’s alpha adjusted for specific risk. The numerator is divided by specific
risk instead of total risk.
Usage
AppraisalRatio(Ra, Rb, Rf = 0, method = c("appraisal", "modified",
"alternative"), ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
method is one of "appraisal" to calculate appraisal ratio, "modified" to calculate modified
Jensen’s alpha or "alternative" to calculate alternative Jensen’s alpha.
... any other passthru parameters
Details
Modified Jensen’s alpha is Jensen’s alpha divided by beta.
Alternative Jensen’s alpha is Jensen’s alpha divided by systematic risk.
α
Appraisalratio =
σ
α
M odif iedJensen0 salpha =
β
α
AlternativeJensen0 salpha =
σS
where alpha is the Jensen’s alpha, σepsilon is the specific risk, σS is the systematic risk.
22 AverageDrawdown
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.77
Examples
data(portfolio_bacon)
print(AppraisalRatio(portfolio_bacon[,1], portfolio_bacon[,2], method="appraisal")) #expected -0.430
print(AppraisalRatio(portfolio_bacon[,1], portfolio_bacon[,2], method="modified"))
print(AppraisalRatio(portfolio_bacon[,1], portfolio_bacon[,2], method="alternative"))
data(managers)
print(AppraisalRatio(managers['1996',1], managers['1996',8]))
print(AppraisalRatio(managers['1996',1:5], managers['1996',8]))
Description
ADD = abs(sum[j=1,2,...,d](D_j/d)) where D’_j = jth drawdown over entire period d = total number
of drawdowns in the entire period
Usage
AverageDrawdown(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Author(s)
Peter Carl
AverageLength 23
AverageLength Calculates the average length (in periods) of the observed drawdowns.
Description
Similar to AverageDrawdown, which calculates the average depth of drawdown, this function cal-
culates the average length of the drawdowns observed.
Usage
AverageLength(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Author(s)
Peter Carl
AverageRecovery Calculates the average length (in periods) of the observed recovery
period.
Description
Similar to AverageDrawdown, which calculates the average depth of drawdown, this function cal-
culates the average length of the recovery period of the drawdowns observed.
Usage
AverageRecovery(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Author(s)
Peter Carl
24 BernardoLedoitRatio
Description
To calculate Bernardo and Ledoit ratio we take the sum of the subset of returns that are above 0 and
we divide it by the opposite of the sum of the subset of returns that are below 0
Usage
BernardoLedoitRatio(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
1
Pn
max(Rt , 0)
BernardoLedoitRatio(R) = 1
n
Pnt=1
n t=1 max(−Rt , 0)
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.95
Examples
data(portfolio_bacon)
print(BernardoLedoitRatio(portfolio_bacon[,1])) #expected 1.78
data(managers)
print(BernardoLedoitRatio(managers['1996']))
print(BernardoLedoitRatio(managers['1996',1])) #expected 4.598
BetaCoMoments 25
Description
calculate higher co-moment betas, or ’systematic’ variance, skewness, and kurtosis
Usage
BetaCoVariance(Ra, Rb)
BetaCoKurtosis(Ra, Rb)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of index, benchmark,
or secondary asset returns to compare against
test condition not implemented yet
Author(s)
Kris Boudt, Peter Carl, Brian Peterson
References
Boudt, Kris, Brian G. Peterson, and Christophe Croux. 2008. Estimation and Decomposition of
Downside Risk for Portfolios with Non-Normal Returns. Journal of Risk. Winter.
Martellini, Lionel, and Volker Ziemann. 2007. Improved Forecasts of Higher-Order Comoments
and Implications for Portfolio Selection. EDHEC Risk and Asset Management Research Centre
working paper.
See Also
CoMoments
Examples
data(managers)
Description
To calculate Burke ratio we take the difference between the portfolio return and the risk free rate
and we divide it by the square root of the sum of the square of the drawdowns. To calculate the
modified Burke ratio we just multiply the Burke ratio by the square root of the number of datas.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf the risk free rate
modified a boolean to decide which ratio to calculate between Burke ratio and modified
Burke ratio.
... any other passthru parameters
Details
rP − rF
BurkeRatio = qP
d 2
t=1 Dt
rP − rF
M odif iedBurkeRatio = qP
d Dt 2
t=1 n
where n is the number of observations of the entire series, d is number of drawdowns, rP is the
portfolio return, rF is the risk free rate and Dt the tth drawdown.
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.90-91
CalmarRatio 27
Examples
data(portfolio_bacon)
print(BurkeRatio(portfolio_bacon[,1])) #expected 0.74
print(BurkeRatio(portfolio_bacon[,1], modified = TRUE)) #expected 3.65
data(managers)
print(BurkeRatio(managers['1996']))
print(BurkeRatio(managers['1996',1]))
print(BurkeRatio(managers['1996'], modified = TRUE))
print(BurkeRatio(managers['1996',1], modified = TRUE))
Description
Both the Calmar and the Sterling ratio are the ratio of annualized return over the absolute value of
the maximum drawdown of an investment. The Sterling ratio adds an excess risk measure to the
maximum drawdown, traditionally and defaulting to 10%.
Usage
CalmarRatio(R, scale = NA)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
excess for Sterling Ratio, excess amount to add to the max drawdown, traditionally and
default .1 (10%)
Details
It is also traditional to use a three year return series for these calculations, although the functions
included here make no effort to determine the length of your series. If you want to use a subset of
your series, you’ll need to truncate or subset the input data to the desired length.
Many other measures have been proposed to do similar reward to risk ranking. It is the opinion
of this author that newer measures such as Sortino’s UpsidePotentialRatio or Favre’s modified
SharpeRatio are both “better” measures, and should be preferred to the Calmar or Sterling Ratio.
28 [Link]
Author(s)
Brian G. Peterson
References
Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004.
See Also
[Link],
maxDrawdown,
[Link],
UpsidePotentialRatio
Examples
data(managers)
CalmarRatio(managers[,1,drop=FALSE])
CalmarRatio(managers[,1:6])
SterlingRatio(managers[,1,drop=FALSE])
SterlingRatio(managers[,1:6])
Description
This is a wrapper for calculating a single factor model (CAPM) alpha.
Usage
[Link](Ra, Rb, Rf = 0)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
Details
"Alpha" purports to be a measure of a manager’s skill by measuring the portion of the managers
returns that are not attributable to "Beta", or the portion of performance attributable to a benchmark.
While the classical CAPM has been almost completely discredited by the literature, it is an example
of a simple single factor model, comparing an asset to any arbitrary benchmark.
[Link] 29
Author(s)
Peter Carl
References
Sharpe, W.F. Capital Asset Prices: A theory of market equilibrium under conditions of risk. Journal
of finance, vol 19, 1964, 425-442.
Ruppert, David. Statistics and Finance, an Introduction. Springer. 2004.
See Also
[Link] [Link]
Examples
Description
The single factor model or CAPM Beta is the beta of an asset to the variance and covariance of an
initial portfolio. Used to determine diversification potential.
30 [Link]
Usage
[Link](Ra, Rb, Rf = 0)
[Link](Ra, Rb, Rf = 0)
[Link](Ra, Rb, Rf = 0)
TimingRatio(Ra, Rb, Rf = 0)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
Details
This function uses a linear intercept model to achieve the same results as the symbolic model used
by BetaCoVariance
Ruppert(2004) reports that this equation will give the estimated slope of the linear regression of Ra
on Rb and that this slope can be used to determine the risk premium or excess expected return (see
Eq. 7.9 and 7.10, p. 230-231).
Two other functions apply the same notion of best fit to positive and negative market returns, sep-
arately. The [Link] is a regression for only positive market returns, which can be used
to understand the behavior of the asset or portfolio in positive or ’bull’ markets. Alternatively,
[Link] provides the calculation on negative market returns.
The TimingRatio may help assess whether the manager is a good timer of asset allocation deci-
sions. The ratio, which is calculated as
β+
T imingRatio =
β−
is best when greater than one in a rising market and less than one in a falling market.
While the classical CAPM has been almost completely discredited by the literature, it is an example
of a simple single factor model, comparing an asset to any arbitrary benchmark.
Author(s)
Peter Carl
[Link] 31
References
Sharpe, W.F. Capital Asset Prices: A theory of market equilibrium under conditions of risk. Journal
of finance, vol 19, 1964, 425-442.
Ruppert, David. Statistics and Finance, an Introduction. Springer. 2004.
Bacon, Carl. Practical portfolio performance measurement and attribution. Wiley. 2004.
See Also
BetaCoVariance [Link] [Link]
Examples
data(managers)
[Link](managers[,1,drop=FALSE],
managers[,8,drop=FALSE],
Rf=.035/12)
[Link](managers[,1,drop=FALSE],
managers[,8,drop=FALSE],
Rf = managers[,10,drop=FALSE])
[Link](managers[,1:6],
managers[,8,drop=FALSE],
Rf=.035/12)
[Link](managers[,1:6],
managers[,8,drop=FALSE],
Rf = managers[,10,drop=FALSE])
[Link](managers[,1:6],
managers[,8:7,drop=FALSE],
Rf=.035/12)
[Link](managers[,1:6],
managers[,8:7,drop=FALSE],
Rf = managers[,10,drop=FALSE])
[Link](managers[, "HAM2", drop=FALSE],
managers[, "SP500 TR", drop=FALSE],
Rf = managers[, "US 3m TR", drop=FALSE])
[Link](managers[, "HAM2", drop=FALSE],
managers[, "SP500 TR", drop=FALSE],
Rf = managers[, "US 3m TR", drop=FALSE])
[Link](managers[, "HAM2", drop=FALSE],
managers[, "SP500 TR", drop=FALSE],
Rf = managers[, "US 3m TR", drop=FALSE])
TimingRatio(managers[, "HAM2", drop=FALSE],
managers[, "SP500 TR", drop=FALSE],
Rf = managers[, "US 3m TR", drop=FALSE])
[Link](managers[, "HAM2", drop=FALSE],
managers[, "SP500 TR", drop=FALSE],
Rf = managers[, "US 3m TR", drop=FALSE],
fit="conditional",
main="Conditional Beta")
32 [Link]
[Link] utility functions for single factor (CAPM) CML, SML, and
RiskPremium
Description
The Capital Asset Pricing Model, from which the popular SharpeRatio is derived, is a theory of
market equilibrium. These utility functions provide values for various measures proposed in the
CAPM.
Usage
[Link](Rb, Rf = 0)
[Link](Ra, Rb, Rf = 0)
[Link](Ra, Rf = 0)
[Link](Rb, Rf = 0)
Arguments
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Details
At it’s core, the CAPM is a single factor linear model. In light of the general ustility and wide use of
single factor model, all functions in the CAPM suite will also be available with SFM (single factor
model) prefixes.
The CAPM provides a justification for passive or index investing by positing that assets that are not
on the efficient frontier will either rise or lower in price until they are on the efficient frontier of the
market portfolio.
The CAPM Risk Premium on an investment is the measure of how much the asset’s performance
differs from the risk free rate. Negative Risk Premium generally indicates that the investment is a
bad investment, and the money should be allocated to the risk free asset or to a different asset with
a higher risk premium.
The Capital Market Line relates the excess expected return on an efficient market portfolio to it’s
Risk. The slope of the CML is the Sharpe Ratio for the market portfolio. The Security Market line
is constructed by calculating the line of Risk Premium over [Link]. For the benchmark asset
this will be 1 over the risk premium of the benchmark asset. The CML also describes the only path
allowed by the CAPM to a portfolio that outperforms the efficient frontier: it describes the line of
reward/risk that a leveraged portfolio will occupy. So, according to CAPM, no portfolio constructed
of the same assets can lie above the CML.
[Link] 33
Probably the most complete criticism of CAPM in actual practice (as opposed to structural or theory
critiques) is that it posits a market equilibrium, but is most often used only in a partial equilibrium
setting, for example by using the S\&P 500 as the benchmark asset. A better method of using and
testing the CAPM would be to use a general equilibrium model that took global assets from all asset
classes into consideration.
Chapter 7 of Ruppert(2004) gives an extensive overview of CAPM, its assumptions and deficiencies.
[Link] is the premium returned to the investor over the risk free asset
(Ra − Rf )
[Link] calculates the expected return of the asset against the benchmark Capital Market Line
[Link] calculates the slope of the Capital Market Line for looking at how a particular asset
compares to the CML
[Link] calculates the slope of the Security Market Line for looking at how a particular
asset compares to the SML created by the benchmark
Author(s)
Brian G. Peterson
References
See Also
Examples
data(managers)
[Link](managers[,"SP500 TR",drop=FALSE], managers[,10,drop=FALSE])
[Link](managers[,"HAM1",drop=FALSE], managers[,"SP500 TR",drop=FALSE], Rf=0)
[Link](managers[,"SP500 TR",drop=FALSE], Rf=0)
[Link](managers[,"HAM1",drop=FALSE], Rf=0)
[Link](managers[,"SP500 TR",drop=FALSE], Rf=0)
# should create plots like in Ruppert 7.1 7.2
34 [Link]
Description
CAPM is estimated assuming that betas and alphas change over time. It is assumed that the market
prices of securities fully reflect readily available and public information. A matrix of market infor-
mation variables, Z measures this information. Possible variables in Z could be the divident yield,
Tresaury yield, etc. The betas of stocks and managed portfolios are allowed to change with market
conditions:
Usage
[Link](Ra, Rb, Rf = 0, Z, lags = 1, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of the asset returns
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of the benchmark
asset return
Rf risk free rate, in same period as your returns
Z an xts, vector, matrix, data frame, timeSeries or zoo object of k variables that
reflect public information
lags number of lags before the current period on which the alpha and beta are condi-
tioned
... any other passthrough parameters
Details
where zt = Zt − E[Z]
- a normalized vector of the deviations of Zt , Bp
- a vector with the same dimension as Zt .
The coefficient b0p can be interpreted as the "average beta" or the beta when all infromation vari-
ables are at their means. The elements of Bp measure the sensitivity of the conditional beta to the
deviations of the Zt from their means. In the similar way the time-varying conditional alpha is
modeled:
αpt = αp (zt ) = α0p + A0p zt
The modified regression is therefore:
Author(s)
Andrii Babii
References
J. Christopherson, D. Carino, W. Ferson. Portfolio Performance Measurement and Benchmarking.
2009. McGraw-Hill. Chapter 12.
Wayne E. Ferson and Rudi Schadt, "Measuring Fund Strategy and Performance in Changing Eco-
nomic Conditions," Journal of Finance, vol. 51, 1996, pp.425-462
See Also
[Link]
Examples
data(managers)
[Link](managers[,1,drop=FALSE], managers[,8,drop=FALSE],
Rf=.035/12, Z=managers[, 9:10])
[Link](managers[80:120,1:6], managers[80:120,7,drop=FALSE],
Rf=managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10])
[Link](managers[80:120,1:6], managers[80:120,8:7],
managers[80:120,10,drop=FALSE], Z=managers[80:120, 9:10])
Description
The regression epsilon is an error term measuring the vertical distance between the return predicted
by the equation and the real result.
Usage
[Link](Ra, Rb, Rf = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
36 [Link]
Details
r = rp − αr − βr ∗ b
where αr is the regression alpha, βr is the regression beta, rp is the portfolio return and b is the
benchmark return
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.71
Examples
data(portfolio_bacon)
print([Link](portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.013
data(managers)
print([Link](managers['1996',1], managers['1996',8]))
print([Link](managers['1996',1:5], managers['1996',8]))
Description
The Jensen’s alpha is the intercept of the regression equation in the Capital Asset Pricing Model
and is in effect the exess return adjusted for systematic risk.
Usage
[Link](Ra, Rb, Rf = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
CDD 37
Details
α = rp − rf − βp ∗ (b − rf )
where rf is the risk free rate, βr is the regression beta, rp is the portfolio return and b is the
benchmark return
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.72
Examples
data(portfolio_bacon)
print([Link](portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.014
data(managers)
print([Link](managers['1996',1], managers['1996',8]))
print([Link](managers['1996',1:5], managers['1996',8]))
Description
For some confidence level p, the conditional drawdown is the the mean of the worst p% drawdowns.
Usage
CDD(R, weights = NULL, geometric = TRUE, invert = TRUE, p = 0.95, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
weights portfolio weighting vector, default NULL, see Details
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
invert TRUE/FALSE whether to invert the drawdown measure. see Details.
p confidence level for calculation, default p=0.95
... any other passthru parameters
38 [Link]
Author(s)
Brian G. Peterson
References
Chekhlov, A., Uryasev, S., and M. Zabarankin. Portfolio Optimization With Drawdown Con-
straints. B. Scherer (Ed.) Asset and Liability Management Tools, Risk Books, London, 2003
[Link]
See Also
ES maxDrawdown
Examples
data(edhec)
t(round(CDD(edhec),4))
Description
Creates an ACF chart or a two-panel plot with the ACF and PACF set to some specific defaults.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
maxlag the number of lags to calculate for, optional
elementcolor the color to use for chart elements, defaults to "gray"
main title of the plot; uses the column name by default.
... any other passthru parameters
[Link] 39
Note
Inspired by the website: [Link] "...here’s an R function
that will plot the ACF and PACF of a time series at the same time on the SAME SCALE, and it
leaves out the zero lag in the ACF: acf2.R. If your time series is in x and you want the ACF and
PACF of x to lag 50, the call to the function is acf2(x,50). The number of lags is optional, so acf2(x)
will use a default number of lags [sqrt(n) + 10, where n is the number of observations]."
That description made a lot of sense, so it’s implemented here for both the ACF alone and the ACF
with the PACF.
Author(s)
Peter Carl
See Also
plot
Examples
data(edhec)
[Link](edhec[,1,drop=FALSE])
Description
A wrapper to create a chart of periodic returns in a bar chart. This is a difficult enough graph to read
that it doesn’t get much use. Still, it is useful for viewing a single set of data.
Usage
[Link](R, [Link] = NULL, colorset = (1:12), ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center
colorset color palette to use, set by default to rational choices
... any other passthru parameters, see plot
main sets the title text, such as in [Link]
[Link] sets the legend text size, such as in [Link]
[Link] sets the title text size, such as in [Link]
40 [Link]
Details
This is really a wrapper for [Link], so several other attributes can also be passed.
Creates a plot of time on the x-axis and vertical lines for each period to indicate value on the y-axis.
Author(s)
Peter Carl
See Also
[Link]
plot
Examples
data(edhec)
[Link](edhec[,"Funds of Funds"], main="Monthly Returns")
Description
Plots the periodic returns as a bar chart overlayed with a risk metric calculation.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
width periods specified for rolling-period calculations. Note that VaR, ES, and Std
Dev with width=0 are calculated from the start of the timeseries
gap numeric number of periods from start of series to use to train risk calculation
methods Used to select the risk parameter of trailing width returns to use: May be any
of:
• none - does not add a risk line,
• ModifiedVaR - uses Cornish-Fisher modified VaR,
• GaussianVaR - uses traditional Value at Risk,
• HistoricalVaR - calculates historical Value at Risk,
• ModifiedES - uses Cornish-Fisher modified Expected Shortfall,
• GaussianES - uses traditional Expected Shortfall,
• HistoricalES - calculates historical Expected Shortfall,
• StdDev - per-period standard deviation
p confidence level for VaR or ModifiedVaR calculation, default is .99
clean the method to use to clean outliers from return data prior to risk metric estima-
tion. See [Link] and VaR for more detail
all if TRUE, calculates risk lines for each column given in R. If FALSE, only cal-
culates the risk line for the first column
... any other passthru parameters to [Link]
[Link] if TRUE and a method for ’clean’ is specified, overlays the actual data with the
"cleaned" data. See [Link] for more detail
[Link]
if TRUE, shows a line across the timeseries at the value of the most recent VaR
estimate, to help the reader evaluate the number of exceptions thus far
[Link] if TRUE and the metric is symmetric, this will show the metric’s positive values
as well as negative values, such as for method "StdDev".
[Link] if TRUE, show the final (out of sample) value
[Link]
if TRUE, show the per-period returns using green and red bars for positive and
negative returns
[Link] legend location, such as in [Link]
ylim set the y-axis limit, same as in plot
lwd set the line width, same as in plot
colorset color palette to use, such as in [Link]
lty set the line type, same as in plot
ypad adds a numerical padding to the y-axis to keep the data away when [Link]="bottom".
See examples below.
[Link] sets the legend text size, such as in [Link]
main sets the title text, such as in [Link]
42 [Link]
Details
Note that StdDev and VaR are symmetric calculations, so a high and low measure will be plotted.
ModifiedVaR, on the other hand, is assymetric and only a lower bound will be drawn.
Creates a plot of time on the x-axis and vertical lines for each period to indicate value on the y-axis.
Overlays a line to indicate the value of a risk metric calculated at that time period.
[Link] places multile bar charts in a single graphic, with associated risk measures
Author(s)
Peter Carl
See Also
[Link]
plot
ES
VaR
[Link]
Examples
## Not run: # not run on CRAN because of example time
data(managers)
# plain
[Link](managers[,1,drop=FALSE], main="Monthly Returns")
# cleaned up a bit
[Link] 43
[Link](managers[,1,drop=FALSE],
methods=c("HistoricalVaR", "ModifiedVaR", "GaussianVaR"),
lwd=2, ypad=.01,
main="... with Padding for Bottom Legend")
## End(Not run)
Description
A wrapper to create box and whiskers plot with some defaults useful for comparing distributions.
Usage
[Link](R, names = TRUE, [Link] = FALSE, [Link] = c(NULL, "mean",
"median", "variance"), colorset = "black", [Link] = "red",
[Link] = 1, [Link] = "|", [Link] = 1,
[Link] = NULL, [Link] = TRUE, [Link] = FALSE,
xlab = "Return", main = "Return Distribution Comparison",
[Link] = "darkgray", ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
names logical. if TRUE, show the names of each series
[Link] logical. default FALSE. if TRUE use method derived for Tufte for limiting
chartjunk
[Link] one of "NULL", "mean", "median", "variance"
colorset color palette to use, set by default to rational choices
[Link] draws the symbols described in [Link],[Link],[Link]
in the color specified
44 [Link]
Details
We have also provided controls for all the symbols and lines in the chart. One default, set by
[Link]=TRUE, will strip chartjunk and draw a Boxplot per recommendations by Edward Tufte. It
can also be useful when comparing several series to sort them in order of ascending or descending
"mean", "median", "variance" by use of [Link] and [Link]=TRUE.
Value
Author(s)
Peter Carl
References
Tufte, Edward R. The Visual Display of Quantitative Information. Graphics Press. 1983. p. 124-129
See Also
boxplot
Examples
data(edhec)
[Link](edhec)
[Link](edhec,[Link]=TRUE)
[Link] 45
Description
Scatter plot of Up Capture versus Down Capture against a benchmark
Usage
[Link](Ra, Rb, main = "Capture Ratio", [Link] = TRUE,
xlab = "Downside Capture", ylab = "Upside Capture", colorset = 1,
symbolset = 1, [Link] = NULL, xlim = NULL, ylim = NULL,
[Link] = 1, [Link] = 0.8, [Link] = 1, [Link] = 1,
[Link] = "darkgray", [Link] = "darkgray", ...)
Arguments
Ra Returns to test, e.g., the asset to be examined
Rb Returns of a benchmark to compare the asset with
main Set the chart title, same as in plot
[Link] Plots the row name with the data point. Default TRUE. Can be removed by
setting it to NULL
xlab Set the x-axis label, as in plot
ylab Set the y-axis label, as in plot
colorset Color palette to use, set by default to "black"
symbolset From pch in plot. Submit a set of symbols to be used in the same order as the
data sets submitted
[Link] Places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
xlim set the x-axis limit, same as in plot
ylim set the y-axis limit, same as in plot
[Link] The magnification to be used for sizing the legend relative to the current setting
of ’cex’.
[Link] The magnification to be used for axis annotation relative to the current setting
of ’cex’, same as in plot.
[Link] The magnification to be used for sizing the title relative to the current setting of
’cex’.
[Link] The magnification to be used for x and y labels relative to the current setting of
’cex’.
[Link] Specify the color of the box, axes, and other chart elements. Default is "dark-
gray"
[Link]
Specify the color of the benchmark reference and crosshairs. Default is "dark-
gray"
... Any other passthru parameters to plot
46 [Link]
Details
Scatter plot shows the coordinates of each set of returns’ Up and Down Capture against a bench-
mark. The benchmark value is by definition plotted at (1,1) with solid crosshairs. A diagonal dashed
line with slope equal to 1 divides the plot into two regions: above that line the UpCapture exceeds
the DownCapture, and vice versa.
Author(s)
Peter Carl
See Also
plot,
par,
UpDownRatios,
[Link]
Examples
data(managers)
[Link](managers[,1:6], managers[,7,drop=FALSE])
Description
Visualization of a Correlation Matrix. On top the (absolute) value of the correlation plus the result
of the [Link] as stars. On bottom, the bivariate scatterplots, with a fitted line
Usage
[Link](R, histogram = TRUE, method = c("pearson", "kendall",
"spearman"), ...)
Arguments
R data for the x axis, can take matrix,vector, or timeseries
histogram TRUE/FALSE whether or not to display a histogram
method a character string indicating which correlation coefficient (or covariance) is to
be computed. One of "pearson" (default), "kendall", or "spearman", can be ab-
breviated.
... any other passthru parameters into pairs
[Link] 47
Note
based on plot at originally found at [Link]/graphiques/sources/source_137.R
Author(s)
Peter Carl
See Also
[Link]
Examples
data(managers)
[Link](managers[,1:8], histogram=TRUE, pch="+")
Description
Chart that cumulates the periodic returns given and draws a line graph of the results as a "wealth
index".
Usage
[Link](R, [Link] = FALSE, geometric = TRUE,
[Link] = NULL, colorset = (1:12), begin = c("first", "axis"), ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
[Link] if [Link] is TRUE, shows the "value of $1", starting the cumulation of
returns at 1 rather than zero
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
colorset color palette to use, set by default to rational choices
begin Align shorter series to:
• first - prior value of the first column given for the reference or longer series
or,
• axis - the initial value (1 or zero) of the axis.
... any other passthru parameters
48 [Link]
Details
Cumulates the return series and displays either as a wealth index or as cumulative returns.
Author(s)
Peter Carl
References
Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004.
See Also
[Link]
plot
Examples
data(edhec)
[Link](edhec[,"Funds of Funds"],main="Cumulative Returns")
[Link](edhec[,"Funds of Funds"],[Link]=TRUE, main="Growth of $1")
data(managers)
[Link](managers,main="Cumulative Returns",begin="first")
[Link](managers,main="Cumulative Returns",begin="axis")
Description
A time series chart demonstrating drawdowns from peak equity attained through time, calculated
from periodic returns.
Usage
[Link](R, geometric = TRUE, [Link] = NULL, colorset = (1:12),
...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
[Link] 49
Details
Any time the cumulative returns dips below the maximum cumulative returns, it’s a drawdown.
Drawdowns are measured as a percentage of that maximum cumulative return, in effect, measured
from peak equity.
Author(s)
Peter Carl
References
Bacon, C. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 88
See Also
plot
[Link]
findDrawdowns
sortDrawdowns
maxDrawdown
[Link]
[Link]
Examples
data(edhec)
[Link](edhec[,c(1,2)],
main="Drawdown from Peak Equity Attained",
[Link]="bottomleft")
Description
Creates an emperical cumulative distribution function (ECDF) overlaid with a cumulative distribu-
tion function (CDF)
Usage
[Link](R, main = "Empirical CDF", xlab = "x", ylab = "F(x)",
colorset = c("black", "#005AFF"), lwd = 1, lty = c(1, 1),
[Link] = "darkgray", xaxis = TRUE, yaxis = TRUE, ...)
50 [Link]
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
main set the chart title, same as in plot
xlab set the x-axis label, same as in plot
ylab set the y-axis label, same as in plot
colorset color palette to use, defaults to c("black", "\#005AFF"), where first value is used
to color the step function and the second color is used for the fitted normal
lwd set the line width, same as in plot
lty set the line type, same as in plot
[Link] specify the color of chart elements. Default is "darkgray"
xaxis if true, draws the x axis
yaxis if true, draws the y axis
... any other passthru parameters to plot
Details
The empirical cumulative distribution function (ECDF for short) calculates the fraction of obser-
vations less or equal to a given value. The resulting plot is a step function of that fraction at each
observation. This function uses ecdf and overlays the CDF for a fitted normal function as well.
Inspired by a chart in Ruppert (2004).
Author(s)
Peter Carl
References
Ruppert, David. Statistics and Finance, an Introduction. Springer. 2004. Ch. 2 Fig. 2.5
See Also
plot, ecdf
Examples
data(edhec)
[Link](edhec[, 1, drop=FALSE])
[Link] 51
Description
Creates a time series plot where events given by a set of dates are aligned, with the adjacent prior
and posterior time series data plotted in order. The x-axis is time, but relative to the date specified,
e.g., number of months preceeding or following the events.
Usage
[Link](R, dates, prior = 12, post = 12, main = NULL, xlab = NULL,
...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
dates a list of dates (e.g., c("09/03","05/06")) formatted the same as in R. This
function matches the re-formatted row or index names (dates) with the given
list, so to get a match the formatting needs to be correct.
prior the number of periods to plot prior to the event. Interpreted as a positive number.
post the number of periods to plot following to the event. Interpreted as a positive
number.
main set the chart title, same as in plot
xlab set the x-axis label, same as in plot
... any other passthru parameters to the plot function
Details
This is a chart that is commonly used for event studies in econometrics, usually with recession
dates, to demonstrate the path of a time series going into and coming out of an event. The time axis
is simply the number of periods prior and following the event, and each line represents a different
event. Note that if time periods are close enough together and the window shown is wide enough,
the data will appear to repeat. That can be confusing, but the function does not currently allow for
different windows around each event.
Author(s)
Peter Carl
See Also
[Link],
plot,
par
52 [Link]
Examples
## Not run:
data(managers)
n = [Link](managers[,2,drop=FALSE])
[Link](Drawdowns(managers[,2,drop=FALSE]),
dates = n$Trough,
prior=max([Link](n$"To Trough")),
post=max([Link](n$Recovery)),
lwd=2, colorset=redfocus, [Link]=NULL,
main = "Worst Drawdowns")
## End(Not run)
Description
Create a histogram of returns, with optional curve fits for density and normal. This is a wrapper
function for hist, see the help for that function for additional arguments you may wish to pass in.
Usage
[Link](R, breaks = "FD", main = NULL, xlab = "Returns",
ylab = "Frequency", methods = c("none", "[Link]", "[Link]",
"[Link]", "[Link]", "[Link]", "[Link]", "[Link]", "[Link]"),
[Link] = TRUE, colorset = c("lightgray", "#00008F", "#005AFF",
"#23FFDC", "#ECFF13", "#FF4A00", "#800000"), [Link] = "white",
lwd = 2, xlim = NULL, ylim = NULL, [Link] = "darkgray",
[Link] = NULL, [Link] = NULL, [Link] = 0.7,
[Link] = "darkgray", probability = FALSE, p = 0.95,
[Link] = 0.8, [Link] = 0.8, [Link] = 1, [Link] = 1,
xaxis = TRUE, yaxis = TRUE, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
breaks one of:
• a vector giving the breakpoints between histogram cells,
• a single number giving the number of cells for the histogram,
• a character string naming an algorithm to compute the number of cells (see
‘Details’),
• a function to compute the number of cells.
For the last three the number is a suggestion only. see hist for details, default
"FD"
main set the chart title, same as in plot
[Link] 53
Details
The default for breaks is "FD". Other names for which algorithms are supplied are "Sturges"
(see [Link]), "Scott", and "FD" / "Freedman-Diaconis" (with corresponding functions
[Link] and [Link]). Case is ignored and partial matching is used. Alternatively, a
function can be supplied which will compute the intended number of breaks as a function of R.
Note
Code inspired by a chart on:
[Link]
Author(s)
Peter Carl
See Also
hist
Examples
data(edhec)
[Link](edhec[,'Equity Market Neutral',drop=FALSE])
methods = c("[Link]","[Link]","[Link]","[Link]"))
Description
Plot the return data against any theoretical distribution.
Usage
[Link](R, distribution = "norm", ylab = NULL,
xlab = paste(distribution, "Quantiles"), main = NULL, las = par("las"),
envelope = FALSE, labels = FALSE, col = c(1, 4), lwd = 2, pch = 1,
cex = 1, line = c("quartiles", "robust", "none"),
[Link] = "darkgray", [Link] = 0.8, [Link] = 0.8,
[Link] = 1, [Link] = 1, xaxis = TRUE, yaxis = TRUE, ylim = NULL,
...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
distribution root name of comparison distribution - e.g., ’norm’ for the normal distribution;
’t’ for the t-distribution. See examples for other ideas.
ylab set the y-axis label, as in plot
xlab set the x-axis label, as in plot
main set the chart title, same as in plot
las set the direction of axis labels, same as in plot
envelope confidence level for point-wise confidence envelope, or FALSE for no envelope.
labels vector of point labels for interactive point identification, or FALSE for no labels.
col color for points and lines; the default is the second entry in the current color
palette (see ’palette’ and ’par’).
lwd set the line width, as in plot
pch symbols to use, see also plot
cex symbols to use, see also plot
line ’quartiles’ to pass a line through the quartile-pairs, or ’robust’ for a robust-
regression line; the latter uses the ’rlm’ function in the ’MASS’ package. Spec-
ifying ’line = "none"’ suppresses the line.
[Link] provides the color for drawing chart elements, such as the box lines, axis lines,
etc. Default is "darkgray"
[Link] The magnification to be used for axis annotation relative to the current setting
of ’cex’
56 [Link]
[Link] The magnification to be used for sizing the legend relative to the current setting
of ’cex’
[Link] The magnification to be used for x- and y-axis labels relative to the current
setting of ’cex’
[Link] The magnification to be used for the main title relative to the current setting of
’cex’.
xaxis if true, draws the x axis
yaxis if true, draws the y axis
ylim set the y-axis limits, same as in plot
... any other passthru parameters to the distribution function
Details
A Quantile-Quantile (QQ) plot is a scatter plot designed to compare the data to the theoretical distri-
butions to visually determine if the observations are likely to have come from a known population.
The empirical quantiles are plotted to the y-axis, and the x-axis contains the values of the theorical
model. A 45-degree reference line is also plotted. If the empirical data come from the population
with the choosen distribution, the points should fall approximately along this reference line. The
larger the departure from the reference line, the greater the evidence that the data set have come
from a population with a different distribution.
Author(s)
John Fox, ported by Peter Carl
References
main code forked/borrowed/ported from the excellent:
Fox, John (2007) car: Companion to Applied Regression
[Link]
See Also
qqplot
[Link]
plot
Examples
library(MASS)
data(managers)
#layout(rbind(c(1,2),c(3,4)))
## Not run:
# Panel 3, Skew-T distribution
library(sn)
fit = [Link](y=x)
[Link](x, main = "Skew T Distribution", envelope=0.95,
distribution = 'st', location = fit$dp[[1]],
scale = fit$dp[[2]], shape = fit$dp[[3]], df=fit$dp[[4]])
## End(Not run)
#end examples
Description
Uses a scatterplot to display the relationship of a set of returns to a market benchmark. Fits a linear
model and overlays the resulting model. Also overlays a Loess line for comparison.
Usage
[Link](Ra, Rb, Rf = 0, [Link] = FALSE,
[Link] = TRUE, main = "Title", ylab = NULL, xlab = NULL,
xlim = NA, colorset = 1:12, symbolset = 1:12,
[Link] = "darkgray", [Link] = NULL, ylog = FALSE,
fit = c("loess", "linear", "conditional", "quadratic"), span = 2/3,
degree = 1, family = c("symmetric", "gaussian"), ylim = NA,
evaluation = 50, [Link] = 0.8, cex = 0.8, lwd = 2, ...)
Arguments
Ra a vector of returns to test, e.g., the asset to be examined
Rb a matrix, [Link], or timeSeries of benchmark(s) to test the asset against
58 [Link]
Author(s)
Peter Carl
References
Chapter 7 of Ruppert(2004) gives an extensive overview of CAPM, its assumptions and deficiencies.
See Also
plot
[Link] 59
Examples
data(managers)
[Link](managers[, 1:2, drop = FALSE],
managers[, 8, drop = FALSE],
Rf = managers[, 10, drop = FALSE],
[Link] = TRUE, fit = c("loess", "linear"),
[Link] = "topleft")
[Link]
relative performance chart between multiple return series
Description
Plots a time series chart that shows the ratio of the cumulative performance for two assets at each
point in time and makes periods of under- or out-performance easier to see.
Usage
[Link](Ra, Rb, main = "Relative Performance",
xaxis = TRUE, colorset = (1:12), [Link] = NULL, ylog = FALSE,
elementcolor = "darkgray", lty = 1, [Link] = 0.7, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
main set the chart title, same as in plot
xaxis if true, draws the x axis
colorset color palette to use, set by default to rational choices
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
ylog TRUE/FALSE set the y-axis to logarithmic scale, similar to plot, default FALSE
elementcolor provides the color for drawing less-important chart elements, such as the box
lines, axis lines, etc. replaces darken
lty set the line type, same as in plot
[Link] the magnification to be used for sizing the legend relative to the current setting
of ’cex’.
... any other passthru parameters
60 [Link]
Details
To show under- and out-performance through different periods of time, a time series view is more
helpful. The value of the chart is less important than the slope of the line. If the slope is positive,
the first asset (numerator) is outperforming the second, and vice versa. May be used to look at the
returns of a fund relative to each member of the peer group and the peer group index. Alternatively,
it might be used to assess the peers individually against an asset class or peer group index.
Author(s)
Peter Carl
See Also
[Link]
Examples
data(managers)
[Link](managers[, 1:6, drop=FALSE],
managers[, 8, drop=FALSE],
colorset=rich8equal, [Link]="bottomright",
main="Relative Performance to S&P")
[Link]
scatter chart of returns vs risk for comparing multiple instruments
Description
A wrapper to create a scatter chart of annualized returns versus annualized risk (standard deviation)
for comparing manager performance. Also puts a box plot into the margins to help identify the
relative performance quartile.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
main set the chart title, same as in plot
[Link] plots the row name with the data point. default TRUE. Can be removed by
setting it to NULL
xlab set the x-axis label, as in plot
ylab set the y-axis label, as in plot
method if set as "calc", then the function will calculate values from the set of returns
passed in. If method is set to "nocalc" then we assume that R is a column of
return and a column of risk (e.g., annualized returns, annualized risk), in that
order. Other method cases may be set for different risk/return calculations.
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
[Link] this draws a Sharpe ratio line that indicates Sharpe ratio levels of c(1,2,3).
Lines are drawn with a y-intercept of the risk free rate and the slope of the
appropriate Sharpe ratio level. Lines should be removed where not appropriate
(e.g., [Link] = NULL).
[Link] TRUE/FALSE adds a boxplot summary of the data on the axis
colorset color palette to use, set by default to rational choices
symbolset from pch in plot, submit a set of symbols to be used in the same order as the
data sets submitted
[Link] provides the color for drawing chart elements, such as the box lines, axis lines,
etc. Default is "darkgray"
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
xlim set the x-axis limit, same as in plot
ylim set the y-axis limit, same as in plot
[Link] The magnification to be used for sizing the legend relative to the current setting
of ’cex’.
[Link] The magnification to be used for axis annotation relative to the current setting
of ’cex’, same as in plot.
[Link] The magnification to be used for sizing the title relative to the current setting of
’cex’.
[Link] The magnification to be used for x and y labels relative to the current setting of
’cex’.
... any other passthru parameters to plot
Note
Code inspired by a chart on: [Link]
62 [Link]
Author(s)
Peter Carl
Examples
data(edhec)
[Link](edhec, Rf = .04/12)
[Link](edhec, Rf = .04/12, [Link] = TRUE)
[Link]
chart rolling correlation fo multiple assets
Description
A wrapper to create a chart of rolling correlation metrics in a line chart
Usage
[Link](Ra, Rb, width = 12, xaxis = TRUE,
[Link] = NULL, colorset = (1:12), ..., fill = NA)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
width number of periods to apply rolling function window over
xaxis if true, draws the x axis
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
colorset color palette to use, set by default to rational choices
... any other passthru parameters
fill a three-component vector or list (recycled otherwise) providing filling values at
the left/within/to the right of the data range. See the fill argument of [Link]
for details.
Details
The previous parameter [Link] has been replaced with fill; use fill = NA instead of [Link] = TRUE,
or fill = NULL instead of [Link] = FALSE.
Author(s)
Peter Carl
[Link] 63
Examples
Description
A wrapper to create a rolling mean return chart with 95
Usage
[Link](R, width = 12, xaxis = TRUE, ylim = NULL, lwd = c(2,
1, 1), ..., fill = NA)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
width number of periods to apply rolling function window over
xaxis if true, draws the x axis
ylim set the y-axis limit, same as in plot
lwd set the line width, same as in plot. Specified in order of the main line and the
two confidence bands.
... any other passthru parameters
fill a three-component vector or list (recycled otherwise) providing filling values at
the left/within/to the right of the data range. See the fill argument of [Link]
for details.
Details
The previous parameter [Link] has been replaced with fill; use fill = NA instead of [Link] = TRUE,
or fill = NULL instead of [Link] = FALSE.
Author(s)
Peter Carl
64 [Link]
Examples
data(edhec)
[Link](edhec[, 9, drop = FALSE])
[Link]
wrapper to create a chart of rolling performance metrics in a line chart
Description
A wrapper to create a chart of rolling performance metrics in a line chart
Usage
[Link](R, width = 12, FUN = "[Link]", ...,
ylim = NULL, main = NULL, fill = NA)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
width number of periods to apply rolling function window over
FUN any function that can be evaluated using a single set of returns (e.g., rolling
[Link] won’t work, but [Link] will)
... any other passthru parameters to plot or the function specified
ylim set the y-axis limit, same as in plot
main set the chart title, same as in plot
fill a three-component vector or list (recycled otherwise) providing filling values at
the left/within/to the right of the data range. See the fill argument of [Link]
for details.
Details
The parameter [Link] has been deprecated; use fill = NA instead of [Link] = TRUE, or
fill = NULL instead of [Link] = FALSE.
Author(s)
Peter Carl
See Also
[Link], rollapply
[Link] 65
Examples
data(edhec)
[Link](edhec[, 1:3], width = 24)
[Link](edhec[, 1:3],
FUN = 'mean', width = 24, colorset = rich8equal,
lwd = 2, [Link] = "topleft",
main = "Rolling 24-Month Mean Return")
[Link](edhec[, 1:3],
FUN = '[Link]', width = 24,
colorset = rich8equal, lwd = 2, [Link] = "topleft",
main = "Rolling 24-Month Sharpe Ratio")
[Link]
A wrapper to create charts of relative regression performance through
time
Description
A wrapper to create a chart of relative regression performance through time
Usage
[Link](Ra, Rb, width = 12, Rf = 0,
attribute = c("Beta", "Alpha", "R-Squared"), main = NULL, [Link] = TRUE,
...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
width number of periods to apply rolling function window over
Rf risk free rate, in same period as your returns
attribute one of "Beta","Alpha","R-Squared" for which attribute to show
main set the chart title, same as in plot
[Link] TRUE/FALSE If TRUE it adds any times that would not otherwise have been in
the result with a value of NA. If FALSE those times are dropped.
... any other passthru parameters to [Link]
66 [Link]
Details
A group of charts in [Link] displays alpha, beta, and R-squared estimates in
three aligned charts in a single device.
The attribute parameter is probably the most confusing. In mathematical terms, the different choices
yield the following:
Alpha - shows the y-intercept
Beta - shows the slope of the regression line
R-Squared - shows the degree of fit of the regression to the data
[Link] uses rq rather than lm for the regression, and may be more
robust to outliers in the data.
Note
Most inputs are the same as "plot" and are principally included so that some sensible defaults could
be set.
Author(s)
Peter Carl
See Also
lm
rq
Examples
Description
Draws a scatter chart. This is another chart "primitive", since it only contains a set of sensible
defaults.
Usage
[Link](x, y, [Link] = TRUE, main = "Title", ylab = NULL,
xlab = NULL, xlim = NULL, ylim = NULL, colorset = 1, symbolset = 1,
[Link] = "darkgray", [Link] = 0.8, [Link] = 0.8,
[Link] = 1, [Link] = 1, ...)
Arguments
x data for the x axis, can take matrix,vector, or timeseries
y data for the y axis, can take matrix,vector, or timeseries
[Link] if true, draws a grid aligned with the points on the x and y axes
main set the chart title, same as in plot
ylab set the y-axis label, as in plot
xlab set the x-axis label, as in plot
xlim set the x-axis limit, same as in plot
ylim set the y-axis limit, same as in plot
colorset color palette to use, set by default to rational choices
symbolset from pch in plot, submit a set of symbols to be used in the same order as the
data sets submitted
[Link] provides the color for drawing chart elements, such as the box lines, axis lines,
etc. Default is "darkgray"
[Link] The magnification to be used for axis annotation relative to the current setting
of ’cex’, same as in plot.
[Link] The magnification to be used for sizing the legend relative to the current setting
of ’cex’.
[Link] The magnification to be used for x- and y-axis labels relative to the current
setting of ’cex’
[Link] The magnification to be used for the main title relative to the current setting of
’cex’.
... any other passthru parameters
Note
Most inputs are the same as "plot" and are principally included so that some sensible defaults could
be set.
68 [Link]
Author(s)
Peter Carl
See Also
plot
Examples
## Not run:
data(edhec)
[Link](edhec[,1],edhec[,2])
## End(Not run)
Description
A chart that shows rolling calculations of annualized return and annualized standard deviation have
proceeded through time. Lines and dots are darker for more recent time periods.
Usage
[Link](R, Rf = 0, main = "Annualized Return and Risk",
[Link] = c("all", "lastonly", "firstandlast", "none"),
xlab = "Annualized Risk", ylab = "Annualized Return", [Link] = c(1,
2, 3), colorset = 1:12, symbolset = 16, [Link] = NULL,
xlim = NULL, ylim = NULL, width = 12, stepsize = 12, lty = 1,
lwd = 2, [Link] = 0.8, [Link] = 1, [Link] = 1, [Link] = 0.8,
[Link] = 0.8, [Link] = "darkgray", ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
main set the chart title, same as in plot
[Link] plots the row name with the data point. default TRUE. Can be removed by
setting it to NULL
xlab set the x-axis label, as in plot
ylab set the y-axis label, as in plot
[Link] this draws a Sharpe ratio line that indicates Sharpe ratio levels of c(1,2,3).
Lines are drawn with a y-intercept of the risk free rate and the slope of the
appropriate Sharpe ratio level. Lines should be removed where not appropriate
(e.g., [Link] = NULL).
[Link] 69
Author(s)
Peter Carl
References
~put references to the literature/web site here ~
See Also
[Link]
Examples
data(managers)
[Link](managers[,c("HAM2","SP500 TR"),drop=FALSE],
width=36, stepsize=12,
colorset=c('red','orange'),
70 [Link]
[Link]="firstandlast",
rf=.04/12,
main="Trailing 36-month Performance Calc'd Every 12 Months")
Description
This creates a stacked column chart with time on the horizontal axis and values in categories. This
kind of chart is commonly used for showing portfolio ’weights’ through time, although the function
will plot any values by category.
Usage
[Link](w, colorset = NULL, space = 0.2, [Link] = 0.8,
[Link] = 0.8, [Link] = 1, [Link] = 0.8, [Link] = 1,
xaxis = TRUE, [Link] = "under", [Link] = "darkgray",
unstacked = TRUE, xlab = "Date", ylab = "Value", ylim = NULL,
[Link] = "%b %y", [Link] = "auto", [Link] = TRUE,
las = 0, [Link] = NULL, ...)
Arguments
w a matrix, data frame or zoo object of values to be plotted. Rownames should
contain dates or period labels; column names should indicate categories. See
examples for detail.
colorset color palette to use, set by default to rational choices
space the amount of space (as a fraction of the average bar width) left before each bar,
as in barplot. Default is 0.2.
[Link] The magnification to be used for sizing the axis text relative to the current setting
of ’cex’, similar to plot.
[Link] The magnification to be used for sizing the legend relative to the current setting
of ’cex’, similar to plot.
[Link] The magnification to be used for x- and y-axis labels relative to the current
setting of ’cex’.
[Link] The magnification to be used for event line labels relative to the current setting
of ’cex’.
[Link] The magnification to be used for the chart title relative to the current setting of
’cex’.
xaxis If true, draws the x axis
[Link] 71
[Link] places a legend into a location on the chart similar to [Link]. The
default, "under," is the only location currently implemented for this chart. Use
’NULL’ to remove the legend.
[Link] provides the color for drawing less-important chart elements, such as the box
lines, axis lines, etc.
unstacked logical. If set to ’TRUE’ and only one row of data is submitted in ’w’, then the
chart creates a normal column chart. If more than one row is submitted, then
this is ignored. See examples below.
xlab the x-axis label, which defaults to ’NULL’.
ylab Set the y-axis label, same as in plot
ylim set the y-axis limit, same as in plot
[Link] Re-format the dates for the xaxis; the default is "%m/%y"
[Link] Should major tickmarks be drawn and labeled, default ’auto’
[Link] Should minor tickmarks be drawn, default TRUE
las sets the orientation of the axis labels, as described in par. Defaults to ’3’.
[Link] Allows for non-date labeling of date axes, default is NULL
... arguments to be passed to barplot.
Details
This function is a wrapper for barplot but adds three additional capabilities. First, it calculates and
sets a bottom margin for long column names that are rotated vertically. That doesn’t always result
in the prettiest chart, but it does ensure readable labels.
Second, it places a legend "under" the graph rather than within the bounds of the chart (which would
obscure the data). The legend is created from the column names. The default is to create the legend
when there’s more than one row of data being presented. If there is one row of data, the chart may
be "unstacked" and the legend removed.
Third, it plots or stacks negative values from an origin of zero, similar to the behavior of barchart
from the ’lattice’ package.
Note
The ’w’ attribute is so named because this is a popular way to show portfolio weights through
time. That being said, this function isn’t limited to any particular values and doesn’t provide any
normalization, so that the chart can be used more generally.
The principal drawback of stacked column charts is that it is very difficult for the reader to judge
size of 2nd, 3rd, etc., data series because they do not have common baseline. Another is that with a
large number of series, the colors may be difficult to discern. As alternatives, Cleveland advocates
the use of trellis like displays, and Tufte advocates the use of small multiple charts.
Author(s)
Peter Carl
72 [Link]
References
Cleveland, W.S. (1994), The Elements of Graphing Data, Summit, NJ: Hobart Press.
Tufte, Edward R. (2001) The Visual Display of Quantitative Information, 2nd edition. The Graphics
Press, Cheshire, Connecticut. See [Link] for this and other references.
See Also
barplot, par
Examples
data(weights)
head(weights)
Description
Draws a line chart and labels the x-axis with the appropriate dates. This is really a "primitive", since
it extends the base plot and standardizes the elements of a chart. Adds attributes for shading areas
of the timeline or aligning vertical lines along the timeline. This function is intended to be used
inside other charting functions.
Usage
[Link](R, ..., [Link] = TRUE, xaxis = TRUE, yaxis = TRUE,
[Link] = FALSE, type = "l", lty = 1, lwd = 2, las = par("las"),
main = NULL, ylab = NULL, xlab = "", [Link] = "%Y-%m-%d",
[Link] = NULL, xlim = NULL, ylim = NULL,
[Link] = "darkgray", [Link] = NULL, [Link] = NULL,
[Link] = NULL, [Link] = "darkgray",
[Link] = "aliceblue", colorset = (1:12), pch = (1:12),
[Link] = NULL, ylog = FALSE, [Link] = 0.8, [Link] = 0.8,
[Link] = 1, [Link] = 0.8, [Link] = 1, [Link] = "auto",
[Link] = TRUE, [Link] = "lightgray", [Link] = "dotted",
[Link] = NULL, dygraphPlot = FALSE, [Link] = FALSE)
[Link] 73
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
[Link] if true, draws a grid aligned with the points on the x and y axes
xaxis if true, draws the x axis
yaxis if true, draws the y axis
[Link] if true, draws the y axis on the right-hand side of the plot
type set the chart type, same as in plot
lty set the line type, same as in plot
lwd set the line width, same as in plot
las set the axis label rotation, same as in plot
main set the chart title, same as in plot
ylab set the y-axis label, same as in plot
xlab set the x-axis label, same as in plot
[Link] allows specification of other date formats in the data object, defaults to "%Y-
%m-%d"
[Link] re-format the dates for the xaxis; the default is "%m/%y"
xlim set the x-axis limit, same as in plot
ylim set the y-axis limit, same as in plot
[Link] provides the color for drawing chart elements, such as the box lines, axis lines,
etc. Default is "darkgray"
[Link] if not null, vertical lines will be drawn to indicate that an event happened during
that time period. [Link] should be a list of dates (e.g., c("09/03","05/06"))
formatted the same as [Link]. This function matches the re-formatted row
names (dates) with the [Link], so to get a match the formatting needs to be
correct.
74 [Link]
[Link] if not null and [Link] is not null, this will apply a list of text labels (e.g.,
c("This Event", "That Event") to the vertical lines drawn. See the example
below.
[Link] these are shaded areas described by start and end dates in a vector of xts date
rangees, e.g., c("1926-10::1927-11","1929-08::1933-03") See the exam-
ples below.
[Link] draws the event described in [Link] in the color specified
[Link] draws the shaded region described by [Link] in the color specified
colorset color palette to use, set by default to rational choices
pch symbols to use, see also plot
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
ylog TRUE/FALSE set the y-axis to logarithmic scale, similar to plot, default FALSE
[Link] The magnification to be used for axis annotation relative to the current setting
of ’cex’, same as in plot.
[Link] The magnification to be used for sizing the legend relative to the current setting
of ’cex’.
[Link] The magnification to be used for x- and y-axis labels relative to the current
setting of ’cex’.
[Link] The magnification to be used for event line labels relative to the current setting
of ’cex’.
[Link] The magnification to be used for the chart title relative to the current setting of
’cex’.
[Link] Should major tickmarks be drawn and labeled, default ’auto’
[Link] Should minor tickmarks be drawn, default TRUE
[Link] sets the color for the reference grid
[Link] defines the line type for the grid
[Link] Allows for non-date labeling of date axes, default is NULL
dygraphPlot Plot using dygraphs default FALSE
[Link] if TRUE, scales the y axis labels by 100
space default 0
Author(s)
Peter Carl
See Also
Examples
"Russian Crisis",
"LTCM",
"Tech Bubble",
"Sept 11")
data(edhec)
R=edhec[,"Funds of Funds",drop=FALSE]
[Link] = cumprod(1+R) - 1
[Link]([Link])
[Link]([Link], colorset = "darkblue",
[Link] = "bottomright",
[Link] = [Link],
[Link] = rgb(204/255, 204/255, 204/255, alpha=0.25),
[Link] = [Link],
[Link] = [Link],
[Link] = "red", lwd = 2)
Description
Creates a chart of Value-at-Risk and/or Expected Shortfall estimates by confidence interval for
multiple methods.
Usage
[Link](R, methods = c("GaussianVaR", "ModifiedVaR",
"HistoricalVaR", "GaussianES", "ModifiedES", "HistoricalES"),
clean = c("none", "boudt", "geltner"), elementcolor = "darkgray",
[Link] = TRUE, xlab = "Confidence Level",
ylab = "Value at Risk", type = "l", lty = c(1, 2, 4), lwd = 1,
colorset = (1:12), pch = (1:12), [Link] = "bottomleft",
[Link] = 0.8, main = NULL, ylim = NULL, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
methods one or more calculation methods indicated "GaussianVaR", "ModifiedVaR",
"HistoricalVaR", "GaussianES", "ModifiedES", "HistoricalES". See VaR or ES
for more detail.
clean method for data cleaning through [Link]. Current options are "none" or
"boudt" or "geltner".
elementcolor the color used to draw chart elements. The default is "darkgray"
[Link] if true, draws a grid aligned with the points on the x and y axes
xlab set the x-axis label, same as in plot
[Link] 77
Details
This chart shows estimated VaR along a series of confidence intervals for selected calculation meth-
ods. Useful for comparing a method to the historical VaR calculation.
Author(s)
Peter Carl
References
Boudt, K., Peterson, B. G., Croux, C., 2008. Estimation and Decomposition of Downside Risk for
Portfolios with Non-Normal Returns. Journal of Risk, forthcoming.
See Also
VaR
ES
Examples
data(managers)
[Link](managers[,1,drop=FALSE],
methods=c("HistoricalVaR", "ModifiedVaR", "GaussianVaR"),
colorset=bluefocus, lwd=2)
78 [Link]
[Link]
Create combined wealth index, period performance, and drawdown
chart
Description
For a set of returns, create a wealth index chart, bars for per-period performance, and underwater
chart for drawdown.
Usage
[Link](R, Rf = 0, main = NULL, geometric = TRUE,
methods = "none", width = 0, [Link] = NULL, ylog = FALSE,
[Link] = FALSE, gap = 12, begin = c("first", "axis"),
[Link] = "topleft", p = 0.95, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
main set the chart title, as in plot
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
methods Used to select the risk parameter of trailing width returns to use in the [Link]
panel: May be any of:
• None - does not add a line,
• ModifiedVaR - uses Cornish-Fisher modified VaR,
• GaussianVaR - uses traditional Value at Risk,
• HistoricalVaR - calculates historical Value at Risk,
• ModifiedES - uses Cornish-Fisher modified Expected Shortfall,
• GaussianES - uses traditional Expected Shortfall,
• HistoricalES - calculates historical Expected Shortfall,
• StdDev - per-period standard deviation
width number of periods to apply rolling function window over
[Link] TRUE/FALSE whether or not to display lines and labels for historical market
shock events
ylog TRUE/FALSE set the y-axis to logarithmic scale, similar to plot, default FALSE
[Link] if [Link] is TRUE, shows the "value of $1", starting the cumulation of
returns at 1 rather than zero
gap numeric number of periods from start of series to use to train risk calculation
begin Align shorter series to:
[Link] 79
• first - prior value of the first column given for the reference or longer series
or,
• axis - the initial value (1 or zero) of the axis.
passthru to [Link]
[Link] sets the legend location in the top chart. Can be set to NULL or nine locations
on the chart: bottomright, bottom, bottomleft, left, topleft, top, topright, right,
or center.
p confidence level for calculation, default p=.95
... any other passthru parameters
Note
Most inputs are the same as "plot" and are principally included so that some sensible defaults could
be set.
Author(s)
Peter Carl
See Also
[Link]
[Link]
[Link]
Examples
data(edhec)
[Link](edhec[,c(1,13)])
[Link]
rolling performance chart
Description
A wrapper to create a rolling annualized returns chart, rolling annualized standard deviation chart,
and a rolling annualized sharpe ratio chart.
Usage
[Link](R, width = 12, Rf = 0, main = NULL,
[Link] = NULL, [Link] = NULL, ...)
80 checkData
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
width number of periods to apply rolling function over
Rf risk free rate, in same period as your returns
main set the chart title, same as in plot
[Link] TRUE/FALSE whether or not to display lines and labels for historical market
shock events
[Link] places a legend into one of nine locations on the chart: bottomright, bottom,
bottomleft, left, topleft, top, topright, right, or center.
... any other passthru parameters
Author(s)
Peter Carl
See Also
[Link]
Examples
data(managers)
[Link](managers[,1:8],
Rf=managers[,10,drop=FALSE],
colorset=tim8equal,
main="Rolling 12-Month Performance",
[Link]="topleft")
checkData check input data type and format and coerce to the desired output type
Description
This function was created to make the different kinds of data classes at least seem more fungible. It
allows the user to pass in a data object without being concerned that the function requires a matrix,
[Link], vector, xts, or timeSeries object. By using checkData, the function "knows" what data
format it has to work with.
Usage
checkData(x, method = c("xts", "zoo", "[Link]", "matrix", "vector"),
[Link] = TRUE, quiet = TRUE, ...)
[Link] 81
Arguments
x a vector, matrix, [Link], xts, timeSeries or zoo object to be checked and
coerced
method type of coerced data object to return, one of c("xts", "zoo", "[Link]", "ma-
trix", "vector"), default "xts"
[Link] TRUE/FALSE Remove NA’s from the data? used only with ’vector’
quiet TRUE/FALSE if false, it will throw warnings when errors are noticed, default
TRUE
... any other passthru parameters
Author(s)
Peter Carl
Examples
data(edhec)
x = checkData(edhec)
class(x)
head(x)
tail(x)
# Note that passing in a single column loses the row and column names
x = checkData(edhec[,1])
class(x)
head(x)
# Include the "drop" attribute to keep row and column names
x = checkData(edhec[,1,drop=FALSE])
class(x)
head(x)
x = checkData(edhec, method = "matrix")
class(x)
head(x)
x = checkData(edhec[,1], method = "vector")
class(x)
head(x)
Description
Robustly clean a time series to reduce the magnitude, but not the number or direction, of observa-
tions that exceed the 1 − α% risk threshold.
82 [Link]
Usage
[Link](R, alpha = 0.01, trim = 0.001)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
alpha probability to filter at 1-alpha, defaults to .01 (99%)
trim where to set the "extremeness" of the Mahalanobis distance
Details
Many risk measures are calculated by using the first two (four) moments of the asset or portfolio
return distribution. Portfolio moments are extremely sensitive to data spikes, and this sensitivity
is only exacerbated in a multivariate context. For this reason, it seems appropriate to consider
estimates of the multivariate moments that are robust to return observations that deviate extremely
from the Gaussian distribution.
There are two main approaches in defining robust alternatives to estimate the multivariate moments
by their sample means (see e.g. Maronna[2006]). One approach is to consider a more robust
estimator than the sample means. Another one is to first clean (in a robust way) the data and then
take the sample means and moments of the cleaned data.
Our cleaning method follows the second approach. It is designed in such a way that, if we want to
estimate downside risk with loss probability α, it will never clean observations that belong to the
1 − α least extreme observations. Suppose we have an n-dimensional vector time series of length
T : r1 , ..., rT . We clean this time series in three steps.
1. Ranking the observations in function of their extremeness. Denote µ and Σ the mean and
covariance matrix of the bulk of the data and let b·c be the operator that takes the integer part of
its argument. As a measure of the extremeness of the return observation rt , we use its squared
Mahalanobis distance d2t = (rt − µ)0 Σ−1 (rt − µ). We follow Rousseeuw(1985) by estimating
µ and Σ as the mean vector and covariance matrix (corrected to ensure consistency) of the
subset of size b(1 − α)T c for which the determinant of the covariance matrix of the elements
in that subset is the smallest. These estimates will be robust against the α most extreme returns.
Let d2(1) , ..., d2(T ) be the ordered sequence of the estimated squared Mahalanobis distances such
that d2(i) ≤ d2(i+1) .
2. Outlier identification. Return observations are qualified as outliers if their estimated squared
Mahalanobis distance d2t is greater than the empirical 1 − α quantile d2(b(1−α)T c) and exceeds
a very extreme quantile of the Chi squared distribution function with n degrees of freedom,
which is the distribution function of d2t when the returns are normally distributed. In this
application we take the 99.9% quantile, denoted χ2n,0.999 .
3. Data cleaning. Similarly to Khan(2007) we only clean the returns that are identified as
outliers in step 2 by replacing these returns rt with
s
max(d2(b(1−α)T )c , χ2n,0.999 )
rt
d2t
The cleaned return vector has the same orientation as the original return vector, but its mag-
nitude is smaller. Khan(2007) calls this procedure of limiting the value of d2t to a quantile of
the χ2n distribution, “multivariate Winsorization’.
CoMoments 83
Note that the primary value of data cleaning lies in creating a more robust and stable estimation
of the distribution describing the large majority of the return data. The increased robustness and
stability of the estimated moments utilizing cleaned data should be used for portfolio construction.
If a portfolio manager wishes to have a more conservative risk estimate, cleaning may not be indi-
cated for risk monitoring. It is also important to note that the robust method proposed here does not
remove data from the series, but only decreases the magnitude of the extreme events. It may also
be appropriate in practice to use a cleaning threshold somewhat outside the VaR threshold that the
manager wishes to consider. In actual practice, it is probably best to back-test the results of both
cleaned and uncleaned series to see what works best with the particular combination of assets under
consideration.
Value
cleaned data matrix
Note
This function and much of this text was originally written for Boudt, et. al, 2008
Author(s)
Kris Boudt, Brian G. Peterson
References
Boudt, K., Peterson, B. G., Croux, C., 2008. Estimation and Decomposition of Downside Risk for
Portfolios with Non-Normal Returns. Journal of Risk, forthcoming.
Khan, J. A., S. Van Aelst, and R. H. Zamar (2007). Robust linear model selection based on least
angle regression. Journal of the American Statistical Association 102.
Maronna, R. A., D. R. Martin, and V. J. Yohai (2006). Robust Statistics: Theory and Methods.
Wiley.
Rousseeuw, P. J. (1985). Multivariate estimation with high breakdown point. In W. Grossmann, G.
Pflug, I. Vincze, and W. Wertz (Eds.), Mathematical Statistics and Its Applications, Volume B, pp.
283?297. Dordrecht-Reidel.
See Also
[Link]
Description
calculates coskewness and cokurtosis as the skewness and kurtosis of two assets with reference to
one another.
84 CoMoments
Usage
CoSkewnessMatrix(R, ...)
CoKurtosisMatrix(R, ...)
CoVariance(Ra, Rb)
CoSkewness(Ra, Rb)
CoKurtosis(Ra, Rb)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of index, benchmark,
portfolio, or secondary asset returns to compare against
unbiased TRUE/FALSE whether to use a correction to have an unbiased estimator, default
FALSE
[Link] TRUE/FALSE whether to return the full moment matrix or only the vector with
the unique elements (the latter is advised for speed), default TRUE
Details
Ranaldo and Favre (2005) define coskewness and cokurtosis as the skewness and kurtosis of a
given asset analysed with the skewness and kurtosis of the reference asset or portfolio. Adding an
asset to a portfolio, such as a hedge fund with a significant level of coskewness to the portfolio,
can increase or decrease the resulting portfolio’s skewness. Similarly, adding a hedge fund with a
positive cokurtosis coefficient will add kurtosis to the portfolio.
The co-moments are useful for measuring the marginal contribution of each asset to the portfolio’s
resulting risk. As such, comoments of asset return distribution should be useful as inputs for portfo-
lio optimization in addition to the covariance matrix. Martellini and Ziemann (2007) point out that
the problem of portfolio selection becomes one of selecting tangency points in four dimensions,
incorporating expected return, second, third and fourth centered moments of asset returns.
Even outside of the optimization problem, measuring the co-moments should be a useful tool for
evaluating whether or not an asset is likely to provide diversification potential to a portfolio, not
only in terms of normal risk (i.e. volatility) but also the risk of assymetry (skewness) and extreme
events (kurtosis).
Author(s)
Kris Boudt, Peter Carl, Dries Cornilly, Brian Peterson
DownsideDeviation 85
References
Boudt, Kris, Brian G. Peterson, and Christophe Croux. 2008. Estimation and Decomposition of
Downside Risk for Portfolios with Non-Normal Returns. Journal of Risk. Winter.
Boudt, Kris, Cornilly, Dries and Verdonck, Tim. 2017. A Coskewness Shrinkage Approach for
Estimating the Skewness of Linear Combinations of Random Variables. Submitted. Available at
SSRN: [Link]
Martellini, L., & Ziemann, V. 2010. Improved estimates of higher-order comoments and implica-
tions for portfolio selection. Review of Financial Studies, 23(4), 1467-1502.
Ranaldo, Angelo, and Laurent Favre Sr. 2005. How to Price Hedge Funds: From Two- to Four-
Moment CAPM. SSRN eLibrary.
Scott, Robert C., and Philip A. Horvath. 1980. On the Direction of Preference for Moments of
Higher Order than the Variance. Journal of Finance 35(4):915-919.
See Also
BetaCoSkewness
BetaCoKurtosis
BetaCoMoments
ShrinkageMoments
EWMAMoments
StructuredMoments
MCA
Examples
data(managers)
CoVariance(managers[, "HAM2", drop=FALSE], managers[, "SP500 TR", drop=FALSE])
CoSkewness(managers[, "HAM2", drop=FALSE], managers[, "SP500 TR", drop=FALSE])
CoKurtosis(managers[, "HAM2", drop=FALSE], managers[, "SP500 TR", drop=FALSE])
Description
Downside deviation, semideviation, and semivariance are measures of downside risk.
Usage
DownsideDeviation(R, MAR = 0, method = c("full", "subset"), ...,
potential = FALSE)
DownsidePotential(R, MAR = 0)
86 DownsideDeviation
SemiDeviation(R)
SemiVariance(R)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
method one of "full" or "subset", indicating whether to use the length of the full series
or the length of the subset of the series below the MAR as the denominator,
defaults to "full"
... any other passthru parameters
potential if TRUE, calculate downside potential instead, default FALSE
Details
Downside deviation, similar to semi deviation, eliminates positive returns when calculating risk.
Instead of using the mean return or zero, it uses the Minimum Acceptable Return as proposed by
Sharpe (which may be the mean historical return or zero). It measures the variability of under-
performance below a minimum targer rate. The downside variance is the square of the downside
potential.
To calculate it, we take the subset of returns that are less than the target (or Minimum Acceptable
Returns (MAR)) returns and take the differences of those to the target. We sum the squares and
divide by the total number of returns to get a below-target semi-variance.
v
u n
uX min[(Rt − M AR), 0]2
DownsideDeviation(R, M AR) = δM AR =t
t=1
n
n
X min[(Rt − M AR), 0]2
DownsideV ariance(R, M AR) =
t=1
n
n
X min[(Rt − M AR), 0]
DownsideP otential(R, M AR) =
t=1
n
where n is either the number of observations of the entire series or the number of observations in
the subset of the series falling below the MAR.
SemiDeviation or SemiVariance is a popular alternative downside risk measure that may be used
in place of standard deviation or variance. SemiDeviation and SemiVariance are implemented as a
wrapper of DownsideDeviation with MAR=mean(R).
In many functions like Markowitz optimization, semideviation may be substituted directly, and the
covariance matrix may be constructed from semideviation or the vector of returns below the mean
rather than from variance or the full vector of returns.
DownsideDeviation 87
In semideviation, by convention, the value of n is set to the full number of observations. In semi-
variance the the value of n is set to the subset of returns below the mean. It should be noted that
while this is the correct mathematical definition of semivariance, this result doesn’t make any sense
if you are also going to be using the time series of returns below the mean or below a MAR to
construct a semi-covariance matrix for portfolio optimization.
Sortino recommends calculating downside deviation utilizing a continuous fitted distribution rather
than the discrete distribution of observations. This would have significant utility, especially in cases
of a small number of observations. He recommends using a lognormal distribution, or a fitted
distribution based on a relevant style index, to construct the returns below the MAR to increase the
confidence in the final result. Hopefully, in the future, we’ll add a fitted option to this function, and
would be happy to accept a contribution of this nature.
Author(s)
Peter Carl, Brian G. Peterson, Matthieu Lestel
References
Sortino, F. and Price, L. Performance Measurement in a Downside Risk Framework. Journal of
Investing. Fall 1994, 59-65.
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
Plantinga, A., van der Meer, R. and Sortino, F. The Impact of Downside Risk on Risk-Adjusted
Performance of Mutual Funds in the Euronext Markets. July 19, 2001. Available at SSRN:
[Link]
Examples
data(portfolio_bacon)
MAR = 0.005
DownsideDeviation(portfolio_bacon[,1], MAR) #expected 0.0255
DownsidePotential(portfolio_bacon[,1], MAR) #expected 0.0137
data(managers)
apply(managers[,1:6], 2, sd, [Link]=TRUE)
DownsideDeviation(managers[,1:6]) # MAR 0%
DownsideDeviation(managers[,1:6], MAR = .04/12) #MAR 4%
SemiDeviation(managers[,1,drop=FALSE])
SemiDeviation(managers[,1:6])
SemiVariance (managers[,1,drop=FALSE])
SemiVariance (managers[,1:6]) #calculated using method="subset"
88 DownsideFrequency
Description
To calculate Downside Frequency, we take the subset of returns that are less than the target (or
Minimum Acceptable Returns (MAR)) returns and divide the length of this subset by the total
number of returns.
Usage
DownsideFrequency(R, MAR = 0, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
... any other passthru parameters
Details
n
X min[(Rt − M AR), 0]
DownsideF requency(R, M AR) =
t=1
Rt ∗ n
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.94
Examples
data(portfolio_bacon)
MAR = 0.005
print(DownsideFrequency(portfolio_bacon[,1], MAR)) #expected 0.458
data(managers)
print(DownsideFrequency(managers['1996']))
print(DownsideFrequency(managers['1996',1])) #expected 0.25
DRatio 89
Description
The d ratio is similar to the Bernado Ledoit ratio but inverted and taking into account the frequency
of positive and negative returns.
Usage
DRatio(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
It has values between zero and infinity. It can be used to rank the performance of portfolios. The
lower the d ratio the better the performance, a value of zero indicating there are no returns less than
zero and a value of infinity indicating there are no returns greater than zero.
Pn
nd ∗ t=1 max(−Rt , 0)
DRatio(R) = Pn
nu ∗ t=1 max(Rt , 0)
where n is the number of observations of the entire series, nd is the number of observations less
than zero, nu is the number of observations greater than zero
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.95
Examples
data(portfolio_bacon)
print(DRatio(portfolio_bacon[,1])) #expected 0.401
data(managers)
print(DRatio(managers['1996']))
print(DRatio(managers['1996',1])) #expected 0.0725
90 DrawdownPeak
Description
DD = sqrt(sum[j=1,2,...,d](D_j^2/n)) where D_j = jth drawdown over the entire period d = total
number of drawdowns in entire period n = number of observations
Usage
DrawdownDeviation(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Description
Drawdawn peak is for each return its drawdown since the previous peak
Usage
DrawdownPeak(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Author(s)
Matthieu Lestel
Drawdowns 91
Description
findDrawdowns will find the starting period, the ending period, and the amount and length of the
drawdown.
Usage
Drawdowns(R, geometric = TRUE, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
... any other passthru parameters
Details
Often used with sortDrawdowns to get the largest drawdowns.
Drawdowns will calculate the drawdown levels as percentages, for use in [Link].
Returns an unordered list:
Author(s)
Peter Carl
findDrawdowns modified with permission from function by Sankalp Upadhyay
References
Bacon, C. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 88
92 edhec
See Also
sortDrawdowns
maxDrawdown
sortDrawdowns
[Link]
[Link]
[Link]
Examples
data(edhec)
findDrawdowns(edhec[,"Funds of Funds", drop=FALSE])
sortDrawdowns(findDrawdowns(edhec[,"Funds of Funds", drop=FALSE]))
Description
EDHEC composite hedge fund style index returns.
Usage
edhec
Format
CSV conformed into an xts object with monthly observations
Details
EDHEC Data used in PerformanceAnalytics and related publications with the kind permission of
the EDHEC Risk and Asset Management Research Center.
The ’edhec’ data set included with PerformanceAnalytics will be periodically updated (typically
annually) to include additional observations. If you intend to use this data set in automated tests,
please be sure to subset your data like edhec[1:120,] to use the first ten years of observations.
From the EDHEC website: “The EDHEC Risk and Asset Management Research Centre plays a
noted role in furthering applied financial research and systematically highlighting its practical uses.
As part of its philosophy, the centre maintains a dialogue with professionals which benefits the
industry as a whole. At the same time, its proprietary R&D provides sponsors with an edge over
competition and joint ventures allow selected partners to develop new business opportunities.
To further assist financial institutions and investors implement the latest research advances in order
to meet the challenges of the changing asset management landscape, the centre has spawned two
ETL 93
consultancies and an executive education arm. Clients of these derivative activities include many of
the leading organisations throughout Europe.”
see [Link]
Source
[Link]
References
About EDHEC Alternative Indexes. December 16, 2003. EDHEC-Risk.
[Link]
Vaissie Mathieu. A Detailed Analysis of the Construction Methods and Management Principles of
Hedge Fund Indices. October 2003. EDHEC.
[Link]
Examples
data(edhec)
Description
Calculates Expected Shortfall(ES) (also known as) Conditional Value at Risk(CVaR) or Expected
Tail Loss (ETL) for univariate, component, and marginal cases using a variety of analytical methods.
Usage
ETL(R = NULL, p = 0.95, ..., method = c("modified", "gaussian",
"historical"), clean = c("none", "boudt", "geltner"),
portfolio_method = c("single", "component"), weights = NULL, mu = NULL,
sigma = NULL, m3 = NULL, m4 = NULL, invert = TRUE,
operational = TRUE)
94 ETL
Arguments
Background
This function provides several estimation methods for the Expected Shortfall (ES) (also called Ex-
pected Tail Loss (ETL) or Conditional Value at Risk (CVaR)) of a return series and the Component
ES (ETL/CVaR) of a portfolio.
At a preset probability level denoted c, which typically is between 1 and 5 per cent, the ES of a
return series is the negative value of the expected value of the return when the return is less than
its c-quantile. Unlike value-at-risk, conditional value-at-risk has all the properties a risk measure
should have to be coherent and is a convex function of the portfolio weights (Pflug, 2000). With
a sufficiently large data set, you may choose to estimate ES with the sample average of all returns
that are below the c empirical quantile. More efficient estimates of VaR are obtained if a (correct)
assumption is made on the return distribution, such as the normal distribution. If your return series
is skewed and/or has excess kurtosis, Cornish-Fisher estimates of ES can be more appropriate. For
the ES of a portfolio, it is also of interest to decompose total portfolio ES into the risk contributions
of each of the portfolio components. For the above mentioned ES estimators, such a decomposition
is possible in a financially meaningful way.
ETL 95
Note
The option to invert the ES measure should appease both academics and practitioners. The math-
ematical definition of ES as the negative value of extreme losses will (usually) produce a positive
number. Practitioners will argue that ES denotes a loss, and should be internally consistent with
the quantile (a negative number). For tables and charts, different preferences may apply for clarity
and compactness. As such, we provide the option, and set the default to TRUE to keep the return
consistent with prior versions of PerformanceAnalytics, but make no value judgement on which
approach is preferable.
Author(s)
Brian G. Peterson and Kris Boudt
References
Boudt, Kris, Peterson, Brian, and Christophe Croux. 2008. Estimation and decomposition of down-
side risk for portfolios with non-normal returns. 2008. The Journal of Risk, vol. 11, 79-103.
Cont, Rama, Deguest, Romain and Giacomo Scandolo. Robustness and sensitivity analysis of risk
measurement procedures. Financial Engineering Report No. 2007-06, Columbia University Center
for Financial Engineering.
Laurent Favre and Jose-Antonio Galeano. Mean-Modified Value-at-Risk Optimization with Hedge
Funds. Journal of Alternative Investment, Fall 2002, v 5.
Martellini, L. and Ziemann, V., 2010. Improved estimates of higher-order comoments and implica-
tions for portfolio selection. Review of Financial Studies, 23(4):1467-1502.
Pflug, G. Ch. Some remarks on the value-at-risk and the conditional value-at-risk. In S. Uryasev,
ed., Probabilistic Constrained Optimization: Methodology and Applications, Dordrecht: Kluwer,
2000, 272-281.
Scaillet, Olivier. Nonparametric estimation and sensitivity analysis of expected shortfall. Mathe-
matical Finance, 2002, vol. 14, 74-86.
See Also
VaR
[Link]
[Link]
[Link]
Examples
data(edhec)
# now use modified Cornish Fisher calc to take non-normal distribution into account
ES(edhec, p=.95, method="modified")
Description
calculates exponentially weighted moving average covariance, coskewness and cokurtosis matrices
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns (with
mean zero)
lambda decay coefficient
last.M2 last estimated covariance matrix before the observed returns R
... any other passthru parameters
last.M3 last estimated coskewness matrix before the observed returns R
[Link] TRUE/FALSE whether to return the full moment matrix or only the vector with
the unique elements (the latter is advised for speed), default TRUE
last.M4 last estimated cokurtosis matrix before the observed returns R
EWMAMoments 97
Details
The coskewness and cokurtosis matrices are defined as the matrices of dimension p x p^2 and p x
p^3 containing the third and fourth order central moments. They are useful for measuring nonlinear
dependence between different assets of the portfolio and computing modified VaR and modified ES
of a portfolio.
EWMA estimation of the covariance matrix was popularized by the RiskMetrics report in 1996.
The [Link] and [Link] are straightforward extensions to the setting of third and fourth order
central moments
Author(s)
Dries Cornilly
References
JP Morgan. Riskmetrics technical document. 1996.
See Also
CoMoments
ShrinkageMoments
StructuredMoments
MCA
Examples
data(edhec)
# EWMA estimation
# '[Link] = F' would speed up calculations in higher dimensions
sigma <- [Link](edhec, 0.94)
m3 <- [Link](edhec, 0.94)
m4 <- [Link](edhec, 0.94)
Description
Fama beta is a beta used to calculate the loss of diversification. It is made so that the systematic risk
is equivalent to the total portfolio risk.
Usage
FamaBeta(Ra, Rb, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
... any other passthru parameters
Details
σP
βF =
σM
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.78
Examples
data(portfolio_bacon)
print(FamaBeta(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 1.03
data(managers)
print(FamaBeta(managers['1996',1], managers['1996',8]))
print(FamaBeta(managers['1996',1:5], managers['1996',8]))
Frequency 99
Description
Gives the period of the return distribution (ie 12 if monthly return, 4 if quarterly return)
Usage
Frequency(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Author(s)
Matthieu Lestel
Examples
data(portfolio_bacon)
print(Frequency(portfolio_bacon[,1])) #expected 12
data(managers)
print(Frequency(managers['1996',1:5]))
HurstIndex calculate the Hurst Index The Hurst index can be used to measure
whether returns are mean reverting, totally random, or persistent.
Description
Hurst obtained a dimensionless statistical exponent by dividing the range by the standard deviation
of the observations, so this approach is commonly referred to as rescaled range (R/S) analysis.
Usage
HurstIndex(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
100 InformationRatio
Details
H = log(m)/log(n)
where m = [max(ri ) − min(ri )]/sigmap and n = numberof observations A Hurst index be-
tween 0.5 and 1 suggests that the returns are persistent. At 0.5, the index suggests returns are totally
random. Between 0 and 0.5 it suggests that the returns are mean reverting.
H.E. Hurst originally developed the Hurst index to help establish optimal water storage along the
Nile. Nile floods are extremely persistent, measuring a Hurst index of 0.9. Peters (1991) notes that
Equity markets have a Hurst index in excess of 0.5, with typical values of around 0.7. That appears
to be anomalous in the context of the mainstream ’rational behaviour’ theories of economics, and
suggests existence of a powerful ’long-term memory’ causal dependence. Clarkson (2001) suggests
that an ’over-reaction bias’ could be expected to generate a powerful ’long-term memory’ effect in
share prices.
References
Clarkson, R. (2001) FARM: a financial actuarial risk model. In Chapter 12 of Managing Downside
Risk in Financial Markets, ed. Sortino, F. and Satchel, S. Woburn MA. Butterworth-Heinemann
Finance.
Peters, E.E (1991) Chaos and Order in Capital Markets, New York: Wiley.
Bacon, Carl. (2008) Practical Portfolio Performance Measurement and Attribution, 2nd Edition.
London: John Wiley & Sons.
Description
The Active Premium divided by the Tracking Error.
Usage
InformationRatio(Ra, Rb, scale = NA)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
Details
InformationRatio = ActivePremium/TrackingError
This relates the degree to which an investment has beaten the benchmark to the consistency with
which the investment has beaten the benchmark.
Kappa 101
Note
William Sharpe now recommends InformationRatio preferentially to the original SharpeRatio.
Author(s)
Peter Carl
References
Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.
See Also
TrackingError
ActivePremium
SharpeRatio
Examples
data(managers)
InformationRatio(managers[,"HAM1",drop=FALSE], managers[, "SP500 TR", drop=FALSE])
InformationRatio(managers[,1:6], managers[,8,drop=FALSE])
InformationRatio(managers[,1:6], managers[,8:7])
Description
Introduced by Kaplan and Knowles (2004), Kappa is a generalized downside risk-adjusted perfor-
mance measure.
Usage
Kappa(R, MAR, l, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
l the coefficient of the Kappa
... any other passthru parameters
102 KellyRatio
Details
To calculate it, we take the difference of the mean of the distribution to the target and we divide it
by the l-root of the lth lower partial moment. To calculate the lth lower partial moment we take the
subset of returns below the target and we sum the differences of the target to these returns. We then
return return this sum divided by the length of the whole distribution.
rp − M AR
Kappa(R, M AR, l) = q Pn
1
l
n ∗ t=1 max(M AR − Rt , 0)l
For l=1 kappa is the Sharpe-omega ratio and for l=2 kappa is the sortino ratio.
Kappa should only be used to rank portfolios as it is difficult to interpret the absolute differences
between kappas. The higher the kappa is, the better.
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.96
Examples
l = 2
data(portfolio_bacon)
MAR = 0.005
print(Kappa(portfolio_bacon[,1], MAR, l)) #expected 0.157
data(managers)
MAR = 0
print(Kappa(managers['1996'], MAR, l))
print(Kappa(managers['1996',1], MAR, l)) #expected 1.493
KellyRatio calculate Kelly criterion ratio (leverage or bet size) for a strategy
Description
Kelly criterion ratio (leverage or bet size) for a strategy.
Usage
KellyRatio(R, Rf = 0, method = "half")
KellyRatio 103
Arguments
Details
The Kelly Criterion was identified by Bell Labs scientist John Kelly, and applied to blackjack and
stock strategy sizing by Ed Thorpe.
The Kelly ratio can be simply stated as: “bet size is the ratio of edge over odds.” Mathematically,
you are maximizing log-utility. As such, the Kelly criterion is equal to the expected excess return
of the strategy divided by the expected variance of the excess return, or
(Rs − Rf )
leverage =
StdDev(R)2
Author(s)
Brian G. Peterson
References
Thorp, Edward O. (1997; revised 1998). The Kelly Criterion in Blackjack, Sports Betting, and the
Stock Market. [Link]
[Link]
Examples
data(managers)
KellyRatio(managers[,1,drop=FALSE], Rf=.04/12)
KellyRatio(managers[,1,drop=FALSE], Rf=managers[,10,drop=FALSE])
KellyRatio(managers[,1:6], Rf=managers[,10,drop=FALSE])
104 kurtosis
kurtosis Kurtosis
Description
compute kurtosis of a univariate distribution
Usage
kurtosis(x, [Link] = FALSE, method = c("excess", "moment", "fisher",
"sample", "sample_excess"), ...)
Arguments
x a numeric vector or object.
[Link] a logical. Should missing values be removed?
method a character string which specifies the method of computation. These are either
"moment", "fisher", or "excess". If "excess" is selected, then the value
of the kurtosis is computed by the "moment" method and a value of 3 will be
subtracted. The "moment" method is based on the definitions of kurtosis for dis-
tributions; these forms should be used when resampling (bootstrap or jackknife).
The "fisher" method correspond to the usual "unbiased" definition of sample
variance, although in the case of kurtosis exact unbiasedness is not possible. The
"sample" method gives the sample kurtosis of the distribution.
... arguments to be passed.
Details
This function was ported from the RMetrics package fUtilities to eliminate a dependency on fUtil-
ties being loaded every time. This function is identical except for the addition of checkData and
additional labeling.
n
1 X ri − r 4
Kurtosis(moment) = ∗ ( )
n i=1 σP
n
1 X ri − r 4
Kurtosis(excess) = ∗ ( ) −3
n i=1 σP
n
n ∗ (n + 1) X ri − r
Kurtosis(sample) = ∗ ( )4
(n − 1) ∗ (n − 2) ∗ (n − 3) i=1 σSP
Pn (ri )4
(n + 1) ∗ (n − 1) 3 ∗ (n − 1)
Kurtosis(f isher) = ∗ ( Pni=1 (r n)2 − )
(n − 2) ∗ (n − 3) i
( i=1 ( n ) 2 n+1
n
n ∗ (n + 1) X ri − r 3 ∗ (n − 1)2
Kurtosis(sampleexcess) = ∗ ( )4 −
(n − 1) ∗ (n − 2) ∗ (n − 3) i=1 σSP (n − 2) ∗ (n − 3)
lpm 105
where n is the number of return, r is the mean of the return distribution, σP is its standard deviation
and σSP is its sample standard deviation
Author(s)
Diethelm Wuertz, Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.84-85
See Also
skewness.
Examples
## mean -
## var -
# Mean, Variance:
r = rnorm(100)
mean(r)
var(r)
## kurtosis -
kurtosis(r)
data(managers)
kurtosis(managers[,1:8])
data(portfolio_bacon)
print(kurtosis(portfolio_bacon[,1], method="sample")) #expected 3.03
print(kurtosis(portfolio_bacon[,1], method="sample_excess")) #expected -0.41
print(kurtosis(managers['1996'], method="sample"))
print(kurtosis(managers['1996',1], method="sample"))
Description
Caclulate a Lower Partial Moment around the mean or a specified threshold.
Usage
lpm(R, n = 2, threshold = 0, about_mean = FALSE)
106 M2Sortino
Arguments
R xts data
n the n-th moment to return
threshold threshold can be the mean or any point as desired
about_mean TRUE/FALSE calculate LPM about the mean under the threshold or use the
threshold to calculate the LPM around (if FALSE)
Details
Lower partial moments capture negative deviation from a reference point. That reference point may
be the mean, or some specified threshold that has other meaning for the investor.
Author(s)
Kyle Balkissoon <kylebalkisoon@[Link]>
References
Huffman S.P. & Moll C.R., "The impact of Asymmetry on Expected Stock Returns: An Investiga-
tion of Alternative Risk Measures", Algorithmic Finance 1, 2011 p. 79-93
Description
M squared for Sortino is a M^2 calculated for Downside risk instead of Total Risk
Usage
M2Sortino(Ra, Rb, MAR = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset return
Rb return vector of the benchmark asset
MAR the minimum acceptable return
... any other passthru parameters
Details
where MS2 is MSquared for Sortino, rP is the annualised portfolio return, σDM is the benchmark
annualised downside risk and D is the portfolio annualised downside risk
managers 107
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.102-103
Examples
data(portfolio_bacon)
MAR = 0.005
print(M2Sortino(portfolio_bacon[,1], portfolio_bacon[,2], MAR)) #expected 0.1035
data(managers)
MAR = 0
print(MSquaredExcess(managers['1996',1], managers['1996',8], MAR))
print(MSquaredExcess(managers['1996',1:5], managers['1996',8], MAR))
Description
A xts object that contains columns of monthly returns for six hypothetical asset managers (HAM1
through HAM6), the EDHEC Long-Short Equity hedge fund index, the S\&P 500 total returns, and
total return series for the US Treasury 10-year bond and 3-month bill. Monthly returns for all series
end in December 2006 and begin at different periods starting from January 1996.
Note that all the EDHEC indices are available in edhec.
Usage
managers
Format
CSV conformed into an xts object with monthly observations
Details
Please note that the ‘managers’ data set included with PerformanceAnalytics will be periodically
updated with new managers and information. If you intend to use this data set in automated tests,
please be sure to subset your data like managers[1:120,1:6] to use the first ten years of observa-
tions on HAM1-HAM6.
108 MarketTiming
Examples
data(managers)
#cumulative returns
tail(cumprod(1+managers),1)
Description
Allows to estimate Treynor-Mazuy or Merton-Henriksson market timing model. The Treynor-
Mazuy model is essentially a quadratic extension of the basic CAPM. It is estimated using a multiple
regression. The second term in the regression is the value of excess return squared. If the gamma co-
efficient in the regression is positive, then the estimated equation describes a convex upward-sloping
regression "line". The quadratic regression is:
Rp − Rf = α + β(Rb − Rf ) + γ(Rb − Rf )2 + εp
γ is a measure of the curvature of the regression line. If γ is positive, this would indicate that the
manager’s investment strategy demonstrates market timing ability.
Usage
MarketTiming(Ra, Rb, Rf = 0, method = c("TM", "HM"))
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of the asset returns
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of the benchmark
asset return
Rf risk free rate, in same period as your returns
method used to select between Treynor-Mazuy and Henriksson-Merton models. May be
any of:
• TM - Treynor-Mazuy model,
• HM - Henriksson-Merton model
By default Treynor-Mazuy is selected
... any other passthrough parameters
MartinRatio 109
Details
The basic idea of the Merton-Henriksson test is to perform a multiple regression in which the
dependent variable (portfolio excess return and a second variable that mimics the payoff to an
option). This second variable is zero when the market excess return is at or below zero and is 1
when it is above zero:
Rp − Rf = α + β(Rb − Rf ) + γD + εp
where all variables are familiar from the CAPM model, except for the up-market return D =
max(0, Rb − Rf ) and market timing abilities γ
Author(s)
Andrii Babii, Peter Carl
References
J. Christopherson, D. Carino, W. Ferson. Portfolio Performance Measurement and Benchmarking.
2009. McGraw-Hill, p. 127-133.
J. L. Treynor and K. Mazuy, "Can Mutual Funds Outguess the Market?" Harvard Business Review,
vol44, 1966, pp. 131-136
Roy D. Henriksson and Robert C. Merton, "On Market Timing and Investment Performance. II.
Statistical Procedures for Evaluating Forecast Skills," Journal of Business, vol.54, October 1981,
pp.513-533
See Also
[Link]
Examples
data(managers)
MarketTiming(managers[,1], managers[,8], Rf=.035/12, method = "HM")
MarketTiming(managers[80:120,1:6], managers[80:120,7], managers[80:120,10])
MarketTiming(managers[80:120,1:6], managers[80:120,8:7], managers[80:120,10], method = "TM")
Description
To calculate Martin ratio we divide the difference of the portfolio return and the risk free rate by the
Ulcer index
Usage
MartinRatio(R, Rf = 0, ...)
110 maxDrawdown
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
... any other passthru parameters
Details
rP − rF
M artinratio = q
Pn Di0 2
i=1 n
where rP is the annualized portfolio return, rF is the risk free rate, n is the number of observations
of the entire series, Di0 is the drawdown since previous peak in period i
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.91
Examples
data(portfolio_bacon)
print(MartinRatio(portfolio_bacon[,1])) #expected 1.70
data(managers)
print(MartinRatio(managers['1996']))
print(MartinRatio(managers['1996',1]))
Description
To find the maximum drawdown in a return series, we need to first calculate the cumulative returns
and the maximum cumulative return to that point. Any time the cumulative returns dips below the
maximum cumulative returns, it’s a drawdown. Drawdowns are measured as a percentage of that
maximum cumulative return, in effect, measured from peak equity.
Usage
maxDrawdown(R, weights = NULL, geometric = TRUE, invert = TRUE, ...)
maxDrawdown 111
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
weights portfolio weighting vector, default NULL, see Details
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
invert TRUE/FALSE whether to invert the drawdown measure. see Details.
... any other passthru parameters
Details
The option to invert the measure should appease both academics and practitioners. The default
option invert=TRUE will provide the drawdown as a positive number. This should be useful for
optimization (which usually seeks to minimize a value), and for tables (where having negative
signs in front of every number may be considered clutter). Practitioners will argue that drawdowns
denote losses, and should be internally consistent with the quantile (a negative number), for which
invert=FALSE will provide the value they expect. Individually, different preferences may apply for
clarity and compactness. As such, we provide the option, but make no value judgment on which
approach is preferable.
Author(s)
Peter Carl
References
Bacon, C. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 88
See Also
findDrawdowns
sortDrawdowns
[Link]
[Link]
[Link]
Examples
data(edhec)
t(round(maxDrawdown(edhec[,"Funds of Funds"]),4))
data(managers)
t(round(maxDrawdown(managers),4))
112 MCA
Description
calculates MCA coskewness and cokurtosis matrices
Usage
[Link](R, k = 1, [Link] = TRUE, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
k the number of components to use
[Link] TRUE/FALSE whether to return the full moment matrix or only the vector with
the unique elements (the latter is advised for speed), default TRUE
... any other passthru parameters
Details
The coskewness and cokurtosis matrices are defined as the matrices of dimension p x p^2 and p x
p^3 containing the third and fourth order central moments. They are useful for measuring nonlinear
dependence between different assets of the portfolio and computing modified VaR and modified ES
of a portfolio.
MCA is a generalization of PCA to higher moments. The principal components in MCA are the
ones that maximize the coskewness and cokurtosis present when projecting onto these directions.
It was introduced by Lim and Morton (2007) and applied to financial returns data by Jondeau and
Rockinger (2017)
If a coskewness matrix (argument M3) or cokurtosis matrix (argument M4) is passed in using ...,
then MCA is performed on the given comoment matrix instead of the sample coskewness or cokur-
tosis matrix.
Author(s)
Dries Cornilly
References
Lim, Hek-Leng and Morton, Jason. 2007. Principal Cumulant Component Analysis. working paper
Jondeau, Eric and Jurczenko, Emmanuel. 2017. Moment Component Analysis: An Illustration
With International Stock Markets. Journal of Business and Economic Statistics
[Link] 113
See Also
CoMoments
ShrinkageMoments
StructuredMoments
EWMAMoments
Examples
data(edhec)
# screeplot MCA
M3dist <- M4dist <- rep(NA, ncol(edhec))
M3S <- [Link](edhec) # sample coskewness estimator
M4S <- [Link](edhec) # sample cokurtosis estimator
for (k in 1:ncol(edhec)) {
M3MCA_list <- [Link](edhec, k)
M4MCA_list <- [Link](edhec, k)
Description
Usage
## S3 method for class 'geometric'
114 MeanAbsoluteDeviation
mean(x, ...)
Arguments
x a vector, matrix, data frame, or time series to calculate the modified mean statis-
tic over
... any other passthru parameters
ci the confidence interval to use
Author(s)
Peter Carl
See Also
sd
mean
Examples
data(edhec)
[Link](edhec[,"Funds of Funds"])
[Link](edhec[,"Funds of Funds"])
[Link](edhec[,"Funds of Funds"])
[Link](edhec[,"Funds of Funds"])
Description
To calculate Mean absolute deviation we take the sum of the absolute value of the difference be-
tween the returns and the mean of the returns and we divide it by the number of returns.
Usage
MeanAbsoluteDeviation(R, ...)
Modigliani 115
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
Pn
i=1 | ri − r |
M eanAbsoluteDeviation =
n
where n is the number of observations of the entire series, ri is the return in month i and r is the
mean return
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.62
Examples
data(portfolio_bacon)
print(MeanAbsoluteDeviation(portfolio_bacon[,1])) #expected 0.0310
data(managers)
print(MeanAbsoluteDeviation(managers['1996']))
print(MeanAbsoluteDeviation(managers['1996',1]))
Description
The Modigliani-Modigliani measure is the portfolio return adjusted upward or downward to match
the benchmark’s standard deviation. This puts the portfolio return and the benchmark return on
’equal footing’ from a standard deviation perspective.
E[Rp − Rf ]
M Mp = = SRp ∗ σb + E[Rf ]
σp
where SRp - Sharpe ratio, σb - benchmark standard deviation
Usage
Modigliani(Ra, Rb, Rf = 0, ...)
116 MSquared
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthrough parameters
Details
This is also analogous to some approaches to ’risk parity’ portfolios, which use (presumably cost-
less) leverage to increase the portfolio standard deviation to some target.
Author(s)
Andrii Babii, Brian G. Peterson
References
J. Christopherson, D. Carino, W. Ferson. Portfolio Performance Measurement and Benchmarking.
2009. McGraw-Hill, p. 97-99.
Franco Modigliani and Leah Modigliani, "Risk-Adjusted Performance: How to Measure It and
Why," Journal of Portfolio Management, vol.23, no., Winter 1997, pp.45-54
See Also
SharpeRatio, TreynorRatio
Examples
data(managers)
Modigliani(managers[,1,drop=FALSE], managers[,8,drop=FALSE], Rf=.035/12)
Modigliani(managers[,1:6], managers[,8,drop=FALSE], managers[,8,drop=FALSE])
Modigliani(managers[,1:6], managers[,8:7], managers[,8,drop=FALSE])
Description
M squared is a risk adjusted return useful to judge the size of relative performance between differ-
ents portfolios. With it you can compare portfolios with different levels of risk.
Usage
MSquared(Ra, Rb, Rf = 0, ...)
MSquaredExcess 117
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset return
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
Details
σM
M 2 = rP + SR ∗ (σM − σP ) = (rP − rF ) ∗ + rF
σP
where rP is the portfolio return annualized, σM is the market risk and σP is the portfolio risk
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.67-68
Examples
data(portfolio_bacon)
print(MSquared(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.10062
data(managers)
print(MSquared(managers['1996',1], managers['1996',8]))
print(MSquared(managers['1996',1:5], managers['1996',8]))
Description
M squared excess is the quantity above the standard M. There is a geometric excess return which is
better for Bacon and an arithmetic excess return
Usage
MSquaredExcess(Ra, Rb, Rf = 0, Method = c("geometric", "arithmetic"), ...)
118 MSquaredExcess
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset return
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
Method one of "geometric" or "arithmetic" indicating the method to use to calculate
MSquareExcess
... any other passthru parameters
Details
1 + M2
M 2 excess(geometric) = −1
1+b
M 2 excess(arithmetic) = M 2 − b
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.68
Examples
data(portfolio_bacon)
MSquaredExcess(portfolio_bacon[,1], portfolio_bacon[,2]) #expected -0.00998
data(managers)
MSquaredExcess(managers['1996',1], managers['1996',8])
MSquaredExcess(managers['1996',1:5], managers['1996',8])
NetSelectivity 119
Description
Net selectivity is the remaining selectivity after deducting the amount of return require to justify not
being fully diversified
Usage
NetSelectivity(Ra, Rb, Rf = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
Details
If net selectivity is negative the portfolio manager has not justified the loss of diversification
N etselectivity = α − d
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.78
Examples
data(portfolio_bacon)
print(NetSelectivity(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.017
data(managers)
print(NetSelectivity(managers['1996',1], managers['1996',8]))
print(NetSelectivity(managers['1996',1:5], managers['1996',8]))
120 Omega
Description
Keating and Shadwick (2002) proposed Omega (referred to as Gamma in their original paper) as a
way to capture all of the higher moments of the returns distribution.
Usage
Omega(R, L = 0, method = c("simple", "interp", "binomial", "blackscholes"),
output = c("point", "full"), Rf = 0, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
L L is the loss threshold that can be specified as zero, return from a benchmark
index, or an absolute rate of return - any specified level
method one of: simple, interp, binomial, blackscholes
output one of: point (in time), or full (distribution of Omega)
Rf risk free rate, as a single number
... any other passthru parameters
Details
Mathematically, Omega is: integral[L to b](1 - F(r))dr / integral[a to L](F(r))dr
where the cumulative distribution F is defined on the interval (a,b). L is the loss threshold that can
be specified as zero, return from a benchmark index, or an absolute rate of return - any specified
level. When comparing alternatives using Omega, L should be common.
Input data can be transformed prior to calculation, which may be useful for introducing risk aver-
sion.
This function returns a vector of Omega, useful for plotting. The steeper, the less risky. Above it’s
mean, a steeply sloped Omega also implies a very limited potential for further gain.
Omega has a value of 1 at the mean of the distribution.
Omega is sub-additive. The ratio is dimensionless.
Kazemi, Schneeweis, and Gupta (2003), in "Omega as a Performance Measure" show that Omega
can be written as: Omega(L) = C(L)/P(L) where C(L) is essentially the price of a European call
option written on the investment and P(L) is essentially the price of a European put option written
on the investment. The maturity for both options is one period (e.g., one month) and L is the strike
price of both options.
The numerator and the denominator can be expressed as: exp(-Rf=0) * E[max(x - L, 0)] exp(-
Rf=0) * E[max(L - x, 0)] with exp(-Rf=0) calculating the present values of the two, where rf is the
per-period riskless rate.
OmegaExcessReturn 121
The first three methods implemented here focus on that observation. The first method takes the sim-
plification described above. The second uses the Black-Scholes option pricing as implemented in
fOptions. The third uses the binomial pricing model from fOptions. The second and third methods
are not implemented here.
The fourth method, "interp", creates a linear interpolation of the cdf of returns, calculates Omega
as a vector, and finally interpolates a function for Omega as a function of L. This method requires
library Hmisc, which can be found on CRAN.
Author(s)
Peter Carl
References
Keating, J. and Shadwick, W.F. The Omega Function. working paper. Finance Development Center,
London. 2002. Kazemi, Schneeweis, and Gupta. Omega as a Performance Measure. 2003.
See Also
Ecdf
Examples
data(edhec)
Omega(edhec)
Omega(edhec[,13],method="interp",output="point")
Omega(edhec[,13],method="interp",output="full")
Description
Omega excess return is another form of downside risk-adjusted return. It is calculated by multiply-
ing the downside variance of the style benchmark by 3 times the style beta.
Usage
OmegaExcessReturn(Ra, Rb, MAR = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
MAR the minimum acceptable return
... any other passthru parameters
122 OmegaSharpeRatio
Details
2
ω = rP − 3 ∗ βS ∗ σM D
where ω is omega excess return, βS is style beta, σD is the portfolio annualised downside risk and
σM D is the benchmark annualised downside risk.
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.103
Examples
data(portfolio_bacon)
MAR = 0.005
print(OmegaExcessReturn(portfolio_bacon[,1], portfolio_bacon[,2], MAR)) #expected 0.0805
data(managers)
MAR = 0
print(OmegaExcessReturn(managers['1996',1], managers['1996',8], MAR))
print(OmegaExcessReturn(managers['1996',1:5], managers['1996',8], MAR))
Description
The Omega-Sharpe ratio is a conversion of the omega ratio to a ranking statistic in familiar form to
the Sharpe ratio.
Usage
OmegaSharpeRatio(R, MAR = 0, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
... any other passthru parameters
PainIndex 123
Details
To calculate the Omega-Sharpe ration we subtract the target (or Minimum Acceptable Returns
(MAR)) return from the portfolio return and we divide it by the opposite of the Downside Devi-
ation.
rp − rt
OmegaSharpeRatio(R, M AR) = Pn max(rt −ri ,0)
t=1 n
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008,
p.95
Examples
data(portfolio_bacon)
MAR = 0.005
print(OmegaSharpeRatio(portfolio_bacon[,1], MAR)) #expected 0.29
MAR = 0
data(managers)
print(OmegaSharpeRatio(managers['1996'], MAR))
print(OmegaSharpeRatio(managers['1996',1], MAR)) #expected 3.60
Description
The pain index is the mean value of the drawdowns over the entire analysis period. The measure is
similar to the Ulcer index except that the drawdowns are not squared. Also, it’s different than the
average drawdown, in that the numerator is the total number of observations rather than the number
of drawdowns.
Usage
PainIndex(R, ...)
124 PainRatio
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
Visually, the pain index is the area of the region that is enclosed by the horizontal line at zero percent
and the drawdown line in the Drawdown chart.
n
X | Di0 |
P ainindex =
i=1
n
where n is the number of observations of the entire series, Di0 is the drawdown since previous peak
in period i
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.89, Becker, Thomas (2006) Zephyr Associates
Examples
data(portfolio_bacon)
print(PainIndex(portfolio_bacon[,1])) #expected 0.04
data(managers)
print(PainIndex(100*managers['1996']))
print(PainIndex(100*managers['1996',1]))
Description
To calculate Pain ratio we divide the difference of the portfolio return and the risk free rate by the
Pain index
Usage
PainRatio(R, Rf = 0, ...)
portfolio_bacon 125
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
... any other passthru parameters
Details
rP − rF
P ainratio = Pn |D0 |
i
i=1 n
where rP is the annualized portfolio return, rF is the risk free rate, n is the number of observations
of the entire series, Di0 is the drawdown since previous peak in period i
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.91
Examples
data(portfolio_bacon)
print(PainRatio(portfolio_bacon[,1])) #expected 2.66
data(managers)
print(PainRatio(managers['1996']))
print(PainRatio(managers['1996',1]))
Description
A xts object that contains columns of monthly returns for an example of portfolio and its benchmark
Usage
portfolio_bacon
Format
CSV conformed into an xts object with monthly observations
126 ProspectRatio
Examples
data(portfolio_bacon)
#cumulative returns
tail(cumprod(1+portfolio_bacon),1)
Description
A object returned by [Link] of price data for use in the example for [Link]
Usage
prices
Format
R variable ’prices’
Examples
data(prices)
Description
Prospect ratio is a ratio used to penalise loss since most people feel loss greater than gain
Usage
ProspectRatio(R, MAR, ...)
[Link] 127
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR the minimum acceptable return
... any other passthru parameters
Details
1
Pn
n ∗ i=1 (M ax(ri , 0) + 2.25 ∗ M in(ri , 0) − M AR)
P rospectRatio(R) =
σD
where n is the number of observations of the entire series, MAR is the minimum acceptable return
and σD is the downside risk
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.100
Examples
data(portfolio_bacon)
MAR = 0.05
print(ProspectRatio(portfolio_bacon[,1], MAR)) #expected -0.134
data(managers)
MAR = 0
print(ProspectRatio(managers['1996'], MAR))
print(ProspectRatio(managers['1996',1], MAR))
Description
This function displays text output in a graphics window. It is the equivalent of ’print’ except that
the output is displayed as a plot.
128 [Link]
Usage
[Link](text, width = 8)
replaceTabs(text, width = 8)
## Default S3 method:
textplot(object, halign = c("center", "left", "right"),
valign = c("center", "top", "bottom"), cex, [Link], cmar, rmar,
[Link], [Link], hadj, vadj, [Link], [Link], mar,
[Link], [Link], [Link], wrap, [Link], [Link], ...)
Arguments
text in the function ’replaceTabs’, the text string to be processed
width in the function ’replaceTabs’, the number of spaces to replace tabs with
object Object to be displayed.
halign Alignment in the x direction, one of "center", "left", or "right".
valign Alignment in the y direction, one of "center", "top" , or "bottom"
cex Character size, see par for details. If unset, the code will attempt to use the
largest value which allows the entire object to be displayed.
[Link] Sets the largest text size as a ceiling
rmar, cmar Space between rows or columns, in fractions of the size of the letter ’M’.
[Link], [Link]
Logical value indicating whether row or column names will be displayed.
hadj, vadj Vertical and horizontal location of elements within matrix cells. These have the
same meaning as the adj graphics paramter (see par).
[Link] Sets the vertical alignment of the row as "top", "bottom", or (default) "center".
[Link] Sets the vertical alignment of the heading as "top", (default) "bottom", or "cen-
ter".
mar Figure margins, see the documentation for par.
[Link] Colors for data elements. If a single value is provided, all data elements will
be the same color. If a matrix matching the dimensions of the data is provided,
each data element will receive the specified color.
[Link], [Link]
Colors for row names and column names, respectively. Either may be specified
as a scalar or a vector of appropriate length.
wrap If TRUE (default), will wrap column names and rownames
[Link] The number of characters after which column labels will be wrapped. Default is
10.
[Link] The number of characters after which row headings will be wrapped. Default is
10.
... Optional arguments passed to the text plotting command or specialized object
methods
[Link] default is TRUE
cspace default is 1
lspace default is 1
[Link] default is 8
Details
A new plot is created and the object is displayed using the largest font that will fit on in the plotting
region. The halign and valign parameters can be used to control the location of the string within
the plotting region.
130 [Link]
For matrixes and vectors a specialized textplot function is available, which plots each of the cells
individually, with column widths set according to the sizes of the column elements. If present, row
and column labels will be displayed in a bold font.
textplot also uses replaceTabs, a function to replace all tabs in a string with an appropriate number of
spaces. That function was also written by Gregory R. Warnes and included in the ’gplots’ package.
Author(s)
Originally written by Gregory R. Warnes <warnes@[Link]> for the package ’gplots’,
modified by Peter Carl
See Also
plot,
text,
[Link],
textplot
Examples
# This was really nice before Hmisc messed up 'format' from R-base
# prettify with [Link] in hmisc package
# require("Hmisc")
# result = t([Link](managers[,1:8]))[-1:-12,]
Description
An average annualized return is convenient for comparing returns.
[Link] 131
Usage
[Link](R, scale = NA, geometric = TRUE)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
Details
Annualized returns are useful for comparing two assets. To do so, you must scale your observations
to an annual scale by raising the compound return to the number of periods in a year, and taking the
root to the number of total observations:
q
scale
prod(1 + Ra ) n − 1 = n prod(1 + Ra )scale − 1
where scale is the number of periods in a year, and n is the total number of periods for which you
have observations.
For simple returns (geometric=FALSE), the formula is:
Ra · scale
Author(s)
Peter Carl
References
Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 6
See Also
[Link],
Examples
data(managers)
[Link](managers[,1,drop=FALSE])
[Link](managers[,1:8])
[Link](managers[,1:8],geometric=FALSE)
132 [Link]
[Link]
calculates an annualized excess return for comparing instruments with
different length history
Description
An average annualized excess return is convenient for comparing excess returns.
Usage
[Link](Rp, Rb, scale = NA, geometric = TRUE)
Arguments
Rp an xts, vector, matrix, data frame, timeSeries or zoo object of portfolio returns
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of benchmark returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
geometric generate geometric (TRUE) or simple (FALSE) excess returns, default TRUE
Details
Annualized returns are useful for comparing two assets. To do so, you must scale your observations
to an annual scale by raising the compound return to the number of periods in a year, and taking the
root to the number of total observations:
q
scale
prod(1 + Ra ) n − 1 = n prod(1 + Ra )scale − 1
where scale is the number of periods in a year, and n is the total number of periods for which you
have observations.
Finally having annualized returns for portfolio and benchmark we can compute annualized excess
return as difference in the annualized portfolio and benchmark returns in the arithmetic case:
er = Rpa − Rba
(1 + Rpa )
er = −1
(1 + Rba )
Author(s)
Andrii Babii
[Link] 133
References
Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 206-
207
See Also
[Link],
Examples
data(managers)
[Link](Rp = managers[,1], Rb = managers[,8])
Description
calculate simple or compound returns from prices
Usage
[Link](prices, method = c("discrete", "log"))
Arguments
prices data object containing ordered price observations
method calculate "discrete" or "log" returns, default discrete(simple)
Details
Two requirements should be made clear. First, the function [Link] assumes regular
price data. In this case, we downloaded monthly close prices. Prices can be for any time scale, such
as daily, weekly, monthly or annual, as long as the data consists of regular observations. Irregular
observations require time period scaling to be comparable. Fortunately, [Link] in the xts
package, or the [Link] in the zoo package supports supports management and conversion
of irregular time series.
Second, if corporate actions, dividends, or other adjustments such as time- or money-weighting are
to be taken into account, those calculations must be made separately. This is a simple function that
assumes fully adjusted close prices as input. For the IBM timeseries in the example below, dividends
and corporate actions are not contained in the "close" price series, so we end up with "price returns"
instead of "total returns". This can lead to significant underestimation of the return series over longer
time periods. To use adjusted returns, specify quote="AdjClose" in [Link], which is
found in package tseries.
134 [Link]
We have changes the default arguments and settings for method from compound and simple to
discrete and log and discrete to avoid confusing between the return type and the chaining
method. In most of the rest of PerformanceAnalytics, compound and simple are used to refer
to the return chaining method used for the returns. The default for this function is to use discrete
returns, because most other package functions use compound chaining by default.
Author(s)
Peter Carl
References
Bacon, C. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. Chapter 2
See Also
[Link]
Examples
## Not run:
require(quantmod)
prices = getSymbols("IBM", from = "1999-01-01", to = "2007-01-01")
## End(Not run)
Description
the n-th centered moment is calculated as
Usage
[Link](R, ...)
centeredmoment(R, power)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
power power or moment to calculate
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of index, benchmark,
portfolio, or secondary asset returns to compare against
p1 first power of the comoment
p2 second power of the comoment
normalize whether to standardize the calculation to agree with common usage, or leave the
default mathematical meaning
Details
These functions are used internally by PerformanceAnalytics to calculate centered moments for a
multivariate distribution as well as the standardized moments of a portfolio distribution. They are
exposed here for users who wish to use them directly, and we’ll get more documentation written
when we can.
These functions were first utilized in Boudt, Peterson, and Croux (2008), and have been subse-
quently used in our other research.
~~ Additional Details will be added to documentation as soon as we have time to write them.
Documentation Patches Welcome. ~~
Author(s)
Kris Boudt and Brian Peterson
References
Boudt, Kris, Brian G. Peterson, and Christophe Croux. 2008. Estimation and Decomposition of
Downside Risk for Portfolios with Non-Normal Returns. Journal of Risk. Winter.
Martellini, L. and Ziemann, V., 2010. Improved estimates of higher-order comoments and implica-
tions for portfolio selection. Review of Financial Studies, 23(4):1467-1502.
Ranaldo, Angelo, and Laurent Favre Sr. 2005. How to Price Hedge Funds: From Two- to Four-
Moment CAPM. SSRN eLibrary.
Scott, Robert C., and Philip A. Horvath. 1980. On the Direction of Preference for Moments of
Higher Order than the Variance. Journal of Finance 35(4):915-919.
Examples
data(managers)
[Link](managers[,1:3,drop=FALSE])
136 [Link]
[Link] clean returns in a time series to to provide more robust risk estimates
Description
A function that provides access to multiple methods for cleaning outliers from return data.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
method one of "none", "boudt", which applies the function [Link] or "geltner"
which applies the function [Link] R
alpha the percentage of outliers you want to clean
... additional parameters passed into the underlying cleaning function
Details
This is a wrapper for offering multiple data cleaning methods for data objects containing returns.
The primary value of data cleaning lies in creating a more robust and stable estimation of the
distribution generating the large majority of the return data. The increased robustness and stability
of the estimated moments using cleaned data should be used for portfolio construction. If an investor
wishes to have a more conservative risk estimate, cleaning may not be indicated for risk monitoring.
In actual practice, it is probably best to back-test the results of both cleaned and uncleaned se-
ries to see what works best when forecasting risk with the particular combination of assets under
consideration.
In this version, only one method is supported. See [Link] for more details.
Author(s)
Peter Carl
See Also
[Link]
[Link]
[Link] 137
Examples
data(managers)
head([Link](managers[,1:4]),n=20)
[Link](managers[,1,drop=FALSE], [Link]=TRUE, clean="boudt", lwd=2, methods="ModifiedVaR")
Description
This is a useful function for calculating cumulative return over a period of time, say a calendar year.
Can produce simple or geometric return.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
Details
Author(s)
Peter Carl
References
Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 6
See Also
[Link]
138 [Link]
Examples
data(managers)
[Link](managers[,1,drop=FALSE])
[Link](managers[,1:8])
[Link](managers[,1:8],geometric=FALSE)
[Link] Calculates the returns of an asset in excess of the given risk free rate
Description
Calculates the returns of an asset in excess of the given "risk free rate" for the period.
Usage
[Link](R, Rf = 0)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns, or as a single digit average
Details
Ideally, your risk free rate will be for each period you have returns observations, but a single average
return for the period will work too.
Mean of the period return minus the period risk free rate
(Ra − Rf )
OR
mean of the period returns minus a single numeric risk free rate
Ra − Rf
Note that while we have, in keeping with common academic usage, assumed that the second pa-
rameter will be a risk free rate, you may also use any other timeseries as the second argument. A
common alteration would be to use a benchmark to produce excess returns over a specific bench-
mark, as demonstrated in the examples below.
Author(s)
Peter Carl
[Link] 139
References
Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 47-52
Examples
data(managers)
head([Link](managers[,1,drop=FALSE], managers[,10,drop=FALSE]))
head([Link](managers[,1,drop=FALSE], .04/12))
head([Link](managers[,1:6], managers[,10,drop=FALSE]))
head([Link](managers[,1,drop=FALSE], managers[,8,drop=FALSE]))
Description
David Geltner developed a method to remove estimating or liquidity bias in real estate index returns.
It has since been applied with success to other return series that show autocorrelation or illiquidity
effects.
Usage
[Link](Ra, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
The theory is that by correcting for autocorrelation, you are uncovering a "true" return from a series
of observed returns that contain illiquidity or manual pricing effects.
The Geltner autocorrelation adjusted return series may be calculated via:
Rt − (Rt−1 · ρ1 )
RG =
1 − ρ1
where ρ1 is the first-order autocorrelation of the return series Ra and Rt is the return of Ra at time
t and Rt−1 is the one-period lagged return.
Author(s)
Brian Peterson
140 [Link]
References
"Edhec Funds of Hedge Funds Reporting Survey : A Return-Based Approach to Funds of Hedge
Funds Reporting",Edhec Risk and Asset Management Research Centre, January 2005,p. 27
Geltner, David, 1991, Smoothing in Appraisal-Based Returns, Journal of Real Estate Finance and
Economics, Vol.4, p.327-345.
Geltner, David, 1993, Estimating Market Values from Appraised Values without Assuming an Effi-
cient Market, Journal of Real Estate Research, Vol.8, p.325-345.
Examples
data(managers)
head([Link](managers[,1:3]),n=20)
Description
Using a time series of returns and any regular or irregular time series of weights for each asset, this
function calculates the returns of a portfolio with the same periodicity of the returns data.
Usage
[Link](R, weights = NULL, [Link] = FALSE,
contribution = FALSE, geometric = TRUE, rebalance_on = c(NA, "years",
"quarters", "months", "weeks", "days"), value = 1, verbose = FALSE, ...)
Arguments
R An xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
weights A time series or single-row matrix/vector containing asset weights, as decimal
percentages, treated as beginning of period weights. See Details below.
[Link] TRUE/FALSE whether to return a wealth index. Default FALSE
contribution if contribution is TRUE, add the weighted return contributed by the asset in a
given period. Default FALSE
geometric utilize geometric chaining (TRUE) or simple/arithmetic (FALSE) to aggregate
returns. Default TRUE.
rebalance_on Default "none"; alternatively "daily" "weekly" "monthly" "annual" to specify
calendar-period rebalancing supported by endpoints. Ignored if weights is an
xts object that specifies the rebalancing dates.
value The beginning of period total portfolio value. This is used for calculating posi-
tion value.
verbose If verbose is TRUE, return a list of intermediary calculations. See Details below.
... any other passthru parameters. Not currently used.
[Link] 141
Details
By default, this function calculates the time series of portfolio returns given asset returns and
weights. In verbose mode, the function returns a list of intermediary calculations that users may
find helpful, including both asset contribution and asset value through time.
When asset return and weights are matched by period, contribution is simply the weighted return
of the asset. c_i = w_i * R_i Contributions are summable across the portfolio to calculate the total
portfolio return.
Contribution cannot be aggregated through time. For example, say we have an equal weighted
portfolio of five assets with monthly returns. The geometric return of the portfolio over several
months won’t match any aggregation of the individual contributions of the assets, particularly if
any rebalancing was done during the period.
To aggregate contributions through time such that they are summable to the geometric returns of
the portfolio, the calculation must track changes in the notional value of the assets and portfolio.
For example, contribution during a quarter will be calculated as the change in value of the position
through those three months, divided by the original value of the portfolio. Approaching it this way
makes the calculation robust to weight changes as well. c_pi = V_(t-p)i - V_t)/V_ti
If the user does not specify weights, an equal weight portfolio is assumed. Alternatively, a vector
or single-row matrix of weights that matches the length of the asset columns may be specified. In
either case, if no rebalancing period is specified, the weights will be applied at the beginning of the
asset time series and no further rebalancing will take place. If a rebalancing period is specified, the
portfolio will be rebalanced to the starting weights at the interval specified.
Note that if weights is an xts object, then any value passed to rebalance_on is ignored. The
weights object specifies the rebalancing dates, therefore a regular rebalancing frequency provided
via rebalance_on is not needed and ignored.
[Link] will work only on daily or lower frequencies. If you are rebalancing intraday,
you should be using a trades/prices framework like the blotter package, not a weights/returns
framework.
Irregular rebalancing can be done by specifying a time series of weights. The function uses the date
index of the weights for xts-style subsetting of rebalancing periods.
Weights specified for rebalancing should be thought of as "end-of-period" weights. Rebalancing
periods can be thought of as taking effect immediately after the close of the bar. So, a March 31
rebalancing date will actually be in effect for April 1. A December 31 rebalancing date will be in
effect on Jan 1, and so forth. This convention was chosen because it fits with common usage, and
because it simplifies xts Date subsetting via endpoints.
In verbose mode, the function returns a list of data and intermediary calculations.
• [Link]: End of Period (BOP) Weight for each asset. An asset’s EOP weight is the sum of
the asset’s BOP weight and contribution for the period divided by the sum of the contributions
and initial weights for the portfolio.
• [Link]: BOP Value for each asset. The BOP value for each asset is the asset’s EOP
value from the prior period, unless there is a rebalance event. If there is a rebalance event,
the BOP value of the asset is the rebalance weight times the EOP value of the portfolio. That
effectively provides a zero-transaction cost change to the position values as of that date to
reflect the rebalance. Note that the sum of the BOP values of the assets is the same as the prior
period’s EOP portfolio value.
• [Link]: EOP Value for each asset. The EOP value is for each asset is calculated as (1 +
asset return) times the asset’s BOP value. The EOP portfolio value is the sum of EOP value
across assets.
To calculate BOP and EOP position value, we create an index for each position. The sum of that
value across assets represents an indexed value of the total portfolio. Note that BOP and EOP
position values are only computed when geometric = TRUE.
From the value calculations, we can calculate different aggregations through time for the asset
contributions. Those are calculated as the EOP asset value less the BOP asset value; that quantity
is divided by the BOP portfolio value. Across assets, those will sum to equal the geometric chained
returns of the portfolio for that same time period. The function does not do this directly, however.
Value
returns a time series of returns weighted by the weights parameter, or a list that includes interme-
diate calculations
Note
This function was previously two functions: [Link] and [Link]. Both
function names are still exported, but the code is now common, and [Link] is probably
to be preferred.
Author(s)
References
Bacon, C. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. Chapter 2
See Also
[Link] endpoints
[Link] 143
Examples
data(edhec)
[Link](edhec["1997",1:5], rebalance_on="quarters") # returns time series
[Link](edhec["1997",1:5], rebalance_on="quarters", verbose=TRUE) # returns list
# with a weights object
data(weights) # rebalance at the beginning of the year to various weights through time
[Link](weights)
x <- [Link](edhec["2000::",1:11], weights=weights,verbose=TRUE)
[Link](x$returns)
[Link](x$[Link])
[Link](x$[Link])
Description
A simple wrapper of [Link] with some defaults for different date formats and xts conversion
Usage
[Link](filename = stop("Please specify a filename"), frequency = c("d",
"m", "q", "i", "o"), [Link] = c("ISO8601", "excel", "oo", "gnumeric"),
sep = ",", header = TRUE, [Link] = FALSE, ...)
Arguments
filename the name of the file to be read
frequency • "d" sets as a daily timeseries using [Link],
• "m" sets as monthly timeseries using [Link],
• "q" sets as a quarterly timeseries using [Link], and
• "i" sets as irregular timeseries using [Link]
[Link] says how the data being read is formatted. Although the default is set to the ISO
8601 standard (which can also be set as " most spreadsheets have less sensible
date formats as defaults. See below.
sep separator, default is ","
header a logical value indicating whether the file contains the names of the variables as
its first line.
[Link] logical. If TRUE then the names of the variables in the data frame are checked
to ensure that they are syntactically valid variable names. If necessary they are
adjusted (by [Link]) so that they are, and also to ensure that there are no
duplicates. See [Link]
... passes through any other parameters to [Link]
144 [Link]
Details
The parameter ’[Link]’ takes several values, including:
excel default date format for MS Excel spreadsheet csv format, which is "%m/%d/%Y"
oo default date format for OpenOffice spreadsheet csv format, "%m/%d/%y", although this may be
operating system dependent
gnumeric default date format for Gnumeric spreadsheet, which is "%d-%b-%Y"
... alternatively, any specific format may be passed in, such as "%M/%y"
Author(s)
Peter Carl
See Also
[Link], [Link]
Examples
## Not run:
[Link]("[Link]", frequency="d")
## End(Not run)
Description
Calculates the ratio of the cumulative performance for two assets through time.
Usage
[Link](Ra, Rb, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return object for the benchmark asset
... ignored
Value
xts or other time series of relative return
Selectivity 145
Author(s)
Peter Carl
See Also
[Link]
Examples
data(managers)
head([Link](managers[,1:3], managers[,8,drop=FALSE]),n=20)
Description
Selectivity is the same as Jensen’s alpha
Usage
Selectivity(Ra, Rb, Rf = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
Details
Selectivity = rp − rf − βp ∗ (b − rf )
where rf is the risk free rate, βr is the regression beta, rp is the portfolio return and b is the
benchmark return
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.78
146 SharpeRatio
Examples
data(portfolio_bacon)
print(Selectivity(portfolio_bacon[,1], portfolio_bacon[,2])) #expected -0.0141
data(managers)
print(Selectivity(managers['1996',1], managers['1996',8]))
print(Selectivity(managers['1996',1:5], managers['1996',8]))
Description
The Sharpe ratio is simply the return per unit of risk (represented by variability). In the classic case,
the unit of risk is the standard deviation of the returns.
Usage
SharpeRatio(R, Rf = 0, p = 0.95, FUN = c("StdDev", "VaR", "ES"),
weights = NULL, annualize = FALSE, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
p confidence level for calculation, default p=.95
FUN one of "StdDev" or "VaR" or "ES" to use as the denominator
weights portfolio weighting vector, default NULL, see Details in VaR
annualize if TRUE, annualize the measure, default FALSE
... any other passthru parameters to the VaR or ES functions
Details
(Ra − Rf )
√
σ(Ra −Rf )
William Sharpe now recommends InformationRatio preferentially to the original Sharpe Ratio.
The higher the Sharpe ratio, the better the combined performance of "risk" and return.
SharpeRatio 147
As noted, the traditional Sharpe Ratio is a risk-adjusted measure of return that uses standard devia-
tion to represent risk.
A number of papers now recommend using a "modified Sharpe" ratio using a Modified Cornish-
Fisher VaR or CVaR/Expected Shortfall as the measure of Risk.
We have recently extended this concept to create multivariate modified Sharpe-like Ratios for stan-
dard deviation, Gaussian VaR, modified VaR, Gaussian Expected Shortfall, and modified Expected
Shortfall. See VaR and ES. You can pass additional arguments to VaR and ES via . . . The most im-
portant is probably the ’method’ argument/
This function returns a traditional or modified Sharpe ratio for the same periodicity of the data being
input (e.g., monthly data -> monthly SR)
Author(s)
Brian G. Peterson
References
Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.
Laurent Favre and Jose-Antonio Galeano. Mean-Modified Value-at-Risk Optimization with Hedge
Funds. Journal of Alternative Investment, Fall 2002, v 5.
See Also
[Link]
InformationRatio
TrackingError
ActivePremium
SortinoRatio
VaR
ES
Examples
data(managers)
SharpeRatio(managers[,1,drop=FALSE], Rf=.035/12, FUN="StdDev")
SharpeRatio(managers[,1,drop=FALSE], Rf = managers[,10,drop=FALSE], FUN="StdDev")
SharpeRatio(managers[,1:6], Rf=.035/12, FUN="StdDev")
SharpeRatio(managers[,1:6], Rf = managers[,10,drop=FALSE], FUN="StdDev")
data(edhec)
SharpeRatio(edhec[, 6, drop = FALSE], FUN="VaR")
SharpeRatio(edhec[, 6, drop = FALSE], Rf = .04/12, FUN="VaR")
SharpeRatio(edhec[, 6, drop = FALSE], Rf = .04/12, FUN="VaR" , method="gaussian")
SharpeRatio(edhec[, 6, drop = FALSE], FUN="ES")
148 [Link]
[Link]
calculate annualized Sharpe Ratio
Description
The Sharpe Ratio is a risk-adjusted measure of return that uses standard deviation to represent risk.
Usage
[Link](R, Rf = 0, scale = NA, geometric = TRUE)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
Details
The Sharpe ratio is simply the return per unit of risk (represented by variance). The higher the
Sharpe ratio, the better the combined performance of "risk" and return.
This function annualizes the number based on the scale parameter.
p
n
prod(1 + Ra )scale − 1
√ √
scale · σ
Using an annualized Sharpe Ratio is useful for comparison of multiple return streams. The an-
nualized Sharpe ratio is computed by dividing the annualized mean monthly excess return by the
annualized monthly standard deviation of excess return.
William Sharpe now recommends Information Ratio preferentially to the original Sharpe Ratio.
Author(s)
Peter Carl
References
Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.
ShrinkageMoments 149
See Also
SharpeRatio
InformationRatio
TrackingError
ActivePremium
SortinoRatio
Examples
data(managers)
[Link](managers[,1,drop=FALSE], Rf=.035/12)
[Link](managers[,1,drop=FALSE], Rf = managers[,10,drop=FALSE])
[Link](managers[,1:6], Rf=.035/12)
[Link](managers[,1:6], Rf = managers[,10,drop=FALSE])
[Link](managers[,1:6], Rf = managers[,10,drop=FALSE],geometric=FALSE)
Description
calculates covariance, coskewness and cokurtosis matrices using linear shrinkage between the sam-
ple estimator and a structured estimator
Usage
[Link](R, targets = 1, f = NULL)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
targets vector of integers selecting the target matrices to shrink to. The first four struc-
tures are, in order: ’independent marginals’, ’independent and identical marginals’,
’observed 1-factor model’ and ’constant correlation’. See Details.
f vector or matrix with observations of the factor, to be used with target 3. See
Details.
unbiasedMSE TRUE/FALSE whether to use a correction to have an unbiased estimator for the
marginal skewness values, in case of targets 1 and/or 2, default FALSE
[Link] TRUE/FALSE whether to return the full moment matrix or only the vector with
the unique elements (the latter is advised for speed), default TRUE
150 ShrinkageMoments
Details
The coskewness and cokurtosis matrices are defined as the matrices of dimension p x p^2 and p x
p^3 containing the third and fourth order central moments. They are useful for measuring nonlinear
dependence between different assets of the portfolio and computing modified VaR and modified ES
of a portfolio.
Shrinkage estimation for the covariance matrix was popularized by Ledoit and Wolf (2003, 2004).
An extension to coskewness and cokurtosis matrices by Martellini and Ziemann (2010) uses the
1-factor and constant-correlation structured comoment matrices as targets. In Boudt, Cornilly and
Verdonck (2017) the framework of single-target shrinkage for the coskewness and cokurtosis ma-
trices is extended to a multi-target setting, making it possible to include several target matrices at
once. Also, an option to enhance small sample performance for coskewness estimation was pro-
posed, resulting in the option ’unbiasedMSE’ present in the ’[Link]’ function.
The first four target matrices of the ’[Link]’, ’[Link]’ and ’[Link]’ correspond to the
models ’independent marginals’, ’independent and identical marginals’, ’observed 1-factor model’
and ’constant correlation’. Coskewness shrinkage includes two more options, target 5 corresponds
to the latent 1-factor model proposed in Simaan (1993) and target 6 is the coskewness matrix under
central-symmetry, a matrix full of zeros. For more details on the targets, we refer to Boudt, Cornilly
and Verdonck (2017) and the supplementary appendix.
If f is a matrix containing multiple factors, then the shrinkage estimator will use each factor in a
seperate single-factor model and use multi-target shrinkage to all targets matrices at once.
Author(s)
Dries Cornilly
References
Boudt, Kris, Brian G. Peterson, and Christophe Croux. 2008. Estimation and Decomposition of
Downside Risk for Portfolios with Non-Normal Returns. Journal of Risk. Winter.
Boudt, Kris, Cornilly, Dries and Verdonck, Tim. 2017. A Coskewness Shrinkage Approach for
Estimating the Skewness of Linear Combinations of Random Variables. Submitted. Available at
SSRN: [Link]
Ledoit, Olivier and Wolf, Michael. 2003. Improved estimation of the covariance matrix of stock
returns with an application to portfolio selection. Journal of empirical finance, 10(5), 603-621.
Ledoit, Olivier and Wolf, Michael. 2004. A well-conditioned estimator for large-dimensional co-
variance matrices. Journal of multivariate analysis, 88(2), 365-411.
Martellini, Lionel and Ziemann, V\"olker. 2010. Improved estimates of higher-order comoments
and implications for portfolio selection. Review of Financial Studies, 23(4), 1467-1502.
Simaan, Yusif. 1993. Portfolio selection and asset pricing: three-parameter framework. Manage-
ment Science, 39(5), 68-577.
See Also
CoMoments
StructuredMoments
EWMAMoments
MCA
skewness 151
Examples
data(edhec)
skewness Skewness
Description
compute skewness of a univariate distribution.
Usage
skewness(x, [Link] = FALSE, method = c("moment", "fisher", "sample"), ...)
Arguments
x a numeric vector or object.
[Link] a logical. Should missing values be removed?
method a character string which specifies the method of computation. These are either
"moment" or "fisher" The "moment" method is based on the definitions of
skewnessfor distributions; these forms should be used when resampling (boot-
strap or jackknife). The "fisher" method correspond to the usual "unbiased"
definition of sample variance, although in the case of skewness exact unbiased-
ness is not possible. The "sample" method gives the sample skewness of the
distribution.
152 skewness
Details
This function was ported from the RMetrics package fUtilities to eliminate a dependency on fUtilti-
ies being loaded every time. The function is identical except for the addition of checkData and column support.
n
1 X ri − r 3
Skewness(moment) = ∗ ( )
n i=1 σP
X ri − r n
n
Skewness(sample) = ∗ ( )3
(n − 1) ∗ (n − 2) i=1 σSP
√
n∗(n−1) Pn 3
n−2 ∗ i=1 xn
Skewness(f isher) = Pn x2 3/2
i=1 ( n )
where n is the number of return, r is the mean of the return distribution, σP is its standard deviation
and σSP is its sample standard deviation
Author(s)
Diethelm Wuertz, Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.83-84
See Also
kurtosis
Examples
## mean -
## var -
# Mean, Variance:
r = rnorm(100)
mean(r)
var(r)
## skewness -
skewness(r)
data(managers)
skewness(managers)
SkewnessKurtosisRatio 153
Description
Skewness-Kurtosis ratio is the division of Skewness by Kurtosis.
Usage
SkewnessKurtosisRatio(R, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
It is used in conjunction with the Sharpe ratio to rank portfolios. The higher the rate the better.
S
SkewnessKurtosisRatio(R, M AR) =
K
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.100
Examples
data(portfolio_bacon)
print(SkewnessKurtosisRatio(portfolio_bacon[,1])) #expected -0.034
data(managers)
print(SkewnessKurtosisRatio(managers['1996']))
print(SkewnessKurtosisRatio(managers['1996',1]))
154 SmoothingIndex
Description
Proposed by Getmansky et al to provide a normalized measure of "liquidity risk."
Usage
SmoothingIndex(R, [Link] = FALSE, MAorder = 2, verbose = FALSE, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
[Link] if FALSE, function removes negative coefficients (thetas) when calculating the
index
MAorder specify the number of periods used to calculate the moving average, defaults to
2
verbose if TRUE, return a list containing the Thetas in addition to the smoothing index/
... any other passthru parameters
Details
To measure the effects of smoothing, Getmansky, Lo, et al (2004) define a "smoothing profile" as a
vector of coefficients for an MLE fit on returns using a two-period moving-average process.
The moving-average process of order k = 2 (specified using MAorder) gives Rt = θ0 Rt +θ1 Rt−1 +
θ2 Rt−2 , under the constraint that the sum of the coefficients is equal to 1. In , the arima function
allows us to create an MA(2) model using an "ARIMA(p,d,q)" model, where p is the number of
autoregressive terms (AR), d is the degree of differencing, and q is the number of lagged forecast
errors (MA) in the prediction equation. The order parameter allows us to specify the three com-
ponents (p, d, q) as an argument, e.g., order = c(0, 0, 2). The method specifies how to fit
the model, in this case using maximum likelihood estimation (MLE) in a fashion similar to the
estimation of standard moving-average time series models, using:
arima(ra, order=c(0,0,2), method="ML", [Link]=TRUE,[Link]=FALSE)
[Link]: Getmansky, et al. (2004) p 555 "By applying the above procedure to observed
de-meaned returns...", so we set that parameter to ’FALSE’.
[Link]: ibid, "we impose the additional restriction that the estimated MA(k) process be
invertible," so we set the parameter to ’TRUE’.
The coefficients, θj , are then normalized to sum to interpreted as a "weighted average of the fund’s
true returns over the most recent k + 1 periods, including the current period."
If these weights are disproportionately centered on a small number of lags, relatively little serial
correlation will be induced. However, if the weights are evenly distributed among many lags, this
would show higher serial correlation.
sortDrawdowns 155
The paper notes that because θj ∈ [0, 1], ξ is also confined to the unit interval, and is minimized
when all the θj ’s are identical. That implies a value of 1/(k + 1) for ξ, and a maximum value of
ξ = 1 when one coefficient is 1 and the rest are 0. In the context of smoothed returns, a lower value
of ξ implies more smoothing, and the upper bound of 1 implies no smoothing.
The "smoothing index", represented as ξ, is calculated the same way the Herfindahl index. The
Herfindal measure is well known in the industrial organization literature as a measure of the con-
centration of firms in a given industry where yj represents the market share of firm j.
This method (as well as the implementation described in the paper), does not enforce θj ∈ [0, 1], so
ξ is not limited to that range either. All we can say is that lower values are "less liquid" and higher
values are "more liquid" or mis-specified. In this function, setting the parameter [Link] = FALSE
does enforce the limitation, eliminating negative autocorrelation coefficients from the calculation
(the papers below do not make an economic case for eliminating negative autocorrelation, however).
Interpretation of the resulting value is difficult. All we can say is that lower values appear to have
autocorrelation structure like we might expect of "less liquid" instruments. Higher values appear
"more liquid" or are poorly fit or mis-specified.
Acknowledgments
Thanks to Dr. Stefan Albrecht, CFA, for invaluable input.
Author(s)
Peter Carl
References
Chan, Nicholas, Mila Getmansky, Shane M. Haas, and Andrew W. Lo. 2005. Systemic Risk
and Hedge Funds. NBER Working Paper Series (11200). Getmansky, Mila, Andrew W. Lo, and
Igor Makarov. 2004. An Econometric Model of Serial Correlation and Illiquidity in Hedge Fund
Returns. Journal of Financial Economics (74): 529-609.
Examples
data(managers)
data(edhec)
SmoothingIndex(managers[,1,drop=FALSE])
SmoothingIndex(managers[,1:8])
SmoothingIndex(edhec)
Description
sortDrawdowns(findDrawdowns(R)) Gives the drawdowns in order of worst to best
156 sortDrawdowns
Usage
sortDrawdowns(runs)
Arguments
Details
Author(s)
Peter Carl
modified with permission from prototype function by Sankalp Upadhyay
References
See Also
DownsideDeviation
maxDrawdown
findDrawdowns
sortDrawdowns
[Link]
[Link]
[Link]
Examples
data(edhec)
findDrawdowns(edhec[,"Funds of Funds", drop=FALSE])
sortDrawdowns(findDrawdowns(edhec[,"Funds of Funds", drop=FALSE]))
SortinoRatio 157
Description
Sortino proposed an improvement on the Sharpe Ratio to better account for skill and excess perfor-
mance by using only downside semivariance as the measure of risk.
Usage
SortinoRatio(R, MAR = 0, ..., weights = NULL)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
... any other passthru parameters
weights portfolio weighting vector, default NULL
Details
Sortino contends that risk should be measured in terms of not meeting the investment goal. This
gives rise to the notion of “Minimum Acceptable Return” or MAR. All of Sortino’s proposed mea-
sures include the MAR, and are more sensitive to downside or extreme risks than measures that use
volatility(standard deviation of returns) as the measure of risk.
Choosing the MAR carefully is very important, especially when comparing disparate investment
choices. If the MAR is too low, it will not adequately capture the risks that concern the investor, and
if the MAR is too high, it will unfavorably portray what may otherwise be a sound investment. When
comparing multiple investments, some papers recommend using the risk free rate as the MAR.
Practitioners may wish to choose one MAR for consistency, several standardized MAR values for
reporting a range of scenarios, or a MAR customized to the objective of the investor.
(Ra − M AR)
SortinoRatio =
δM AR
where δM AR is the DownsideDeviation.
Author(s)
Brian G. Peterson
References
Sortino, F. and Price, L. Performance Measurement in a Downside Risk Framework. Journal of
Investing. Fall 1994, 59-65.
158 SpecificRisk
See Also
SharpeRatio
DownsideDeviation
SemiVariance
SemiDeviation
InformationRatio
Examples
data(managers)
round(SortinoRatio(managers[, 1]),4)
round(SortinoRatio(managers[, 1:8]),4)
Description
Specific risk is the standard deviation of the error term in the regression equation.
Usage
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.75
StdDev 159
Examples
data(portfolio_bacon)
print(SpecificRisk(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.0329
data(managers)
print(SpecificRisk(managers['1996',1], managers['1996',8]))
print(SpecificRisk(managers['1996',1:5], managers['1996',8]))
Description
calculates Standard Deviation for univariate and multivariate series, also calculates component con-
tribution to standard deviation of a portfolio
Usage
StdDev(R, ..., clean = c("none", "boudt", "geltner"),
portfolio_method = c("single", "component"), weights = NULL, mu = NULL,
sigma = NULL, use = "everything", method = c("pearson", "kendall",
"spearman"))
Arguments
R a vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
clean method for data cleaning through [Link]. Current options are "none",
"boudt", or "geltner".
portfolio_method
one of "single","component" defining whether to do univariate/multivariate or
component calc, see Details.
weights portfolio weighting vector, default NULL, see Details
mu If univariate, mu is the mean of the series. Otherwise mu is the vector of means
of the return series , default NULL, , see Details
sigma If univariate, sigma is the variance of the series. Otherwise sigma is the covari-
ance matrix of the return series , default NULL, see Details
use an optional character string giving a method for computing covariances in the
presence of missing values. This must be (an abbreviation of) one of the strings
"everything", "[Link]", "[Link]", "[Link]", or "[Link]".
method a character string indicating which correlation coefficient (or covariance) is to
be computed. One of "pearson" (default), "kendall", or "spearman", can be
abbreviated.
160 [Link]
Details
TODO add more details
This wrapper function provides fast matrix calculations for univariate, multivariate, and component
contributions to Standard Deviation.
It is likely that the only one that requires much description is the component decomposition. This
provides a weighted decomposition of the contribution each portfolio element makes to the univari-
ate standard deviation of the whole portfolio.
Formally, this is the partial derivative of each univariate standard deviation with respect to the
weights.
As with VaR, this contribution is presented in two forms, both a scalar form that adds up to the
univariate standard deviation of the portfolio, and a percentage contribution, which adds up to 100
as with any contribution calculation, contribution can be negative. This indicates that the asset in
question is a diversified to the overall standard deviation of the portfolio, and increasing its weight
in relation to the rest of the portfolio would decrease the overall portfolio standard deviation.
Author(s)
Brian G. Peterson and Kris Boudt
See Also
[Link] sd
Examples
data(edhec)
Description
Standard Deviation of a set of observations Ra is given by:
[Link] 161
Usage
Arguments
x an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
... any other passthru parameters
Details
√
σ = variance(Ra ), std = σ
It should follow that the variance is not a linear function of the number of observations. To deter-
mine possible variance over multiple periods, it wouldn’t make sense to multiply the single-period
variance by the total number of periods: this could quickly lead to an absurd result where total
variance (or risk) was greater than 100 variance needs to demonstrate a decreasing period-to-period
increase as the number of periods increases. Put another way, the increase in incremental vari-
ance per additional period needs to decrease with some relationship to the number of periods. The
standard accepted practice for doing this is to apply the inverse square law. To normalize standard
deviation across multiple periods, we multiply by the square root of the number of periods we wish
to calculate over. To annualize standard deviation, we multiply by the square root of the number of
periods per year.
√ p
σ· periods
Note that any multiperiod or annualized number should be viewed with suspicion if the number of
observations is small.
Author(s)
Brian G. Peterson
References
See Also
sd
[Link]
162 StructuredMoments
Examples
data(edhec)
[Link](edhec)
[Link](edhec[,6,drop=FALSE])
# now for three periods:
[Link](edhec[,6,drop=FALSE],scale=3)
Description
calculates covariance, coskewness and cokurtosis matrices as structured estimators
Usage
[Link](R, struct = c("Indep", "IndepId", "observedfactor", "CC"),
f = NULL)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
struct string containing the preferred method. See Details.
f vector or matrix with observations of the factor, to be used with ’observedfactor’.
See Details.
unbiasedMarg TRUE/FALSE whether to use a correction to have an unbiased estimator for the
marginal skewness values, in case of ’Indep’ or ’IndepId’, default FALSE
[Link] TRUE/FALSE whether to return the full moment matrix or only the vector with
the unique elements (the latter is advised for speed), default TRUE
Details
The coskewness and cokurtosis matrices are defined as the matrices of dimension p x p^2 and p x
p^3 containing the third and fourth order central moments. They are useful for measuring nonlinear
dependence between different assets of the portfolio and computing modified VaR and modified ES
of a portfolio.
StructuredMoments 163
Structured estimation is based on the assumption that the underlying data-generating process is
known, or at least resembles the assumption. The first four structured estimators correspond to
the models ’independent marginals’, ’independent and identical marginals’, ’observed multi-factor
model’ and ’constant correlation’. Coskewness estimation includes an additional model based on
the latent 1-factor model proposed in Simaan (1993).
The constant correlation and 1-factor coskewness and cokurtosis matrices can be found in Martellini
and Ziemann (2010). If f is a matrix containing multiple factors, then the multi-factor model of
Boudt, Lu and Peeters (2915) is used. For information about the other structured matrices, we refer
to Boudt, Cornilly and Verdonck (2017)
Author(s)
Dries Cornilly
References
Boudt, Kris, Lu, Wanbo and Peeters, Benedict. 2015. Higher order comoments of multifactor
models and asset allocation. Finance Research Letters, 13, 225-233.
Boudt, Kris, Brian G. Peterson, and Christophe Croux. 2008. Estimation and Decomposition of
Downside Risk for Portfolios with Non-Normal Returns. Journal of Risk. Winter.
Boudt, Kris, Cornilly, Dries and Verdonck, Tim. 2017. A Coskewness Shrinkage Approach for
Estimating the Skewness of Linear Combinations of Random Variables. Submitted. Available at
SSRN: [Link]
Ledoit, Olivier and Wolf, Michael. 2003. Improved estimation of the covariance matrix of stock
returns with an application to portfolio selection. Journal of empirical finance, 10(5), 603-621.
Martellini, Lionel and Ziemann, V\"olker. 2010. Improved estimates of higher-order comoments
and implications for portfolio selection. Review of Financial Studies, 23(4), 1467-1502.
Simaan, Yusif. 1993. Portfolio selection and asset pricing: three-parameter framework. Manage-
ment Science, 39(5), 68-577.
See Also
CoMoments
ShrinkageMoments
EWMAMoments
MCA
Examples
data(edhec)
Description
Systematic risk as defined by Bacon(2008) is the product of beta by market risk. Be careful ! It’s
not the same definition as the one given by Michael Jensen. Market risk is the standard deviation of
the benchmark. The systematic risk is annualized
Usage
SystematicRisk(Ra, Rb, Rf = 0, scale = NA, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
... any other passthru parameters
Details
σs = β ∗ σm
where σs is the systematic risk, β is the regression beta, and σm is the market risk
Author(s)
Matthieu Lestel
[Link] 165
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.75
Examples
data(portfolio_bacon)
print(SystematicRisk(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.013
data(managers)
print(SystematicRisk(managers['1996',1], managers['1996',8]))
print(SystematicRisk(managers['1996',1:5], managers['1996',8]))
[Link]
Annualized Returns Summary: Statistics and Stylized Facts
Description
Table of Annualized Return, Annualized Std Dev, and Annualized Sharpe
Usage
[Link](R, scale = NA, Rf = 0, geometric = TRUE,
digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
Rf risk free rate, in same period as your returns
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
digits number of digits to round results to
Author(s)
Peter Carl
See Also
[Link]
[Link]
[Link]
166 [Link]
Examples
data(managers)
[Link](managers[,1:8])
require("Hmisc")
result = t([Link](managers[,1:8], Rf=.04/12))
title(main="Annualized Performance")
[Link] wrapper function for combining arbitrary function list into a table
Description
This function creates a table of statistics from vectors of functions and labels passed in. The result-
ing table is formatted such that metrics are calculated separately for each column of returns in the
data object.
Usage
[Link](R, metrics = c("mean", "sd"),
metricsNames = c("Average Return", "Standard Deviation"), ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
metrics lisdt of functions to apply
metricsNames column names for each function
... any other passthru parameters
Details
Assumes an input of period returns. Scale arguements can be used to specify the number of obser-
vations during a year (e.g., 12 = monthly returns).
The idea here is to be able to pass in sets of metrics and values, like:
metrics = c(DownsideDeviation(x,MAR=mean(x)), sd(subset(x,x>0)), sd(subset(x,x<0)), Down-
sideDeviation(x,MAR=MAR), DownsideDeviation(x,MAR=Rf=0), DownsideDeviation(x,MAR=0),maxDrawdown(x))
metricsNames = c("Semi Deviation", "Gain Deviation", "Loss Deviation", paste("Downside Devi-
ation (MAR=",MAR*scale*100," paste("Downside Deviation (rf=",rf*scale*100," Deviation (0
[Link] 167
Passing in two different sets of attributes to the same function doesn’t quite work currently. The
issue is apparent in: > [Link](edhec,metrics=c("VaR", "VaR"), metricsNames=c("Modified
VaR","Traditional VaR"), modified=c(TRUE,FALSE))
In the case of this example, you would simply call VaR as the second function, like so: > ta-
[Link](edhec,metrics=c("VaR", "VaR"),metricsNames=c("Modified VaR","Traditional VaR"))
but we don’t know of a way to compare the same function side by side with different parameters for
each. Suggestions Welcome.
Author(s)
Peter Carl
Examples
data(edhec)
[Link](edhec,metrics=c("VaR", "ES"),
metricsNames=c("Modified VaR","Modified Expected Shortfall"))
168 [Link]
[Link] table for calculating the first six autocorrelation coefficients and sig-
nificance
Description
Produces data table of autocorrelation coefficients ρ and corresponding Q(6)-statistic for each col-
umn in R.
Usage
[Link](R, digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
digits number of digits to round results to for display
Note
To test returns for autocorrelation, Lo (2001) suggests the use of the Ljung-Box test, a significance
test for the auto-correlation coefficients. Ljung and Box (1978) provide a refinement of the Q-
statistic proposed by Box and Pierce (1970) that offers a better fit for the χ2 test for small sample
sizes. [Link] provides both.
Author(s)
Peter Carl
References
Lo, Andrew W. 2001. Risk Management for Hedge Funds: Introduction and Overview. SSRN
eLibrary.
See Also
[Link], acf
Examples
data(managers)
t([Link](managers))
result = t([Link](managers[,1:8]))
title(main="Autocorrelation")
Description
Returns a table of returns formatted with years in rows, months in columns, and a total column in
the last column. For additional columns in R, annual returns will be appended as columns.
Usage
[Link](R, digits = 1, [Link] = TRUE, geometric = TRUE)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
digits number of digits to round results to for presentation
[Link] TRUE/FALSE if TRUE, multiply simple returns by 100 to get %
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
Note
This function assumes monthly returns and does not currently have handling for other scales.
This function defaults to the first column as the monthly returns to be formatted.
Author(s)
Peter Carl
Examples
data(managers)
t([Link](managers[,c(1,7,8)]))
title(main="Calendar Returns")
[Link] Calculate and display a table of capture ratio and related statistics
Description
Creates a table of capture ratios and similar metrics for a set of returns against a benchmark.
Usage
[Link](Ra, Rb, digits = 4)
Arguments
Ra a vector of returns to test, e.g., the asset to be examined
Rb a matrix, [Link], or timeSeries of benchmark(s) to test the asset against.
digits number of digits to round results to for presentation
Details
This table will show statistics pertaining to an asset against a set of benchmarks, or statistics
for a set of assets against a benchmark. [Link] shows only the capture ratio;
[Link] shows three: the capture ratio, the number ratio, and the percentage ratio.
Author(s)
Peter Carl
See Also
UpDownRatios, [Link]
Examples
data(managers)
[Link](managers[,1:6], managers[,7,drop=FALSE])
[Link](managers[,1:6], managers[,7,drop=FALSE])
Description
This is a wrapper for calculating correlation and significance against each column of the data pro-
vided.
Usage
[Link](Ra, Rb, ...)
Arguments
Ra a vector of returns to test, e.g., the asset to be examined
Rb a matrix, [Link], or timeSeries of benchmark(s) to test the asset against.
... any other passthru parameters to [Link]
Author(s)
Peter Carl
See Also
[Link]
Examples
result=[Link](managers[,1:6],managers[,8])
rownames(result)=colnames(managers[,1:6])
require("Hmisc")
textplot([Link](result, [Link]=TRUE, [Link]=FALSE,
cdec=rep(3,dim(result)[2])), rmar = 0.8, cmar = 1.5,
[Link]=.9, halign = "center", valign = "top", [Link]="center"
, [Link]=20, [Link]=10, mar = c(0,0,3,0)+0.1)
title(main="Correlations to SP500 TR")
172 [Link]
Description
Table of Monthly standard deviation, Skewness, Sample standard deviation, Kurtosis, Excess kur-
tosis, Sample Skweness and Sample excess kurtosis
Usage
[Link](R, scale = NA, digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
digits number of digits to round results to
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.87
See Also
[Link]
skewness
kurtosis
Examples
data(managers)
[Link](managers[,1:8])
require("Hmisc")
result = t([Link](managers[,1:8]))
Description
Creates a table of estimates of downside risk measures for comparison across multiple instruments
or funds.
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
ci confidence interval, defaults to 95%
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
Rf risk free rate, in same period as your returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
p confidence level for calculation, default p=.99
digits number of digits to round results to
Author(s)
Peter Carl
See Also
DownsideDeviation
maxDrawdown
VaR
ES
174 [Link]
Examples
data(edhec)
[Link](edhec, Rf=.04/12, MAR =.05/12, p=.95)
[Link]
Downside Summary: Statistics and ratios
Description
Table of Monthly downside risk, Annualised downside risk, Downside potential, Omega, Sortino
ratio, Upside potential, Upside potential ratio and Omega-Sharpe ratio
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
scale number of periods in a year (daily scale = 252, monthly scale =
digits number of digits to round results to
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.98
[Link] 175
See Also
CalmarRatio
BurkeRatio
PainIndex
UlcerIndex
PainRatio
MartinRatio
Examples
data(managers)
[Link](managers[,1:8])
require("Hmisc")
result = t([Link](managers[,1:8]))
Description
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
top the number of drawdowns to include
digits number of digits to round results to
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
... any other passthru parameters
176 [Link]
Details
Returns an data frame with columns:
Author(s)
Peter Carl
References
Bacon, C. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 88
See Also
DownsideDeviation
maxDrawdown
findDrawdowns
sortDrawdowns
[Link]
[Link]
Examples
data(edhec)
[Link](edhec[,1,drop=FALSE])
[Link](edhec[,12,drop=FALSE])
data(managers)
[Link](managers[,8,drop=FALSE])
result=[Link](managers[,1,drop=FALSE])
# This was really nice before Hmisc messed up 'format' from R-base
#require("Hmisc")
#textplot(Hmisc::[Link](result, [Link]=TRUE, [Link]=FALSE,
# cdec=c(rep(3,4), rep(0,3))), rmar = 0.8, cmar = 1.5,
# [Link]=.9, halign = "center", valign = "top", [Link]="center",
# [Link]=5, [Link]=10, mar = c(0,0,3,0)+0.1)
# title(main="Largest Drawdowns for HAM1")
[Link] 177
Description
Table of Calmar ratio, Sterling ratio, Burke ratio, Pain index, Ulcer index, Pain ratio and Martin
ratio
Usage
[Link](R, Rf = 0, scale = NA, digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rf risk free rate, in same period as your returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
digits number of digits to round results to
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.93
See Also
CalmarRatio
BurkeRatio
PainIndex
UlcerIndex
PainRatio
MartinRatio
Examples
data(managers)
[Link](managers[,1:8])
require("Hmisc")
result = t([Link](managers[,1:8], Rf=.04/12))
178 [Link]
Description
Summary of the higher moements and Co-Moments of the return distribution. Used to determine
diversification potential. Also called "systematic" moments by several papers.
Usage
[Link](Ra, Rb, scale = NA, Rf = 0, digits = 4,
method = "moment")
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
Rf risk free rate, in same period as your returns
digits number of digits to round results to
method method to use when computing kurtosis one of: excess, moment, fisher
Author(s)
Peter Carl
References
Martellini L., Vaissie M., Ziemann V. Investing in Hedge Funds: Adding Value through Active
Style Allocation Decisions. October 2005. Edhec Risk and Asset Management Research Centre.
See Also
CoSkewness
CoKurtosis
BetaCoVariance
BetaCoSkewness
BetaCoKurtosis
skewness
kurtosis
[Link] 179
Examples
data(managers)
[Link](managers[,1:3],managers[,8,drop=FALSE])
result=t([Link](managers[,1:6],managers[,8,drop=FALSE]))
rownames(result)=colnames(managers[,1:6])
require("Hmisc")
textplot([Link](result, [Link]=TRUE, [Link]=FALSE,
cdec=rep(3,dim(result)[2])), rmar = 0.8, cmar = 1.5,
[Link]=.9, halign = "center", valign = "top", [Link]="center",
[Link]=5, [Link]=10, mar = c(0,0,3,0)+0.1)
title(main="Higher Co-Moments with SP500 TR")
[Link]
Information ratio Summary: Statistics and Stylized Facts
Description
Table of Tracking error, Annualised tracking error and Information ratio
Usage
[Link](R, Rb, scale = NA, digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
digits number of digits to round results to
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.81
See Also
InformationRatio
TrackingError
180 [Link]
Examples
data(managers)
[Link](managers[,1:8], managers[,8])
require("Hmisc")
result = t([Link](managers[,1:8], managers[,8]))
[Link]
Outperformance Report of Asset vs Benchmark
Description
Table of Outperformance Reporting vs Benchmark
Usage
[Link](R, Rb, period_lengths = c(1, 3, 6, 9, 12, 18, 36))
Arguments
R an xts, timeSeries or zoo object of asset returns
Rb an xts, timeSeries or zoo object of the benchmark returns
period_lengths a vector of periods the user wants to evaluate this over i.e. c(1,3,6,9,12,18,36)
Details
Returns a table that contains the counts and probabilities of outperformance relative to benchmark
for the various period_lengths
Tool for robustness analysis of an asset or strategy, can be used to give the probability an investor
investing at any point in time will outperform the benchmark over a given horizon. Calculates Count
of trailing periods where a fund outperformed its benchmark and calculates the proportion of those
periods, this is commonly used in marketing as the probability of outperformance on a N period
basis.
Returns a table that contains the counts and probabilities of outperformance relative to benchmark
for the various period_lengths
[Link] 181
Author(s)
Kyle Balkissoon
Examples
data(edhec)
[Link](edhec[,1],edhec[,2])
title(main='Table of Convertible Arbitrage vs Benchmark')
Description
A table of estimates of rolling period return measures
Usage
[Link](R, periods = subset(c(12, 36, 60), c(12, 36, 60) <
length([Link](R[, 1]))), FUNCS = c("mean", "sd"),
[Link] = c("Average", "Std Dev"), digits = 4, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
periods number of periods to use as rolling window(s), subset of c(3, 6, 9, 12, 18, 24, 36, 48)
FUNCS list of functions to apply the rolling period to
[Link] vector of function names used for labeling table rows
digits number of digits to round results to
... any other passthru parameters for functions specified in FUNCS
Rb an xts, vector, matrix, data frame, timeSeries or zoo object of index, benchmark,
portfolio, or secondary asset returns to compare against
Author(s)
Peter Carl
See Also
rollapply
182 [Link]
Examples
data(edhec)
[Link](edhec[,10:13], periods=c(12,24,36))
result=[Link](edhec[,10:13], periods=c(12,24,36))
require("Hmisc")
textplot([Link](result, [Link]=TRUE, [Link]=FALSE,
cdec=rep(3,dim(result)[2])), rmar = 0.8, cmar = 1.5,
[Link]=.9, halign = "center", valign = "top", [Link]="center",
[Link]=15, [Link]=10, mar = c(0,0,3,0)+0.1)
title(main="Trailing Period Statistics")
Description
Takes a set of returns and relates them to a benchmark return. Provides a set of measures related to
an excess return single factor model, or CAPM.
Usage
[Link](Ra, Rb, scale = NA, Rf = 0, digits = 4)
Arguments
Ra a vector of returns to test, e.g., the asset to be examined
Rb a matrix, [Link], or timeSeries of benchmark(s) to test the asset against.
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
Rf risk free rate, in same period as your returns
digits number of digits to round results to
Details
This table will show statistics pertaining to an asset against a set of benchmarks, or statistics for a
set of assets against a benchmark.
Author(s)
Peter Carl
[Link] 183
See Also
[Link]
[Link]
TrackingError
ActivePremium
InformationRatio
TreynorRatio
Examples
data(managers)
[Link](managers[,1:3], managers[,8], Rf = managers[,10])
Description
Table of specific risk, systematic risk and total risk
Usage
[Link](Ra, Rb, Rf = 0, digits = 4)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
digits number of digits to round results to
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.76
184 [Link]
See Also
SystematicRisk
SpecificRisk
TotalRisk
Examples
data(managers)
[Link](managers[,1:8], managers[,8])
require("Hmisc")
result = t([Link](managers[,1:8], managers[,8], Rf=.04/12))
Description
Returns a basic set of statistics that match the period of the data passed in (e.g., monthly returns
will get monthly statistics, daily will be daily stats, and so on)
Usage
[Link](R, ci = 0.95, digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
ci confidence interval, defaults to 95%
digits number of digits to round results to
Details
This was created as a way to display a set of related statistics together for comparison across a set of
instruments or funds. Careful consideration to missing data or unequal time series should be given
when intepreting the results.
Author(s)
Peter Carl
[Link] 185
Examples
data(edhec)
[Link](edhec[,1:3])
t([Link](edhec))
result=t([Link](edhec))
require("Hmisc")
textplot([Link](result, [Link]=TRUE, [Link]=FALSE, cdec=c(rep(1,2),rep(3,14))),
rmar = 0.8, cmar = 1.5, [Link]=.9, halign = "center", valign = "top",
[Link]="center", [Link]=10, [Link]=10, mar = c(0,0,3,0)+0.1)
title(main="Statistics for EDHEC Indexes")
Description
Table of Mean absolute difference, Monthly standard deviation and annualised standard deviation
Usage
[Link](R, scale = NA, geometric = TRUE, digits = 4)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
geometric utilize geometric chaining (TRUE) or simple/arithmetic chaining (FALSE) to
aggregate returns, default TRUE
digits number of digits to round results to
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.65
See Also
[Link]
MeanAbsoluteDeviation
186 [Link]
Examples
data(managers)
[Link](managers[,1:8])
require("Hmisc")
result = t([Link](managers[,1:8]))
[Link]
Aggregate contributions through time
Description
Higher frequency contributions provided as a time series are converted to a lower frequency for a
specified calendar period.
Usage
[Link](Contributions, period = c("years", "quarters",
"months", "weeks", "all"))
Arguments
Contributions a time series of the per period contribution to portfolio return of each asset
period period to convert to. See details. "weeks", "months", "quarters", "years", or
"all".
Details
From the portfolio contributions of individual assets, such as those of a particular asset class or
manager, the multiperiod contribution is neither summable from nor the geometric compounding
of single-period contributions. Because the weights of the individual assets change through time as
transactions occur, the capital base for the asset changes.
Instead, the asset’s multiperiod contribution is the sum of the asset’s dollar contributions from each
period, as calculated from the wealth index of the total portfolio. Once contributions are expressed
in cumulative terms, asset contributions then sum to the returns of the total portfolio for the period.
Valid period character strings for period include: "weeks", "months", "quarters", "years", or "all".
These are calculated internally via endpoints. See that function’s help page for further details.
For the special period "all", the contribution is calculated over all rows, giving a single contribution
across all observations.
TotalRisk 187
Author(s)
Peter Carl, with thanks to Paolo Cavatore
References
Morningstar, Total Portfolio Performance Attribution Methodology, p.36. Available at http://
[Link]/US/documents/MethodologyDocuments/MethodologyPapers/TotalPortfolioPerforma
pdf
See Also
[Link]
endpoints
Examples
data(managers, package="PerformanceAnalytics")
[Link](res_qtr_rebal$contribution, period="years")
[Link](res_qtr_rebal$contribution)
Description
The square of total risk is the sum of the square of systematic risk and the square of specific risk.
Specific risk is the standard deviation of the error term in the regression equation. Both terms are
annualized to calculate total risk.
Usage
TotalRisk(Ra, Rb, Rf = 0, ...)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
... any other passthru parameters
188 TrackingError
Details
p
T otalRisk = SystematicRisk 2 + Specif icRisk 2
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.75
Examples
data(portfolio_bacon)
print(TotalRisk(portfolio_bacon[,1], portfolio_bacon[,2])) #expected 0.0134
data(managers)
print(TotalRisk(managers['1996',1], managers['1996',8]))
print(TotalRisk(managers['1996',1:5], managers['1996',8]))
Description
A measure of the unexplained portion of performance relative to a benchmark.
Usage
TrackingError(Ra, Rb, scale = NA)
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
Details
Tracking error is calculated by taking the square root of the average of the squared deviations
between the investment’s returns and the benchmark’s returns, then multiplying the result by the
square root of the scale of the returns.
s
X (Ra − Rb )2
T rackingError = √
len(Ra ) scale
TreynorRatio 189
Author(s)
Peter Carl
References
See Also
InformationRatio TrackingError
Examples
data(managers)
TrackingError(managers[,1,drop=FALSE], managers[,8,drop=FALSE])
TrackingError(managers[,1:6], managers[,8,drop=FALSE])
TrackingError(managers[,1:6], managers[,8:7,drop=FALSE])
Description
The Treynor ratio is similar to the Sharpe Ratio, except it uses beta as the volatility measure (to
divide the investment’s excess return over the beta).
Usage
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
Rf risk free rate, in same period as your returns
scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly
scale = 4)
modified a boolean to decide whether to return the Treynor ratio or Modified Treynor ratio
190 UlcerIndex
Details
To calculate modified Treynor ratio, we divide the numerator by the systematic risk instead of the
beta.
Equation:
(Ra − Rf )
T reynorRatio =
βa,b
rp − rf
M odif iedT reynorRatio =
σs
Author(s)
References
See Also
Examples
data(portfolio_bacon)
data(managers)
round(TreynorRatio(managers[,1], managers[,8], Rf=.035/12),4)
round(TreynorRatio(managers[,1], managers[,8], Rf = managers[,10]),4)
round(TreynorRatio(managers[,1:6], managers[,8], Rf=.035/12),4)
round(TreynorRatio(managers[,1:6], managers[,8], Rf = managers[,10]),4)
round(TreynorRatio(managers[,1:6], managers[,8:7], Rf=.035/12),4)
round(TreynorRatio(managers[,1:6], managers[,8:7], Rf = managers[,10]),4)
Description
Developed by Peter G. Martin in 1987 (Martin and McCann, 1987) and named for the worry caused
to the portfolio manager or investor. This is similar to drawdown deviation except that the impact
of the duration of drawdowns is incorporated by selecting the negative return for each period below
the previous peak or high water mark. The impact of long, deep drawdowns will have significant
impact because the underperformance since the last peak is squared.
Usage
UlcerIndex(R, ...)
Arguments
R a vector, matrix, data frame, timeSeries or zoo object of asset returns
... any other passthru parameters
Details
UI = sqrt(sum[i=1,2,...,n](D’_i^2/n)) where D’_i = drawdown since previous peak in period i
DETAILS: This approach is sensitive to the frequency of the time periods involved and penalizes
managers that take time to recover to previous highs.
REFERENCES: Martin, P. and McCann, B. (1989) The investor’s Guide to Fidelity Funds: Winning
Strategies for Mutual Fund Investors. John Wiley & Sons, Inc. Peter Martin’s web page on UI:
[Link]
## Test against spreadsheet at: [Link]
Author(s)
Matthieu Lestel
UpDownRatios calculate metrics on up and down markets for the benchmark asset
Description
Calculate metrics on how the asset in R performed in up and down markets, measured by periods
when the benchmark asset was up or down.
Usage
UpDownRatios(Ra, Rb, method = c("Capture", "Number", "Percent"),
side = c("Up", "Down"))
192 UpDownRatios
Arguments
Ra an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
Rb return vector of the benchmark asset
method "Capture", "Number", or "Percent" to indicate which measure to return
side "Up" or "Down" market statistics
Details
Author(s)
Peter Carl
References
Examples
data(managers)
UpDownRatios(managers[,1, drop=FALSE], managers[,8, drop=FALSE])
UpDownRatios(managers[,1:6, drop=FALSE], managers[,8, drop=FALSE])
UpDownRatios(managers[,1, drop=FALSE], managers[,8, drop=FALSE], method="Capture")
# Up Capture:
UpDownRatios(managers[,1, drop=FALSE], managers[,8, drop=FALSE], side="Up", method="Capture")
# Down Capture:
UpDownRatios(managers[,1, drop=FALSE], managers[,8, drop=FALSE], side="Down", method="Capture")
UpsideFrequency 193
Description
To calculate Upside Frequency, we take the subset of returns that are more than the target (or
Minimum Acceptable Returns (MAR)) returns and divide the length of this subset by the total
number of returns.
Usage
UpsideFrequency(R, MAR = 0, ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
... any other passthru parameters
Details
n
X max[(Rt − M AR), 0]
U psideF requency(R, M AR) =
t=1
Rt ∗ n
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.94
Examples
data(portfolio_bacon)
MAR = 0.005
print(UpsideFrequency(portfolio_bacon[,1], MAR)) #expected 0.542
data(managers)
print(UpsideFrequency(managers['1996']))
print(UpsideFrequency(managers['1996',1])) #expected 0.75
194 UpsidePotentialRatio
Description
Sortino proposed an improvement on the Sharpe Ratio to better account for skill and excess perfor-
mance by using only downside semivariance as the measure of risk. That measure is the SortinoRatio.
This function, Upside Potential Ratio, was a further improvement, extending the measurement of
only upside on the numerator, and only downside of the denominator of the ratio equation.
Usage
UpsidePotentialRatio(R, MAR = 0, method = c("subset", "full"))
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
method one of "full" or "subset", indicating whether to use the length of the full series or
the length of the subset of the series above(below) the MAR as the denominator,
defaults to "subset"
Details
calculate Upside Potential Ratio of upside performance over downside risk
Sortino proposed an improvement on the Sharpe Ratio to better account for skill and excess perfor-
mance by using only downside semivariance as the measure of risk. That measure is the SortinoRatio.
This function, Upside Potential Ratio, was a further improvement, extending the measurement of
only upside on the numerator, and only downside of the denominator of the ratio equation.
Sortino contends that risk should be measured in terms of not meeting the investment goal. This
gives rise to the notion of “Minimum Acceptable Return” or MAR. All of Sortino’s proposed mea-
sures include the MAR, and are more sensitive to downside or extreme risks than measures that use
volatility(standard deviation of returns) as the measure of risk.
Choosing the MAR carefully is very important, especially when comparing disparate investment
choices. If the MAR is too low, it will not adequately capture the risks that concern the investor, and
if the MAR is too high, it will unfavorably portray what may otherwise be a sound investment. When
comparing multiple investments, some papers recommend using the risk free rate as the MAR.
Practitioners may wish to choose one MAR for consistency, several standardized MAR values for
reporting a range of scenarios, or a MAR customized to the objective of the investor.
Pn
t=1 (Rt − M AR)
UPR =
δM AR
where δM AR is the DownsideDeviation.
UpsideRisk 195
The numerator in UpsidePotentialRatio only uses returns that exceed the MAR, and the denomi-
nator (in DownsideDeviation) only uses returns that fall short of the MAR by default. Sortino con-
tends that this is a more accurate and balanced protrayal of return potential, wherase SortinoRatio
can reward managers most at the peak of a cycle, without adequately penalizing them for past
mediocre performance. Others have used the full series, and this is provided as an option by the
method argument.
Author(s)
Brian G. Peterson
References
Sortino, F. and Price, L. Performance Measurement in a Downside Risk Framework. Journal of
Investing. Fall 1994, 59-65.
Plantinga, A., van der Meer, R. and Sortino, F. The Impact of Downside Risk on Risk-Adjusted
Performance of Mutual Funds in the Euronext Markets. July 19, 2001. Available at SSRN: http:
//[Link]/abstract=277352
See Also
SharpeRatio
SortinoRatio
DownsideDeviation
SemiVariance
SemiDeviation
InformationRatio
Examples
data(edhec)
UpsidePotentialRatio(edhec[, 6], MAR=.05/12) #5 percent/yr MAR
UpsidePotentialRatio(edhec[, 1:6], MAR=0)
Description
Upside Risk is the similar of semideviation taking the return above the Minimum Acceptable Return
instead of using the mean return or zero. To calculate it, we take the subset of returns that are more
than the target (or Minimum Acceptable Returns (MAR)) returns and take the differences of those
to the target. We sum the squares and divide by the total number of returns and return the square
root.
196 UpsideRisk
Usage
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
method one of "full" or "subset", indicating whether to use the length of the full series
or the length of the subset of the series below the MAR as the denominator,
defaults to "full"
stat one of "risk", "variance" or "potential" indicating whether to return the Upside
risk, variance or potential
... any other passthru parameters
Details
v
u n
uX max[(Rt − M AR), 0]2
U psideRisk(R, M AR) = t
t=1
n
n
X max[(Rt − M AR), 0]2
U psideV ariance(R, M AR) =
t=1
n
n
X max[(Rt − M AR), 0]
U psideP otential(R, M AR) =
t=1
n
where n is either the number of observations of the entire series or the number of observations in
the subset of the series falling below the MAR.
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
VaR 197
Examples
data(portfolio_bacon)
MAR = 0.005
print(UpsideRisk(portfolio_bacon[,1], MAR, stat="risk")) #expected 0.02937
print(UpsideRisk(portfolio_bacon[,1], MAR, stat="variance")) #expected 0.08628
print(UpsideRisk(portfolio_bacon[,1], MAR, stat="potential")) #expected 0.01771
MAR = 0
data(managers)
print(UpsideRisk(managers['1996'], MAR, stat="risk"))
print(UpsideRisk(managers['1996',1], MAR, stat="risk")) #expected 1.820
Description
Calculates Value-at-Risk(VaR) for univariate, component, and marginal cases using a variety of
analytical methods.
Usage
VaR(R = NULL, p = 0.95, ..., method = c("modified", "gaussian",
"historical", "kernel"), clean = c("none", "boudt", "geltner"),
portfolio_method = c("single", "component", "marginal"), weights = NULL,
mu = NULL, sigma = NULL, m3 = NULL, m4 = NULL, invert = TRUE)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
p confidence level for calculation, default p=.95
... any other passthru parameters
method one of "modified","gaussian","historical", "kernel", see Details.
clean method for data cleaning through [Link]. Current options are "none",
"boudt", or "geltner".
portfolio_method
one of "single","component","marginal" defining whether to do univariate, com-
ponent, or marginal calc, see Details.
weights portfolio weighting vector, default NULL, see Details
mu If univariate, mu is the mean of the series. Otherwise mu is the vector of means
of the return series, default NULL, see Details
sigma If univariate, sigma is the variance of the series. Otherwise sigma is the covari-
ance matrix of the return series, default NULL, see Details
198 VaR
Background
This function provides several estimation methods for the Value at Risk (typically written as VaR) of
a return series and the Component VaR of a portfolio. Take care to capitalize VaR in the commonly
accepted manner, to avoid confusion with var (variance) and VAR (vector auto-regression). VaR
is an industry standard for measuring downside risk. For a return series, VaR is defined as the
high quantile (e.g. ~a 95 quantile) of the negative value of the returns. This quantile needs to
be estimated. With a sufficiently large data set, you may choose to utilize the empirical quantile
calculated using quantile. More efficient estimates of VaR are obtained if a (correct) assumption
is made on the return distribution, such as the normal distribution. If your return series is skewed
and/or has excess kurtosis, Cornish-Fisher estimates of VaR can be more appropriate. For the VaR
of a portfolio, it is also of interest to decompose total portfolio VaR into the risk contributions of
each of the portfolio components. For the above mentioned VaR estimators, such a decomposition
is possible in a financially meaningful way.
Note
The option to invert the VaR measure should appease both academics and practitioners. The
mathematical definition of VaR as the negative value of a quantile will (usually) produce a positive
number. Practitioners will argue that VaR denotes a loss, and should be internally consistent with
the quantile (a negative number). For tables and charts, different preferences may apply for clarity
and compactness. As such, we provide the option, and set the default to TRUE to keep the return
consistent with prior versions of PerformanceAnalytics, but make no value judgment on which
approach is preferable.
The prototype of the univariate Cornish Fisher VaR function was completed by Prof. Diethelm
Wuertz. All corrections to the calculation and error handling are the fault of Brian Peterson.
Author(s)
Brian G. Peterson and Kris Boudt
References
Boudt, Kris, Peterson, Brian, and Christophe Croux. 2008. Estimation and decomposition of down-
side risk for portfolios with non-normal returns. 2008. The Journal of Risk, vol. 11, 79-103.
Cont, Rama, Deguest, Romain and Giacomo Scandolo. Robustness and sensitivity analysis of risk
measurement procedures. Financial Engineering Report No. 2007-06, Columbia University Center
for Financial Engineering.
Denton M. and Jayaraman, J.D. Incremental, Marginal, and Component VaR. Sunguard. 2004.
Epperlein, E., Smillie, A. Cracking VaR with kernels. RISK, 2006, vol. 19, 70-74.
VaR 199
Gourieroux, Christian, Laurent, Jean-Paul and Olivier Scaillet. Sensitivity analysis of value at risk.
Journal of Empirical Finance, 2000, Vol. 7, 225-245.
Keel, Simon and Ardia, David. Generalized marginal risk. Aeris CAPITAL discussion paper.
Laurent Favre and Jose-Antonio Galeano. Mean-Modified Value-at-Risk Optimization with Hedge
Funds. Journal of Alternative Investment, Fall 2002, v 5.
Martellini, L. and Ziemann, V., 2010. Improved estimates of higher-order comoments and implica-
tions for portfolio selection. Review of Financial Studies, 23(4):1467-1502.
Return to RiskMetrics: Evolution of a Standard [Link]
Zangari, Peter. A VaR Methodology for Portfolios that include Options. 1996. RiskMetrics Moni-
tor, First Quarter, 4-12.
Rockafellar, Terry and Uryasev, Stanislav. Optimization of Conditional VaR. The Journal of Risk,
2000, vol. 2, 21-41.
Dowd, Kevin. Measuring Market Risk, John Wiley and Sons, 2010.
Jorian, Phillippe. Value at Risk, the new benchmark for managing financial risk. 3rd Edition,
McGraw Hill, 2006.
Hallerback, John. "Decomposing Portfolio Value-at-Risk: A General Analysis", 2003. The Journal
of Risk vol 5/2.
Yamai and Yoshiba (2002). "Comparative Analyses of Expected Shortfall and Value-at-Risk: Their
Estimation Error, Decomposition, and Optimization", Bank of Japan.
See Also
[Link]
[Link]
[Link]
Examples
data(edhec)
# now use modified Cornish Fisher calc to take non-normal distribution into account
VaR(edhec, p=.95, method="modified")
Description
Volatility skewness is a similar measure to omega but using the second partial moment. It’s the ratio
of the upside variance compared to the downside variance. Variability skewness is the ratio of the
upside risk compared to the downside risk.
Usage
VolatilitySkewness(R, MAR = 0, stat = c("volatility", "variability"), ...)
Arguments
R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns
MAR Minimum Acceptable Return, in the same periodicity as your returns
stat one of "volatility", "variability" indicating whether to return the volatility skew-
ness or the variability skweness
... any other passthru parameters
Details
2
σU
V olatilitySkewness(R, M AR) = 2
σD
σU
V ariabilitySkewness(R, M AR) =
σD
Author(s)
Matthieu Lestel
References
Carl Bacon, Practical portfolio performance measurement and attribution, second edition 2008
p.97-98
weights 201
Examples
data(portfolio_bacon)
MAR = 0.005
print(VolatilitySkewness(portfolio_bacon[,1], MAR, stat="volatility")) #expected 1.32
print(VolatilitySkewness(portfolio_bacon[,1], MAR, stat="variability")) #expected 1.15
MAR = 0
data(managers)
# print(VolatilitySkewness(managers['1996'], MAR, stat="volatility"))
print(VolatilitySkewness(managers['1996',1], MAR, stat="volatility"))
Description
An xts object that contains columns of monthly weights for a subset of the EDHEC hedge fund
indexes that demonstrate rebalancing portfolios through time.
Note that all the EDHEC indices are available in edhec.
Usage
managers
Format
Details
Examples
data(weights)
zerofill zerofill
Description
Fill NA’s with zeros in a time series to allow analysis when the data must be complete.
Usage
zerofill(x)
Arguments
x time series to zero fill
Details
Note that this function has risks, use carefully. Complete data is preferred. Barring that, filling a
small percentage of results in the middle of a large set is unlikely to cause problems. Barring that,
realize that this will skew your results.
Index
203
204 INDEX
zerofill, 202
zoo, 5