The PerformanceAnalytics Package

July 10, 2007

Type Package

Title Econometric tools for performance and risk analysis.

Version 0.9.5

Date 2007-06-29

Author Peter Carl, Brian G. Peterson

Maintainer Brian G. Peterson

Description Library of econometric functions for performance and risk analysis. This library aims to aid practitioners and researchers in utilizing the latest research in analysis of non-normal return streams. In general, this library is most tested on return (rather than price) data on a monthly scale, but most functions will work with daily or irregular return data as well.

Depends (>= 2.4.0), fExtremes, fPortfolio, quadprog, tseries, Hmisc

License GPL

URL http://braverock.com/R/

R topics documented:

ActivePremium ...... 3 BetaCoKurtosis ...... 4 BetaCoSkewness ...... 5 BetaCoVariance ...... 6 CAPM.alpha ...... 8 CAPM.beta ...... 9 CAPM.utils ...... 11 CalculateReturns ...... 13 CalmarRatio ...... 14 CoKurtosis ...... 15 CoSkewness ...... 16 DownsideDeviation ...... 17 InformationRatio ...... 19

1 2 R topics documented:

KellyRatio ...... 20 Omega...... 21 PerformanceAnalytics-internal ...... 23 PerformanceAnalytics-package ...... 25 Return.annualized ...... 35 Return.cumulative ...... 36 Return.excess ...... 37 SemiDeviation ...... 39 SharpeRatio ...... 40 SharpeRatio.annualized ...... 41 SharpeRatio.modified ...... 43 SortinoRatio ...... 44 sd.multiperiod ...... 46 TrackingError ...... 47 TreynorRatio ...... 48 UpDownRatios ...... 50 UpsidePotentialRatio ...... 51 VaR.Beyond ...... 53 VaR.CornishFisher ...... 54 VaR.Marginal ...... 57 apply.fromstart ...... 58 apply.rolling ...... 59 chart.Bar ...... 60 chart.BarVaR ...... 61 chart.Boxplot ...... 63 chart.Correlation ...... 64 chart.Correlation.color ...... 65 chart.CumReturns ...... 66 chart.Drawdown ...... 67 chart.Histogram ...... 68 chart.QQPlot ...... 70 chart.RegressionDiagnostics ...... 71 chart.RelativePerformance ...... 72 chart.RiskReturnScatter ...... 73 chart.RollingCorrelation ...... 75 chart.RollingMean ...... 76 chart.RollingPerformance ...... 77 chart.RollingRegression ...... 79 chart.Scatter ...... 81 chart.TimeSeries ...... 82 charts.PerformanceSummary ...... 84 charts.RollingPerformance ...... 86 checkData ...... 87 cum.utils ...... 88 download.RiskFree ...... 89 download.SP500PriceReturns ...... 90 edhec ...... 91 findDrawdowns ...... 92 ActivePremium 3

managers ...... 93 maxDrawdown ...... 94 mean.utils ...... 95 moment.fourth ...... 96 moment.third ...... 97 rollingCorrelation ...... 98 rollingFunction ...... 99 rollingRegression ...... 101 rollingStat ...... 102 sortDrawdowns ...... 103 statsTable ...... 104 table.AnnualizedReturns ...... 105 table.CAPM ...... 106 table.Correlation ...... 108 table.DownsideRisk ...... 109 table.Drawdowns ...... 110 table.HigherMoments ...... 111 table.MonthlyReturns ...... 113 table.Returns ...... 114 table.RollingPeriods ...... 115

Index 117

ActivePremium Active Premium

Description The return on an investment’s annualized return minus the benchmark’s annualized return. Active Premium = Investment’s annualized return - Benchmark’s annualized return

Usage ActivePremium(Ra, Rb, scale = 12)

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)

Value ActivePremium (numeric) 4 BetaCoKurtosis

Note

Author(s) Peter Carl

References Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.

See Also InformationRatio TrackingError Return.annualized

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y")

ActivePremium(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE])

BetaCoKurtosis systematic kurtosis of an asset to the initial portfolio

Description Beta CoKurtosis is the beta of an asset to the kurtosis of an initial portfolio. Used to determine diversification potential. Also called "systematic kurtosis" or "systematic cokurtosis" by several papers.

Usage BetaCoKurtosis( Ra, Ri, na.rm = FALSE, method = c("moment", "excess", "fisher")) BetaCoSkewness 5

Arguments Ra return vector of asset being considered for addition to portfolio Ri return vector of initial portfolio na.rm TRUE/FALSE Remove NA’s from the returns? method method to use when computing kurtosis one of: excess, moment, fisher

Details

CoK P((R − R¯ )(R − R¯ )3) K = a,b = a a b b BCoK(Ra, Rb) = CoK(Ra, Rb)/kurtosis(Ra) a,b P 4 Sa (Ra − R¯a)

Value systematic kurtosis of two assets

Note

Author(s) Brian G. Peterson

References Martellini L., Vaissie M., Ziemann V., October 2005. Investing in Hedge Funds: Adding Value through Active Style Allocation Decisions. Edhec Risk and Asset Management Research Centre

See Also CoKurtosis kurtosis

Examples

BetaCoSkewness systematic skewness of an asset to an initial portfolio

Description Beta CoSkewness is the beta of an asset to the skewness of an initial portfolio. Used to determine diversification potential. also called "systematic skewness" or "systematic co-skewness" by several papers. 6 BetaCoSkewness

Usage

BetaCoSkewness(Ra,Ri, na.rm = FALSE)

Arguments

Ra return vector of asset being considered for addition to portfolio Ri return vector of initial portfolio na.rm TRUE/FALSE Remove NA’s from the returns?

Details

CoS P((R − R¯ )(R − R¯ )2) S = a,b = a a b b a,b P 3 Sa (Ra − R¯a)

Value

systematic skewness of asset to an initial portfolio

Note

Author(s)

Brian G. Peterson

References

Martellini L., Vaissie M., Ziemann V., October 2005. Investing in Hedge Funds: Adding Value through Active Style Allocation Decisions. Edhec Risk and Asset Management Research Centre. Equation [5] p. 10

See Also

CoSkewness skewness

Examples BetaCoVariance 7

BetaCoVariance systematic beta of an asset to an initial portfolio

Description Beta covariance is the beta of an asset to the variance and covariance of an initial portfolio. Used to determine diversification potential. also called "systematic beta" by several papers. This function uses a symbolic representation to achieve the same result as the linear intercept model used by CAPM.beta

Usage BetaCoVariance(Ra, Ri, na.rm = FALSE)

Arguments Ra return vector of asset being considered for addition to portfolio Ri return vector of initial portfolio na.rm TRUE/FALSE Remove NA’s from the returns?

Details

Systematic Beta βa,b P ¯ ¯ CoVa,b ((Ra−Ra)(Rb−Rb)) βa,b = = P 2 σa (Ra−R¯a) Ruppert(2004) reports that this equation will give the estimated slope of the linear regression of Raon Rb and that this slope can be used to determine the risk premium or excess expected return (see Ruppert Eq. 7.9 and 7.10, p. 230-231)

Value systematic beta of the asset to the benchmark

Note

Author(s) Brian G. Peterson

References Favre, L. and Renaldo, A.. How to Price Hedge Funds: From Two- to Four-Moment CAPM. October 2003. UBS and Edhec Business School. Equation [5] p 10 Ruppert, David. Statistics and Finance, an Introduction. Springer. 2004. 8 CAPM.alpha

See Also CAPM.beta

Examples

CAPM.alpha calculate CAPM alpha

Description This is a wrapper for calculating a CAPM alpha. "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 performance relative to a benchmark.

Usage CAPM.alpha(Ra, Rb, rf = 0)

Arguments Ra a 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

Value CAPM alpha

Note

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 CAPM.beta CAPM.utils CAPM.beta 9

Examples

# First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) rf.zoo = download.RiskFree(start = start, end = end) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) time(rf.zoo) = as.yearmon(time(rf.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y") time(rf.zoo) = as.Date(time(rf.zoo),format="%b %Y")

CAPM.alpha(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE], rf = rf.zoo)

CAPM.beta calculate CAPM beta

Description

CAPM Beta is the beta of an asset to the variance and covariance of an initial portfolio. Used to determine diversification potential. also called "systematic beta" by several papers. This function uses a linear intercept model to achieve the same results as the symbolic model used by BetaCoVariance

Usage

CAPM.beta(Ra, Rb, rf = 0, digits = 4)

Arguments

Ra a 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 10 CAPM.beta

Details

CoV P((R − R¯ )(R − R¯ )) β = a,b = a a b b a,b P 2 σa (Ra − R¯a)

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)

Value systematic beta of an asset to the index

Note

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 BetaCoVariance CAPM.alpha CAPM.utils

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) rf.zoo = download.RiskFree(start = start, end = end) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) time(rf.zoo) = as.yearmon(time(rf.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y") time(rf.zoo) = as.Date(time(rf.zoo),format="%b %Y") CAPM.utils 11

CAPM.beta(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE], rf = rf.zoo)

CAPM.utils utility functions for 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 CAPM.CML.slope(Rb, rf = 0 ) CAPM.CML(Ra, Rb, rf = 0) CAPM.RiskPremium(Ra, rf = 0) CAPM.SML.slope(Rb, rf = 0)

Arguments Ra a 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 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 CAPM.beta. For the benchmark asset this will be 1 over the risk premium of the benchmark asset. 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. 12 CAPM.utils

CAPM.RiskPremium is the premium returned to the investor over the risk free asset

(Ra − Rf )

CAPM.CML calculates the expected return of the asset against the benchmark Capital Market Line CAPM.CML.slope calculates the slope of the Capital Market Line for looking at how a particular asset compares to the CML CAPM.SML.slope calculates the slope of the Security Market Line for looking at how a particular asset compares to the SML created by the benchmark

Value CAPM value for function called

Note

Author(s) Brian G. Peterson

References Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58. 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 CAPM.beta CAPM.alpha SharpeRatio InformationRatio TrackingError ActivePremium

Examples data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) rf = download.RiskFree(start = start, end = end)

Rb = edhec[,"Funds.of.Funds"]

CAPM.CML.slope(Rb, rf )

CAPM.CML(edhec[,"Equity.Market.Neutral"], Rb, rf)

CAPM.RiskPremium(Rb, rf) CalculateReturns 13

CAPM.RiskPremium(edhec[,"Equity.Market.Neutral"], rf)

CAPM.SML.slope(Rb, rf)

# should create plots like in Ruppert 7.1 7.2

CalculateReturns calculate simple or compound returns from prices

Description calculate simple or compound returns from prices

Usage CalculateReturns(prices, method=c("compound","simple"))

Arguments prices data object containing ordered price observations method calculate "simple" or "compound" returns, default compound

Value vector or matrix of simple or compound returns

Author(s) Peter Carl

References

See Also Return.cumulative

Examples require(tseries) prices = get.hist.quote("^gspc", start = "1999-01-01", end = "2007-01-01", quote = "Close", compression = "m") returns = CalculateReturns(prices, method="simple") colnames(returns)="SP500" 14 CalmarRatio

CalmarRatio calculate a Calmar or Sterling reward/risk ratio

Description Calmar and Sterling Ratios are yet another method of creating a risk-adjusted measure for ranking investments similar to the SharpeRatio.

Usage CalmarRatio(Ra, scale = 12) SterlingRatio(Ra, scale = 12, excess=.1)

Arguments Ra a 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 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%. 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 opin- ion of this author that newer measures such as Sortino’s UpsidePotentialRatio or Favre’s SharpeRatio.modified are both “better” measures, and should be preferred to the Calmar or Sterling Ratio.

Value Calmar or Sterling Reward/Risk Ratio

Note

Author(s) Brian G. Peterson CoKurtosis 15

References Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004.

See Also Return.annualized, maxDrawdown, SharpeRatio.modified, UpsidePotentialRatio

Examples data(edhec) lapply(edhec,CalmarRatio) lapply(edhec,SterlingRatio)

CoKurtosis calculate the co-moment for kurtosis of two assets

Description CoKurtosis is the product of the fourth higher moments of two assets.

Usage CoKurtosis( Ra, Ri, na.rm = FALSE )

Arguments Ra return vector of asset being considered for addition to portfolio Ri return vector of initial portfolio na.rm TRUE/FALSE Remove NA’s from the returns?

Details

X 3 CoKa,b = ((Ra − R¯a)(Ri − R¯i) )

Value value of cokurtosis of Ri and Ra

Note 16 CoSkewness

Author(s) Brian G. Peterson

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. Equation [5] p. 10 Martellini L. and Ziemann V. 2005. Marginal Impacts on Portfolio Distributions. Working Paper, Edhec Risk and Asset Management Research Centre

See Also BetaCoKurtosis kurtosis

Examples

CoSkewness calculate the co-moment for skewness of two assets

Description CoSkewness is the product of the third higher moments of two assets.

Usage CoSkewness( Ra, Ri, na.rm = FALSE )

Arguments Ra return vector of asset being considered for addition to portfolio Ri return vector of initial portfolio na.rm TRUE/FALSE Remove NA’s from the returns?

Details

X 2 CoSa,b = ((Ra − R¯a)(Ri − R¯i) )

Value value of coskewness of Ri and Ra

Note DownsideDeviation 17

Author(s) Brian G. Peterson

References Martellini L., Vaissie M., Ziemann V. October 2005. Investing in Hedge Funds: Adding Value through Active Style Allocation Decisions. Edhec Risk and Asset Management Research Centre. Equation [5] p. 10 Martellini L. and Ziemann V. 2005. Marginal Impacts on Portfolio Distributions. Working Paper, Edhec Risk and Asset Management Research Centre

See Also BetaCoSkewness skewness

Examples

DownsideDeviation function for downside risk of the return distribution

Description Downside deviation is an alternative measure of dounside risk.

Usage DownsideDeviation(Ra, MAR = 0)

Arguments Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns MAR Minimum Acceptable Return, in the same periodicity as your returns

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). 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.

r Pn (R − MAR)2 DownsideDeviation(R, MAR) = δ = t=1 t MAR n 18 DownsideDeviation

This is also useful for calculating semi-deviation or semivariance by setting MAR = mean(x) 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.

Value

Note

Author(s)

Peter Carl

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://ssrn.com/abstract=277352

http://www.sortino.com/htm/performance.htm see especially end note 10

See Also

Examples

data(edhec) head(edhec[,6,drop=FALSE]) sd(edhec[,6]) DownsideDeviation(edhec[,6]) # MAR 0% DownsideDeviation(edhec[,6], MAR = .04/12) #MAR 4% DownsideDeviation(edhec[,6], MAR = mean(edhec[,6])) #MAR = mean return, calculate semivariance InformationRatio 19

InformationRatio InformationRatio = ActivePremium/TrackingError

Description The Active Premium divided by the Tracking Error. 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.

Usage InformationRatio(Ra, Rb, scale = 12)

Arguments Ra a 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 William Sharpe now recommends InformationRatio preferentially to the original SharpeRatio.

Value information ratio (number)

Note

Author(s) Peter Carl

References Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.

See Also TrackingError ActivePremium SharpeRatio 20 KellyRatio

Examples data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) sp500 = download.SP500PriceReturns(start="1996-12-31",end=end) InformationRatio(edhec[,13],sp500)

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(Ra, rf = 0, method="half")

Arguments Ra a vector of returns to perform a mean over rf risk free rate, in same period as your returns method method=half will use the half-Kelly, this is the default

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 Kelly criterion says: f should equal the expected excess return of the strategy divided by the ex- pected variance of the excess return, or

(R − R ) leverage = s f StdDev(R)2

As a performance metric, the Kelly Ratio calculated retrospectively on a particular investment will give you a measure of the edge that investment has over the risk free rate. It may be use as a stack ranking method to compare investments in a manner similar to the various ratios related to the Sharpe ratio. Omega 21

Value

Kelly Ratio or Bet/Leverage Size

Note

Author(s)

Brian G. Peterson

References

Thorp, Edward O. (1997; revised 1998). The Kelly Criterion in Blackjack, Sports Betting, and the Stock Market. http://www.bjmath.com/bjmath/thorp/paper.htm http://en.wikipedia.org/wiki/Kelly_criterion

See Also

Examples

data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) end = rownames(edhec[edhec.length,])

rf.zoo = download.RiskFree(start = start, end = end)

for (i in 1:ncol(edhec)) {print(colnames(edhec)[i]); print(KellyRatio(edhec[,i],rf=rf.zoo))}

Omega calculate Omega for a return series

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) 22 Omega

Arguments R a 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, in same period as your returns

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) * E[max(x - L, 0)] exp(-rf) * E[max(L - x, 0)] with exp(-rf) calculating the present values of the two, where rf is the per-period riskless rate. 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.

Value

Author(s) Peter Carl PerformanceAnalytics-internal 23

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)

for(i in 1:13) { print(colnames(edhec)[i]); print(Omega(edhec[,i], method="simple")) }

Omega(edhec[,13],method="interp",output="point")

Omega(edhec[,13],method="interp",output="full")

PerformanceAnalytics-internal internal functions for setting useful defaults for graphs

Description Internal functions and data objects to make graphs easier to read, and better for print and presenta- tion. Also contains common economic cycle dates and dates of serious market events per asset class.

Usage legend(x, y = NULL, legend, fill = NULL, col = par("col"), lty, lwd, pch, angle = 45, density = NULL, bty = "o", bg = par("bg"), pt.bg = NA, cex = 1, pt.cex = cex, pt.lwd = lwd, xjust = 0, yjust = 1, x.intersp = 1, y.intersp = 1, adj = c(0, 0.5), text.width = NULL, text.col = par("col"), merge = do.lines && has.pch, trace = FALSE, plot = TRUE, ncol = 1, horiz = FALSE, title = NULL, inset = 0, border.col = NULL, border.lwd = 1, border.lty = "solid")

Arguments x, y the x and y co-ordinates to be used to position the legend. They can be specified by keyword or in any way which is accepted by xy.coords: See Details. legend a character or expression vector. of length ≥ 1 to appear in the legend. fill if specified, this argument will cause boxes filled with the specified colors (or shaded in the specified colors) to appear beside the legend text. col the color of points or lines appearing in the legend. lty, lwd the line types and widths for lines appearing in the legend. One of these two must be specified for line drawing. pch the plotting symbols appearing in the legend, either as vector of 1-character strings, or one (multi character) string. Must be specified for symbol drawing. angle angle of shading lines. 24 PerformanceAnalytics-internal

density the density of shading lines, if numeric and positive. If NULL or negative or NA color filling is assumed. bty the type of box to be drawn around the legend. The allowed values are "o" (the default) and "n". bg the background color for the legend box. (Note that this is only used if bty != "n".) box.lty, box.lwd the line type and width for the legend box. pt.bg the background color for the points, corresponding to its argument bg. cex character expansion factor relative to current par("cex"). pt.cex expansion factor(s) for the points. pt.lwd line width for the points, defaults to the one for lines, or if that is not set, to par("lwd"). xjust how the legend is to be justified relative to the legend x location. A value of 0 means left justified, 0.5 means centered and 1 means right justified. yjust the same as xjust for the legend y location. x.intersp character interspacing factor for horizontal (x) spacing. y.intersp the same for vertical (y) line distances. adj numeric of length 1 or 2; the string adjustment for legend text. Useful for y- adjustment when labels are plotmath expressions. text.width the width of the legend text in x ("user") coordinates. (Should be posi- tive even for a reversed x axis.) Defaults to the proper value computed by strwidth(legend). text.col the color used for the legend text. merge logical; if TRUE, “merge” points and lines but not filled boxes. Defaults to TRUE if there are points and lines. trace logical; if TRUE, shows how legend does all its magical computations. plot logical. If FALSE, nothing is plotted but the sizes are returned. ncol the number of columns in which to set the legend items (default is 1, a vertical legend). horiz logical; if TRUE, set the legend horizontally rather than vertically (specifying horiz overrides the ncol specification). title a character string or length-one expression giving a title to be placed at the top of the legend. inset inset distance(s) from the margins as a fraction of the plot region when legend is placed by keyword.

Details All items ending in .labels or .dates contain labels or dates that would be appropriate for specific asset classes or economic cycles. legend is a wrapper function for legend to better handle placement and formatting of a legend for the charts all objects ending in symbol are symbol sets for line charts. PerformanceAnalytics-package 25

See Also legend

Examples

PerformanceAnalytics-package Econometric tools for performance and risk analysis.

Description Library of econometric functions for performance and risk analysis of financial portfolios. This library aims to aid practitioners and researchers in using the latest research in analysis of both normal and non-normal return streams. We created this library 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 wrapper functions for functionality easily replicated in R, so that we could access that functionality using a function with defaults and naming consistent with common usage in the finance literature. The following sections cover Performance Analysis, Risk Analysis (with a separate treatment of VaR), Summary Tables of related statistics, Charts and Graphs, a variety of Wrappers and Utility functions, and some thoughts on work yet to be done.

Details

Package: PerformanceAnalytics Type: Package Version: 0.9.5 Date: 2007-06-29 License: GPL Copyright: (c) 2004-2007 Brian G. Peterson and Peter Carl URL: http://braverock.com/R/

In general, this library is most tested on return (rather than price) data on a monthly scale. Many functions will work with daily or irregular return data as well. See function CalculateReturns for calculating returns from prices, and be aware that the aggregate function has methods for tseries and zoo timeseries data classes to rationally coerce irregular data into regular data of the correct periodicity.

In this summary, we attempt to provide an overview of the capabilities provided by PerformanceAnalytics and pointers to other literature and resources in R needed 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. 26 PerformanceAnalytics-package

Performance Analysis Performance measurement is the first step down a longer road. When discussing performance at an abstract level, terms such as “return” and “risk” are deliberately vague because they help to disguise some (usually unnecessary) complexity. Scratch the surface to answer more complicated questions, and that complexity is necessarily uncovered again. Indeed, the literature around the subject of performance analysis seems to have exploded with the popularity of alternative assets such as hedge funds, managed futures, commodities, and structured products. Simpler tools that seemed appropriate in a relative investment world seem inappropriate for an absolute return world. Risk measurement, which is nearly inseparable from performance assessment, has been on a long march to become multi-dimensional and multi-moment while trying to answer the 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 before 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. Proprietary traders will object, complaining that “You can’t eat returns,” and will prefer to look at 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 financial econometrics, however, is focused on returns rather than prices. 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 useful statistical qualities. As a result, the PerformanceAnalytics library focuses on returns. See CalculateReturns for convert- ing net asset values or prices into returns, either discrete or continuous. Many papers and theories refer to “excess returns”: we have implemented the most common methods of calculating excess returns in function Return.excess. See pfolioReturn in package fPortfolio for calculating returns from a portfolio of instru- ments with a combination of historical returns and a weighting vector. See package portfolio for a more sophisticated class-based collection of positions into a historical portfolio, allowing you to track changes in the composition of a portfolio over time. Returns and risk may be annualized as a way to simplify comparison over longer time periods. Although it requires a bit of estimating, such aggregation is popular because it offers a reference point for easy comparison. Examples are in Return.annualized, sd.annualized, and SharpeRatio.annualized. Basic measures of performance tend to treat returns as independent observations. In this case, the entirety of R’s base is applicable to such analysis. Some basic statistics we have collected in table.MonthlyReturns include:

mean arithmetic mean mean.geometric geometric mean mean.stderr standard error of the mean (S.E. mean) mean.LCL lower confidence level (LCL) of the mean PerformanceAnalytics-package 27

mean.UCL upper confidence level (UCL) of the mean quantile for calculating various quantiles of the distribution min minimum return max maximum return range range of returns length(R) number of observations sum(is.na(R)) number of NA’s

Modern Portfolio Theory (MPT) Modern Portfolio Theory 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 fron- tier will either rise or lower in price until they are on the efficient frontier of the market portfolio. The CAPM.RiskPremium 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. CAPM.alpha is the degree to which the assets returns are not due to the return that could be captured from the market. Conversely, CAPM.beta 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 CAPM.CML relates the excess expected return on an efficient market portfolio to its risk (represented in CAPM by sd ). The slope of the CML, CAPM.CML.slope, is the Sharpe Ratio for the market portfolio. The Security Market Line is constructed by calculating the line of CAPM.RiskPremium over CAPM.beta. For the bench- mark 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 CAPM.SML.slope. 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. 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 bench- mark’s annualized return. A closely related measure is the TrackingError, which measures the unexplained 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, properly applied, will maximize log-utility of returns and avoid risk of ruin. Utilizing the Kelly Criterion to determine leverage or investment size on a strategy is guaranteed to avoid risk of ruin and eventually (over a long enough time horizon) create wealth, but it may be incredibly volatile, with a N% chance of being down N% at some point in time. Even when an investor or analyst does not intend to utilize the Kelly criterion as part of the investment sizing strategy, it can be used as a stack- ranking method like InformationRatio to describe the “edge” an investment would have over a random strategy or distribution. InformationRatio, KellyRatio, SharpeRatio, SortinoRatio, UpsidePotentialRatio, Spearman Rank Correlation provided by rcorr and other methods discussed here are all methods of rank-ordering relative performance. Alexander and Dimitriu(2004) in “The Art of Investing in 28 PerformanceAnalytics-package

Hedge Funds” show that relative rankings 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 predicting 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 “buckets” of target instruments will have significant overlap. This observation specifically supports the point made early in this document regarding “accretion of the evidence” for a positive or negative investment decision. It is often valuable when evaluating an investment to know whether the instrument that you are ex- amining follows a normal distribution. One of the first methods to determine how close the asset is to a normal or log-normal distribution is to visually look at your data. Both chart.QQPlot and chart.Histogram will quickly give you a feel for whether or not you are looking at a normally 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 concen- tration 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. If you find yourself needing to analyze the distribution of complex or non-smooth asset distributions, the nortest package has several advanced statistical tests for analyzing the normality of a distribution. One question that an investor or researcher is often required to answer revolves around how to di- versify a portfolio. In a mean-variance world, an asset is a diversifier if it lowers the variance (and hopefully also raises the mean return) of the portfolio. In a world with more nuanced risk metrics, you may also test the target portfolio to see if it has lower measures of risk than the current portfolio. If you want to do more analysis, we have provided functions to calculate the higher moments and co-moments of the distribution. We have already discussed skewness and kurtosis provided by package fBasics. Increasing skewness and decreasing kurtosis of the target portfolio prob- ably marks a good diversifier. You can also work on minimizing the co-moments and systematic co-moments of the distribution to improve the resilience of the portfolio to multiple different mar- ket conditions in much the way that minimizing covariance and systematic beta will mark a well diversified portfolio in a mean-variance framework. See CoSkewness and CoKurtosis for the co-moments and SystematicSkewness and SystematicKurtosis for the systematic standardized co-moments. Other diversification potential in a portfolio is not strictly econometric, and follow the classic asset delineations of asset type, size, industry, growth/value, currency, or geographic region, all of which are well-covered elsewhere. We have covered multiple methods of performance analysis in this summary section, but it is also important to note that we have not covered performance attribution. We have not examined tools for determining the sources and causes for the returns, or the underlying causes for the risks of an instrument (more on Risk Measurement and prediction below). There is a significant amount of academic literature on identifying these sources of risk or returns. Much of it falls into the field of “factor analysis” where “risk factors” are used to retrospectively 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 PerformanceAnalytics-package 29

some wrapping of this functionality focused on finance, but the capabilities already available from the base functions are quite powerful.

Summary Tabular Data Summary statistics are then the necessary aggregation and reduction of these (potentially thou- sands) of periodic return numbers. Usually these statistics are most palatable when organized into a table of related statistics, assembled for a particular purpose. A common offering of past re- turns organized by month and cumulated by calendar year is usually presented as a table, such as in table.Returns. Adding benchmarks or peers alongside the annualized data is helpful for comparing returns in calendar years. When we started this project, we debated whether such tables would be broadly useful or not. No reader is likely to think that we captured the precise statistics to help their decision. We merely offer these as a starting point for creating your own. Add, subtract, do whatever seems useful to you. If you think that your work may be useful to others, please consider sharing it so that we may include it in a future version of this library. Other tables for comparison of related groupings of statistics discussed elsewhere in this summary:

table.MonthlyReturns provides a statistical summary of the monthly returns themselves table.AnnualizedReturns calculates aggregate returns and risk (usually used in graphics, see below) table.CAPM a collection of statistics offered by practitioners of Modern Portfolio Theory table.HigherMoments metrics for evaluating diversification potential by comparing higher moments table.DownsideRisk statistics for those wanting to compare the extent of observed losses table.Drawdowns data on the length and depth of the worst drawdowns table.Correlation a table arranged for comparing correlations table.RollingPeriods calculates statistics over varying periods of time

Charts and Graphs Graphs and charts can also help to organize the information visually. Our goal in creating these charts was to simplify the process of creating well-formatted charts that are used often in portfolio analysis, and to create print-quality graphics that may be used in documents for consumption by non-analysts or researchers. R’s graphics capabilities are substantial, but the simplicity of the out- put of R default graphics functions such as plot does not always compare well against graphics delivered with commercial asset or portfolio analysis from places such as MorningStar or PerTrac. The cumulative returns or wealth index is usually the first thing displayed, even though neither conveys much information. See chart.CumReturns. Individual period returns may be help- ful for identifying problematic periods, such as in chart.Bar. Risk measures can be helpful when overlaid on the period returns, to display the bounds at which losses may be expected. See chart.BarVaR and the following section on Risk Analysis. More information can be conveyed when such charts are displayed together, as in charts.PerformanceSummary, which com- bines the performance data with detail on downside risk (see chart.Drawdown). Two-dimensional charts can also be useful while remaining easy to understand. chart.Scatter is a utility scatter chart with some additional attributes that are used in chart.RiskReturnScatter. Overlaying Sharpe ratio lines or boxplots helps to add information about relative performance along those dimensions. The relative performance through time of two assets can be plotted with chart.RelativePerformance. This plot displays the ratio of the cumulative performance at each point in time and makes periods of under- or out-performance easy to see. The value of the 30 PerformanceAnalytics-package

chart is less important than the slope of the line. If the slope is positive, the first asset is outperform- ing the second, and vice verse. Affectionately known as the Canto chart, it was used effectively in Canto (2006). For distributional analysis, a few graphics may be useful. chart.Boxplot is an example of a graphic that is difficult to create in Excel and is under-utilized as a result. A boxplot of re- turns is, however, a very useful way to instantly observe the shape of large collections of asset returns in a manner that makes them easy to compare to one another. chart.Histogram and chart.QQPlot are two charts from the packages with only small modifications. Rolling performance is typically used as a way to assess stability of a return stream. Although per- haps it doesn’t get much credence in the financial literature as it derives from work in digital signal processing, many practitioners find it a useful way to examine and segment performance and risk periods. See chart.RollingPerformance, which is a way to display different metrics over rolling time periods. chart.RollingMean is a specific example of a rolling mean and one stan- dard deviation bands. A group of related metrics is offered in charts.RollingPerformance. These charts use utility functions such as rollingFunction and rollingStat. chart.RollingCorrelation shows how correlations change over rolling periods. chart.RollingRegression displays the coefficients of a linear model fitted over rolling periods. A group of charts in charts.RollingRegression displays alpha, beta, and R-squared estimates in three aligned charts in a single device. A number of charts or groups of charts that remain unfinished or were experimental and may be modified or removed in the future. chart.RegressionDiagnostics, chart.Correlation, and chart.Correlation.color are examples. The latter two are slight modifications of code from the package MASS and the R base. See their documentation for more information. We have been greatly inspired by other peoples’ work, some of which is on display at http: //addictedtor.free.fr/. Particular inspiration came from and John Bollinger for their work at http://addictedtor.free.fr/graphiques/RGraphGallery. php?graph=65.

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 is also sometimes called 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 additional Counterparty Risks in manual or over the counter markets, and in many 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). 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 sd.annualized, or the equivalent function sd.multiperiod for scaling to an arbitrary number of periods. Many assets, including hedge funds, commodities, options, and PerformanceAnalytics-package 31

even most common stocks over a sufficiently long period, do not follow a normal distribution. For such common but non-normally distributed assets, a more sophisticated approach than standard deviation/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) http:// papers.ssrn.com/sol3/papers.cfm?abstract_id=910640. This measure is also called SemiDeviation. The more general case of downside deviation is implemented in the function 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 utilizing solve.QP or portfolio.optim or MarkowitzPortfolio. Use of semivariance or many other risk measures will not necessarily create a smooth ellipse, causing significant additional diffi- culties 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 chart.Drawdown. 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 compar- ing multiple assets using Sharpe, you should use SharpeRatio.annualized. It is important to note that William Sharpe now recommends InformationRatio preferentially to the original Sharpe Ratio. The SortinoRatio utilizes 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 utilize upside returns for the numerator and DownsideDeviation as the denominator in UpsidePotentialRatio. Favre and Galeano(2002) propose utilizing the ratio of expected excess return over the Cornish-Fisher modifiedVaR to produce SharpeRatio.modified. TreynorRatio is also similar to the Sharpe Ratio, except it uses CAPM.beta in place of the volatility measure to produce the ratio of the investment’s excess return over the beta. One of the newest statistical methods developed for analyzing the risk of financial instruments is Omega. Omega analytically constructs a cumulative distribution function, in a manner similar to chart.QQPlot, 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. Omega is still a very new method, and the academic literature is still exploring the best manner to utilize 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, how many observations are 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 32 PerformanceAnalytics-package

highly correlated and shares other characteristics can be quite informative. Factor analysis may be utilized 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 long distribution for testing. If you use a method such as Monte Carlo simulation or the bootstrap, it is often valuable to use chart.Boxplot 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.

Value at Risk - VaR

Traditional mean-VaR: In the early 90’s, academic literature started referring to “value at risk”, typically written as VaR. Take care to capitalize VaR in the commonly accepted manner, to avoid confusion with var (variance) and VAR (vector auto-regression). With a sufficiently large data set, you may choose to utilize a non-parametric VaR estimation method using the historical dis- tribution and the probability quantile of the distribution calculated using qnorm. The negative return at the correct quantile (usually 95% or 99%), is the non-parametric VaR estimate. J.P. Mor- gan’s RiskMetrics parametric mean-VaR was published in 1994 and this methodology for esti- mating parametric mean-VaR has become what people are generally referring to as “VaR” and what we have implemented as VaR.traditional. See Return to RiskMetrics: Evolution of a Standardhttp://www.riskmetrics.com/r2rovv.html, fPortfolio has also imple- mented traditional mean-VaR as the VaR function. Parametric traditional VaR does a better job of accounting for the tails of the distribution by more precisely estimating the tails below the risk quantile. It is still insufficient if the assets have a distribution that varies widely from normality. The VaR contains methods for simulating and estimating lognormal VaR.norm and generalized Pareto VaR.gpd distributions to overcome some of the problems with nonparametric or parametric mean-VaR calculations on a limited sample size. There is also a VaR.backtest function to apply simulation methods to create a more robust estimate of the potential distribution of losses. The VaR package also provides plots for its functions. Conditional VaR and Beyond VaR: The fPortfolio package has implemented Conditional Value at Risk, also called Expected Shortfall (not to be confused with shortfall probability, which is much less useful), in functions CVaR and CVaRplus. Expected Shortfall attempts to measure the mag- nitude of the average loss exceeding the traditional mean-VaR. Expected Shortfall has proven to be a reasonable risk predictor for many asset classes. See Uryasev(2000) and Sherer and Mar- tin(2005) for more information on Conditional Value at Risk. A similar measure called Beyond VaR implemented here as VaR.Beyond also attempts to estimate average loss beyond traditional mean-VaR. Adding VaR and Beyond VaR will produce a measure very similar to Expected Shortfall CVaRplus. 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. Both CVaR and BeyondVaR have been shown to perform significantly better than mean-VaR with respect to non-normal distributions, especially when estimated using the bootstrap or Monte Carlo. Modified Cornish-Fisher VaR: The limitations of traditional mean-VaR are all related to the use of a symmetrical distribution function. Use of simulations, resampling, or Pareto distributions all help in making a more accurate prediction, but they are still flawed for assets with significantly non-normal (skewed or kurtotic) distributions. Huisman(1999) and Favre and Galleano(2002) pro- pose to overcome this extensively documented failing of traditional VaR by directly incorporating PerformanceAnalytics-package 33

the higher moments of the return distribution into the VaR calculation. This new VaR measure in- corporates skewness and kurtosis via an analytical estimation using a Cornish-Fisher (special case of a Taylor) expansion. The resulting measure is referred to variously as “Cornish-Fisher VaR” or “Modified VaR”. We provide this measure as function VaR.CornishFisher with equivalent alias modifiedVaR, Modified VaR produces the same results as traditional mean-VaR when the return distribution is normal, so it may be used as a direct replacement. Many papers in the fi- nance literature have reached the conclusion that Modified VaR is a superior measure, and may be substituted in any case where mean-VaR would previously have been utilized. 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.Marginal function calculates Marginal VaR for all instruments in the portfolio. Marginal VaR as provided here may use traditional mean-VaR or Modified VaR for the calculation. Per Artzner,et.al.(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. Sherer and Martin(2005) p. 180 report that CVaR may be a subadditive measure under many circumstances, but present only a special rather than the general case. Clearly, a general subbadditive risk measure for downside risk is required. Incremental or Component VaR attempt to provide just such a measure. In Incremental or Component VaR, the Component VaR value for each element of the portfolio will sum to the total VaR of the portfolio. Several EDHEC papers suggest utilizing Modified VaR instead of mean-VaR in the Incremental and Component VaR calculation. We have not yet succeeded in implementing an Incremental and Component VaR calculation that utilizes Modified Cornish-Fisher VaR. We hope to add it to a future version of this library. 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, this author will 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”.

Wrapper and Utility Functions

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. In general, the use of the data-coercion function has been hidden inside the business functions provided. checkData may also save you time and trouble in your own code and functions outside of the functionality provided by the PerformanceAnalytics library. When you are analyzing relative or absolute performance of investments, you need to analyze returns, but much data is available only as prices. We have provided the simple wrapper func- tion CalculateReturns to address this by taking a stream of prices and calculating sim- ple or compounded returns from the price vector. The excellent tseries library includes the function get.hist.quote for retrieving market data from online sources. Many of the func- tions in PerformanceAnalytics require either a benchmark or a risk free rate, and many practi- tioners will not have access to a formal database of historical returns. To facilitate the examples and provide an example of how to retrieve and coerce the data, we have provided functions for 34 PerformanceAnalytics-package

S&P 500 returns in the download.SP500PriceReturns and the 13-day US Treasury Bill in download.RiskFree. We also provide wrappers for cumulative maxima of the returns in a multicolumn series in cummax.column and for the cumulative product (compound return) in cumprod.column. 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 apply.fromstart and apply.rolling to make handling of “from inception” and “rolling window” calculations easier.

Further Work

Optimization Performance Attribution Factor Analysis Hedge Selection and Analysis Shock/Scenario Analysis We have attempted to standardize function parameters and variable names, but more work exists to be done here. There are functions included in this package that would benefit from more complex examples. There is also an opportunity to extend several of the co-moments and risk measures to use multivari- ate estimates of the higher moments, which should produce more robust estimates of the moments of a portfolio of multiple diverse assets. Any comments, suggestions, or code patches to these ends are invited. If you’ve implemented anything in the list above, 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 permission of the EDHEC Risk and Asset Management Research Center. http://www.edhec-risk.com/indexes/pure_style Prototypes of the drawdowns functionality were provided by Sankalp Upadhyay, and modified with permission. Thanks to Joe Wayne Byers and Dirk Eddelbuettel for comments on early versions of these func- tions. Thanks to the R-SIG-Finance community without whom this library would not be possible.

Author(s)

Brian G. Peterson Peter Carl

Maintainer: Brian G. Peterson [email protected] Return.annualized 35

References

Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. Canto, Victor. Understanding Asset Allocation. FT Prentice Hall. 2006. Lhabitant, F. Hedge Funds: Quantitative Insights. Wiley. 2004. Litterman, R., Gumerlock R., et. al. The Practice of Risk Management: Implementing Processes for Managing Firm-Wide Market Risk. Euromoney. 1998. Murrel, Paul. R Graphics. Chapman and Hall. 2006. Ruppert, David. Statistics and Finance, an Introduction. Springer. 2004. Scherer, B. and Martin, D. Modern Portfolio Optimization. Springer. 2005. Tsay, R. Analysis of Financial Time Series. Wiley. 2001. Zivot, E. and Wang, Z. Modeling Financial Time Series with S-Plus: second edition. Springer. 2006.

See Also

CRAN task view on Empirical Finance http://cran.r-project.org/src/contrib/Views/Econometrics.html Grant Farnsworth’s Econometrics in R http://cran.r-project.org/doc/contrib/Farnsworth-EconometricsInR.pdf Collection of R charts and graphs http://addictedtor.free.fr/graphiques/

Return.annualized calculate an annualized return for comparing instruments with differ- ent length history

Description

An average annualized return is convenient for comparing returns.

Usage

Return.annualized(Ra, scale = 12, geometric = TRUE)

Arguments

Ra a 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 generate geometric (TRUE) or simple (FALSE) returns, default TRUE 36 Return.cumulative

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 n scale prod(1 + Ra) n − 1 = prod(1 + Ra) − 1

where scale is the number of periods in a year, and n is the total number of periods for which you have observations. @todo: add ability to calculate simple annualized returns to current geometric-only calculation

Value annualized return

Note

Author(s) Peter Carl

References Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 6

See Also Return.cumulative,

Examples data(edhec) Return.annualized(edhec[,13])

Return.cumulative calculate a compounded (geometric) cumulative return

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 Return.cumulative(R, geometric = TRUE) Return.excess 37

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns geometric generate geometric (TRUE) or simple (FALSE) returns, default TRUE

Details product of all the individual period returns

(1 + r1)(1 + r2)(1 + r3) ... (1 + rn) − 1 = prod(1 + R) − 1

Value cumulative simple or geometric return

Author(s) Peter Carl

References Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 6

See Also Return.annualized

Examples data(edhec) head(edhec[,13,drop=FALSE]) Return.cumulative(edhec[,13]) Return.cumulative(edhec[,13], geometric = FALSE)

Return.excess 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. 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.

Usage Return.excess(R, rf) 38 Return.excess

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns rf risk free rate, in same period as your returns, or as a sinlge digit average

Details 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.

Value mean excess return

Author(s) Peter Carl

References Bacon, Carl. Practical Portfolio Performance Measurement and Attribution. Wiley. 2004. p. 47-52

Examples data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) end = rownames(edhec[edhec.length,])

rf.zoo = download.RiskFree(start = start, end = end)

Return.excess(edhec[,"Funds.of.Funds"],rf.zoo) Return.excess(edhec[,"Long.Short.Equity"],rf.zoo)

sp.zoo = download.SP500PriceReturns(start = start, end = end) Return.excess(edhec[,"Funds.of.Funds"],sp.zoo) Return.excess(edhec[,"Long.Short.Equity"],sp.zoo) SemiDeviation 39

SemiDeviation deviation below the mean of the return distribution

Description

Semideviation is the portion of the return stream below the mean return.

Usage SemiDeviation(Ra) SemiVariance(Ra)

Arguments

Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns

Details

SemiDeviation or SemiVariance is a popular alternative downside risk measure that may be used in place of standard deviation or variance. This function is 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 rather than from variance.

Value

vector of returns below the mean return

Note

Author(s)

Peter Carl

References http://en.wikipedia.org/wiki/Semivariance

See Also DownsideDeviation 40 SharpeRatio

Examples data(edhec) head(edhec[,7,drop=FALSE]) sd(edhec[,7]) SemiDeviation(edhec[,7])

SharpeRatio Sharpe Ratio

Description The Sharpe Ratio is a risk-adjusted measure of return that uses standard deviation to represent risk.

Usage SharpeRatio(Ra, rf = 0)

Arguments Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns rf risk free rate, in same period as your returns

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.

(R − R ) a√ f σ

William Sharpe now recommends InformationRatio preferentially to the original Sharpe Ra- tio.

Value Sharpe Ratio

Note

Author(s) Peter Carl

References Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58. SharpeRatio.annualized 41

See Also SharpeRatio.annualized InformationRatio TrackingError ActivePremium SortinoRatio

Examples data(edhec) head(edhec[, 6, drop = FALSE]) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) rf = download.RiskFree(start=start, end=end)

SharpeRatio(edhec[, 6, drop = FALSE]) SharpeRatio(edhec[, 6, drop = FALSE], rf = .04/12) SharpeRatio(edhec[, 6, drop = FALSE], rf = rf)

SharpeRatio.annualized calculate annualized Sharpe Ratio

Description The Sharpe Ratio is a risk-adjusted measure of return that uses standard deviation to represent risk.

Usage SharpeRatio.annualized(Ra, rf = 0, scale = 12)

Arguments Ra a 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)

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. 42 SharpeRatio.annualized

pn scale prod(1 + Ra) − 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.

Value annualized Sharpe Ratio

Note

Author(s) Peter Carl

References Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.

See Also SharpeRatio InformationRatio TrackingError ActivePremium SortinoRatio

Examples data(edhec) head(edhec[, 6, drop = FALSE]) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) rf = download.RiskFree(start=start, end=end)

SharpeRatio.annualized(edhec[, 6, drop = FALSE]) SharpeRatio.annualized(edhec[, 6, drop = FALSE], rf = .04/12) SharpeRatio.annualized(edhec[, 6, drop = FALSE], rf = rf) SharpeRatio.modified 43

SharpeRatio.modified calculate a modified Sharpe Ratio of Return/modVaR

Description The Sharpe ratio is simply the return per unit of risk (represented by variability). The higher the Sharpe ratio, the better the combined performance of "risk" and return. The Sharpe Ratio is a risk-adjusted measure of return that uses standard deviation to represent risk. A number of papers now recommend using a "modified Sharpe" ratio using a Modified Cornish- Fisher VaR as the measure of Risk.

Usage SharpeRatio.modified(Ra, rf = 0, p = 0.95, scale = 1)

Arguments Ra a 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=.99 scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly scale = 4)

Details

(R − R ) modSharpe = a f modV aRRa,p

or for an annualized measure:

pn prod(1 + (R − R ))scale − 1 modSharpe = √ a f scale · modV aRRa,p

Value This function returns a modified Sharpe ratio for the same periodicity of the data being input (e.g., monthly data -> monthly SR)

Note

Author(s) Brian G. Peterson 44 SortinoRatio

References 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 VaR.CornishFisher SharpeRatio

Examples data(edhec) head(edhec[, 6, drop = FALSE]) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) rf = download.RiskFree(start=start, end=end)

SharpeRatio.modified(edhec[, 6, drop = FALSE]) SharpeRatio.modified(edhec[, 6, drop = FALSE], rf = .04/12) SharpeRatio.modified(edhec[, 6, drop = FALSE], rf = rf)

SortinoRatio calculate Sortino Ratio of performance over downside risk

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(Ra, MAR = 0)

Arguments Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns MAR Minimum Acceptable Return, in the same periodicity as your returns

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 SortinoRatio 45

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.

(R − MAR) SortinoRatio = a δMAR

where δMAR is the DownsideDeviation.

Value

Sortino ratio

Note

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.

See Also

SharpeRatio DownsideDeviation SemiVariance SemiDeviation InformationRatio

Examples

data(edhec) head(edhec[,6, drop = FALSE]) SortinoRatio(edhec[, 6]) 46 sd.multiperiod

sd.multiperiod calculate a multiperiod or annualized Standard Deviation

Description

Standard Deviation of a set of observations Ra is given by: σ = 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 vari- ance (or risk) was greater than 100%. It follows then that the total variance needs to demonstrate a decreasing period-to-period increase as the number of periods increases. Put another way, the increase in incremental variance 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.

√ σ · pperiods

Note that any multiperiod or annualized number should be viewed with suspicion if the number of observations is small.

Usage sd.multiperiod(x, na.rm=FALSE, periods = 12, ...) sd.annualized(x, na.rm=FALSE, periods = 12, ...) StdDev.annualized(Ra, na.rm=FALSE, scale = 12, ...) StdDev(Ra) std(Ra)

Arguments x, Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns periods,scale number of periods in a year (daily scale = 252, monthly scale = 12, quarterly scale = 4) na.rm TRUE/FALSE Remove NA’s from the returns? ... any other passthru parameters

Value standard deviation value, scaled for multiple periods TrackingError 47

Author(s) Brian G. Peterson

References

See Also sd http://wikipedia.org/wiki/inverse-square_law

Examples data(edhec) head(edhec[,6,drop=FALSE]) sd.annualized(edhec[,6]) # now for three periods: sd.multiperiod(edhec[,6],scale=3)

TrackingError Calculate Tracking Error of returns against a benchmark

Description A measure of the unexplained portion of performance relative to a benchmark.

Usage TrackingError(Ra, Rb, scale = 12)

Arguments Ra a 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 2 X (Ra − Rb) T rackingError = √ len(Ra) scale 48 TreynorRatio

Value Tracking Error (number)

Note

Author(s) Peter Carl

References Sharpe, W.F. The Sharpe Ratio,Journal of Portfolio Management,Fall 1994, 49-58.

See Also InformationRatio TrackingError

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y")

TrackingError(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE])

TreynorRatio calculate Treynor Ratio of excess return over CAPM beta

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). TreynorRatio 49

Usage TreynorRatio(Ra, Rb, rf = 0, scale = 12, ...)

Arguments Ra a 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 Equation: (Ra − Rf ) βa,b

Value Treynor ratio

Author(s) Peter Carl

References

See Also SharpeRatio SortinoRatio CAPM.beta

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) rf.zoo = download.RiskFree(start = start, end = end) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) 50 UpDownRatios

time(rf.zoo) = as.yearmon(time(rf.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y") time(rf.zoo) = as.Date(time(rf.zoo),format="%b %Y")

TreynorRatio(data.zoo[,1], data.zoo[,2], rf=rf.zoo)

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(R, Rb, method = "capture", side = "up", ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns Rb return vector of the benchmark asset method "capture", "number", or "percentage" to indicate which measure to return side "up" or "down" market statistics ... any other passthru parameters

Details This is a function designed to calculate several related metrics: Up (Down) Capture Ratio: this is a measure of an investment’s compound return when the bench- mark was up (down) divided by the benchmark’s compound return when the benchmark was up (down). The greater (lower) the value, the better. Up (Down) Number Ratio: similarly, this is a measure of the number of periods that the investment was up (down) when the benchmark was up (down), divided by the number of periods that the Benchmark was up (down). Up (Down) Percentage Ratio: this is a measure of the number of periods that the investment outper- formed the benchmark when the benchmark was up (down), divided by the number of periods that the benchmark was up (down). Unlike the prior two metrics, in both cases a higher value is better.

Value A data.table of n-period trailing calculations for each column in x.

Author(s) Peter Carl UpsidePotentialRatio 51

References

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y")

# Up Capture: UpDownRatios(data.zoo[,1, drop=FALSE], data.zoo[,2, drop=FALSE]) # Down Capture: UpDownRatios(data.zoo[,1, drop=FALSE], data.zoo[,2, drop=FALSE], side="down")

UpsidePotentialRatio calculate Upside Potential Ratio of upside performance over downside risk

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(Ra, MAR = 0)

UPR(Ra, MAR = 0)

Arguments Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns MAR Minimum Acceptable Return, in the same periodicity as your returns 52 UpsidePotentialRatio

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.

Pn (R − MAR) UPR = t=1 t δMAR

where δMAR is the DownsideDeviation. The numerator in UpsidePotentialRatio only uses returns that exceed the MAR, and the de- nominator (in DownsideDeviation) only uses returns that fall short of the MAR. 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.

Value

Upside potential ratio

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: //ssrn.com/abstract=277352

See Also SharpeRatio SortinoRatio DownsideDeviation SemiVariance SemiDeviation InformationRatio VaR.Beyond 53

Examples data(edhec) UpsidePotentialRatio(edhec[, 6], MAR=.05/12) #5 percent/yr MAR

VaR.Beyond calculate BVaR or loss Beyond traditional mean-VaR

Description Beyond VaR purports to estimate average loss beyond VaR. Please note that your milage will vary; expect that values obtained from the normal distribution differs radically from the real situation. BeyondVaR is described in theoretical detail in the paper: Gaussel, N., Legras, J., Longin, F., and Rabemananjara, R. "Beyond the VaR Horizon" 2001, Quants Review No. 37

Usage VaR.Beyond(R, p=.95, modified=FALSE, add=FALSE, periods = 1)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns p confidence level for calculation, default p=.99 modified TRUE/FALSE default FALSE, use Cornish Fisher Expansion to take higher mo- ments into account add TRUE/FALSE default FALSE, add VaR to BeyondVaR value for total predicted loss, like CVaRplus periods number of periods to calculate predicted loss beyond the VaR for, default 1

Details We believe that the extension of Cornish-Fisher VaR as an option in the Beyond VaR calculation is unique to this library.

Value estimated Value of single period loss Beyond traditional mean-VaR

Author(s) Peter Carl Brian G. Peterson

References Gaussel, N., Legras, J., Longin, F., and Rabemananjara, R. "Beyond the VaR Horizon" 2001, Quants Review No. 37 54 VaR.CornishFisher

See Also VaR.CornishFisher VaR.traditional CVaR CVaRplus

Examples data(edhec)

# first do normal Beyond VaR calc VaR.Beyond(edhec)

# now use modified Cornish-Fisher VaR calc to take non-normal distribution into account VaR.Beyond(edhec,modified=TRUE)

VaR.CornishFisher calculate various Value at Risk (VaR) measures

Description These functions calculate both traditional mean-VaR and modified Cornish-Fisher VaR

Usage VaR.CornishFisher(R, p = 0.99, modified = TRUE) modifiedVaR(R, p = 0.99) VaR.traditional(R, p = 0.99) VaR.mean(R, p = 0.99) VaR(R, p = 0.99)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns p confidence level for calculation, default p=.99 modified TRUE/FALSE default TRUE, use Cornish Fisher Expansion to take higher mo- ments into account

Details In the early 90’s, academic literature started referring to “value at risk”, typically written as VaR. Take care to capitalize VaR in the commonly accepted manner, to avoid confusion with var (vari- ance) and VAR (vector auto-regression). With a sufficiently large data set, you may choose to utilize a non-parametric VaR estimation method using the historical distribution and the probability quan- tile of the distribution calculated using quantile for an arbitrary historical distribution or qnorm for an idealized normal distribution. The negative return at the correct quantile (usually 95% or 99%), is the non-parametric historical VaR estimate. VaR.CornishFisher 55

In a set of returns for which sufficently long history exists, the per-period Value at risk is simply the correct quantile of the period losses µ with variance σ is denoted by:

V aR = µq.99

where q.99 is the 99% quantile of the distribution. fPortfolio has implemented historical mean-VaR as the VaR function. This method is also sometimes called “historical VaR”, as it is by definition ex post analysis of the return distribution. When you don’t have a sufficiently long set of returns to use non-parametric or historical VaR, or wish to more closely model an ideal distribution, it is common to us a parmetric estimate based on the distribution. J.P. Morgan’s RiskMetrics parametric mean-VaR was published in 1994 and this methodology for estimating parametric mean-VaR has become what most literature generally refers to as “VaR” and what we have implemented as VaR.traditional. See Return to RiskMetrics: Evolution of a Standardhttp://www.riskmetrics.com/r2rovv.html, Parametric mean-VaR does a better job of accounting for the tails of the distribution by more pre- cisely estimating shape of the distribution tails of the risk quantile. The most common estimate is a normally distributed R ∼ N(µ, σ2) return series. In this case, estimation of VaR requires the mean return R¯, the distribution of losses µ, and the variance of the returns σ. In the most common case, parametric VaR is thus calculated by

σ = variance(R)

√ V aR = R¯ − q.99 · σ

where q.99 is the 99% quantile of the distribution. Represented in R by qnorm(1-p) Other forms of parametric mean-VaR estimation utilize a different distribution for the distribu- tion of losses µ to better account for the possible fat-tailed nature of downside risk. The package VaR contains methods for simulating and estimating lognormal VaR.norm and generalized Pareto VaR.gpd distributions to overcome some of the problems with nonparametric or parametric mean- VaR calculations on a limited sample size or on potentially fat-tailed distributions. There is also a VaR.backtest function to apply simulation methods to create a more robust estimate of the po- tential distribution of losses. Less commonly a covariance matrix of multiple risk factors may be applied. The limitations of mean Value-at-Risk are well covered in the literature. The limitations of tradi- tional mean-VaR are all related to the use of a symetrical distribution function. Use of simulations, resampling, or Pareto distributions all help in making a more accurate prediction, but they are still flawed for assets with significantly non-normal (skewed or kurtotic) distributions. Favre and Galeano(2002) provide a modified VaR calculation that takes the higher moments of non-normal distributions (skewness, kurtosis) into account through the use of a Cornish Fisher expansion, and collapses to standard (traditional) mean-VaR if the return stream follows a standard distribution. This measure is now widely cited and used in the literature, and is usually referred to as “Modi- fied VaR” or “Modified Cornish-Fisher VaR”.They arrive at their modified VaR calculation in the following manner: 56 VaR.CornishFisher

zc = qp = qnorm(p)

S = skewness(R)

K = kurtosis(R)

(z2 − 1)S (z3 − 3z )K (2z3 − 5z )S2 z = z + c + c c + c c cf c 6 24 36

√ modV aR = R¯ − zcf σ

Cornish-Fisher VaR collapses to traditional mean-VaR when returns are normally distributed. As such, the VaR.mean and VaR.traditional functions are wrappers for the VaR.CornishFisher function. The Cornish-Fisher expansion also naturally encompasses much of the variability in re- turns that could be uncovered by more computationally intensive techniques such as resampling or Monte-Carlo simulation. Favre and Galeano also utilize modified VaR in a modified Sharpe Ratio as the return/risk measure for their portfolio optimization analysis, see SharpeRatio.modified for more information.

Value

VaR measure

Note

The prototype of the Cornish Fisher VaR function was completed by Diethelm Wuertz. All correc- tions to the calculation and error handling ar the fault of Brian Peterson.

Author(s)

Brian G. Peterson

References

Laurent Favre and Jose-Antonio Galeano. Mean-Modified Value-at-Risk Optimization with Hedge Funds. Journal of Alternative Investment, Fall 2002, v 5. Uryasev S, Rockafellar R. Optimization of Conditional VaR. University of Florida, Working paper, 1999. VaR.Marginal 57

See Also VaR.Beyond VaR.Marginal SharpeRatio.modified skewness kurtosis VaR VaR.gpd VaR.norm VaR.backtest CVaR

Examples data(edhec)

# first do normal VaR calc VaR.traditional(edhec, p=.95)

# now use modified Cornish Fisher calc to take non-normal distribution into account VaR.CornishFisher(edhec, p=.95)

# now use default p=.99 VaR.CornishFisher(edhec)

VaR.Marginal Calculate the Marginal VaR of each element of a portfolio

Description Marginal VaR is the difference between the VaR of the portfolio without the asset in question and the entire portfolio. This function calculates Marginal VaR for all instruments in the portfolio.

Usage VaR.Marginal(R, p = 0.99, modified = TRUE, weightingvector=NULL)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns or the components p confidence level for calculation, default p=.99 modified TRUE/FALSE whether to use Cornish-Fisher VaR weightingvector vector of weights for each element in the portfolio 58 apply.fromstart

Details

Value matrix of Marginal VaRs

Note Different papers call this different things. In the Denton and Jayaraman paper referenced here, this calculation is called Incremental VaR. We have chosen the more common usage of calling this difference in VaR’s in portfolios without the instrument and with the instrument as the “difference at the Margin”, thus the name Marginal VaR. This is incredibly confusing, and hasn’t been resolved in the literature at this time.

Author(s) Brian G. Peterson

References Denton M. and Jayaraman, J.D. Incremental, Marginal, and Component VaR. Sunguard. 2004.

See Also VaR.CornishFisher

Examples data(edhec) # construct a weighting vector for an equally weighted portfolio eqweight=t(rep(1/length(edhec), length(edhec))) VaR.Marginal(R=edhec,p=0.99,weightingvector=eqweight)

apply.fromstart calculate a function over an expanding window always starting from the beginning of the series

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 apply.fromstart(R, FUN = "mean" , gap = 1, ...) apply.rolling 59

Arguments R a 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 Return.annualized will) gap the number of data points from the beginning of the series required to “train” the calculation ... any other passthru parameters

Value A timeseries in a zoo object of the calculation results

Author(s) Peter Carl

See Also apply

Examples

apply.rolling calculate a function over a rolling window

Description Creates a results timeseries of a function applied over a rolling window. Wrapper function for rollapply to hide some of the complexity of managing single-column zoo objects.

Usage apply.rolling(R, width = 12, FUN = "mean", na.pad = TRUE, ...)

Arguments R a 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 Return.annualized will) width number of periods to apply rolling function window over na.pad 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 60 chart.Bar

Value A timeseries in a zoo object of the calculation results

Author(s) Peter Carl

See Also apply rollapply

Examples

chart.Bar wrapper for barchart of returns

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 chart.Bar(R, legend.loc = NULL, colorset = (1:12), ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns legend.loc 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

Details This is really a wrapper for chart.TimeSeries, so several other attributes can also be passed.

Value Creates a plot of time on the x-axis and vertical lines for each period to indicate value on the y-axis.

Note chart.BarVaR 61

Author(s) Peter Carl

References

See Also chart.TimeSeries plot

Examples data(edhec) chart.Bar(edhec[,"Funds.of.Funds"], main="Monthly Returns")

chart.BarVaR Periodic returns in a bar chart with risk metric overlay

Description Plots the periodic returns in a bar chart overlayed with a risk metric calculation.

Usage chart.BarVaR(R, width = 0, gap = 12, risk.line = TRUE, method = c("ModifiedVaR","VaR","StdDev"), reference.grid = TRUE, xaxis = TRUE, main = "Title", ylab="Value", xlab="Date", date.format = "%m/%y", xlim = NA, ylim = NA, lwd = 1, colorset =(1:12), p=.99, lty = "13", all = FALSE, ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns width periods specified for rolling-period calculations. Note that VaR 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 method one of StdDev, VaR, or ModifiedVaR, default ModifiedVaR p confidence level for VaR or ModifiedVaR calculation, default is .99 risk.line if risk.line is set to FALSE, then this function just draws the underlying bar chart reference.grid if true, draws a grid aligned with the points on the x and y axes xaxis if true, draws the x axis main set the chart title, same as in plot ylab set the y-axis label, same as in plot 62 chart.BarVaR

xlab set the x-axis label, same as in plot date.format 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 lwd set the line width, same as in plot lty set the line type, same as in plot all if TRUE, calculates risk lines for each column given in R. If FALSE, only cal- culates the risk line for the first column colorset color palette to use, set by default to rational choices ... any other passthru parameters

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.

Value 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.

Note

Author(s) Peter Carl

References

See Also chart.TimeSeries plot VaR VaR.CornishFisher

Examples data(edhec) chart.BarVaR(edhec[,"Funds.of.Funds",drop=FALSE], main="Monthly Returns") chart.BarVaR(edhec[,"Funds.of.Funds",drop=FALSE], main="Monthly Returns", method="VaR") chart.BarVaR(edhec[,"Funds.of.Funds",drop=FALSE], main="Monthly Returns", method="StdDev", n=36) chart.Boxplot 63

chart.Boxplot box whiskers plot wrapper, with sensible defaults

Description

A wrapper to create box and whiskers plot, but with some sensible defaults useful for comparing distributions.

Usage

chart.Boxplot(R, horizontal = TRUE, ...)

Arguments

R a vector, matrix, data frame, timeSeries or zoo object of asset returns horizontal TRUE/FALSE plot horizontal (TRUE) or vertical (FALSE) ... any other passthru parameters

Value

Creates a box plot of returns with some defaults.

Author(s)

Peter Carl

References

See Also

boxplot

Examples

data(edhec) chart.Boxplot(edhec) 64 chart.Correlation

chart.Correlation correlation matrix chart

Description Visualization of a Correlation Matrix. On top the (absolute) value of the correlation plus the result of the cor.test as stars. On botttom, the bivariate scatterplots, with a fitted line

Usage chart.Correlation(x, y, histogram = TRUE)

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 histogram TRUE/FALSE whether or not to display a histogram

Value correlation chart

Note based on plot at http://addictedtor.free.fr/graphiques/sources/source_137. R

Author(s) Peter Carl

References

See Also table.Correlation chart.Correlation.color

Examples chart.Correlation.color 65

chart.Correlation.color correlation matrix chart, in color

Description Another, simpler, visualization of a Correlation Matrix, probably better for larger sets of data.

Usage chart.Correlation.color(R, new = FALSE, nrgcols = 50, labels = TRUE, labcols = 1, title = "", ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns new Describe new here nrgcols number or regularly spaced columns labels TRUE/FALSE use labels or not labcols labels to use title title for the plot ... any other passthru parameters

Value correlation chart

Note based on chart by Sandrine Dudoit, [email protected], from "SMA" library

Author(s) Peter Carl

References

See Also table.Correlation chart.Correlation

Examples 66 chart.CumReturns

chart.CumReturns Cumulates and graphs a set of periodic returns

Description Chart that cumulates the periodic returns given and draws a line graph of the results as a "wealth index".

Usage chart.CumReturns(R, wealth.index = FALSE, legend.loc = NULL, colorset =(1:12), begin = c("first","axis"), ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns wealth.index if wealth.index is TRUE, shows the "value of $1", starting the cumulation of returns at 1 rather than zero legend.loc 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

Details Cumulates the return series and displays either as a wealth index or as cumulative returns.

Value A timeseries line chart of the cumulative return series.

Note

Author(s) Peter Carl

References chart.Drawdown 67

See Also chart.TimeSeries plot

Examples data(edhec) chart.CumReturns(edhec[,"Funds.of.Funds"],main="Cumulative Returns") chart.CumReturns(edhec[,"Funds.of.Funds"],wealth.index=TRUE, main="Value of \$1")

chart.Drawdown Time series chart of drawdowns through time

Description A time series chart demonstrating drawdowns from peak equity attained through time, calculated from periodic returns.

Usage chart.Drawdown(R, legend.loc = NULL, colorset = (1:12), ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns colorset color palette to use, set by default to rational choices legend.loc 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

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.

Value A chart with time on the x-axis and the value peak equity attained on the y-axis.

Note

Author(s) Peter Carl 68 chart.Histogram

References

See Also plot chart.TimeSeries findDrawdowns sortDrawdowns maxDrawdown table.Drawdowns table.DownsideRisk

Examples data(edhec) chart.Drawdown(edhec[,c(1,2)], main="Drawdown from Peak Equity Attained", legend.loc="bottomleft")

chart.Histogram histogram of returns

Description Create a histogram of returns, with optional curve fits for density and normal. This is wrapper function for hist, see the help for that function for additional arguments you may wish to pass in.

Usage chart.Histogram(R, breaks = "FD", main = NULL, xlab = "Returns", ylab = "Frequency", methods = c("add.density", "add.normal", "add.centered", "add.rug", "add.risk", "add.qqplot"), colorset = c("lightgray", "#00008F", "#005AFF", "#23FFDC", "#ECFF13", "#FF4A00", "#800000"), border.col = "white", box.col = "white", lwd = 2, xlim = NULL, darken = FALSE, ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns breaks how to calculate the breaks between the bars, 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. In the last three cases the number is a suggestion only. see hist for details, default "FD" methods 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 chart.Histogram 69

border.col color to use for the border box.col color to use for the box xlim set the x-axis limit, same as in plot lwd set the line width, same as in plot colorset color palette to use, set by default to rational choices darken if true, draws the chart elements in "darkgray" rather than "gray". Makes it easier to print for some printers. ... any other passthru parameters

Details The default for breaks is "FD". Other names for which algorithms are supplied are "Sturges" (see nclass.Sturges), "Scott", and "FD" / "Freedman-Diaconis" (with correspond- ing functions nclass.scott and nclass.FD). 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.

Value chart of histogram of returns

Note Code inspired by a chart on: http://zoonek2.free.fr/UNIX/48_R/03.html

Author(s) Peter Carl

References

See Also hist

Examples #first get some data data(edhec) #default chart is too busy chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE])

# version with more breaks and the standard close fit density distribution chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], breaks=40, methods = c("add.density", "add.rug") )

chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], methods = c( "add.centered") ) 70 chart.QQPlot

# version with just the histogram and normal distribution centered on 0 chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], methods = c( "add.centered") )

# version with histogram, normal, and close fit distribtuion chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], methods = c( "add.centered", "add.density") )

# add a rug to the previous plot for more granularity on precisely where the distribution fell chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], methods = c( "add.centered", "add.density", "add.rug") )

# now show a qqplot to give us another view on how normal the data are chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], methods = c( "add.centered", "add.density", "add.rug", "add.qqplot") )

# add risk measure(s) to show where those are in relation to observed returns chart.Histogram(edhec[,'Equity.Market.Neutral',drop=FALSE], methods = c("add.density", "add.centered", "add.rug", "add.risk") )

chart.QQPlot wrapper for qq.plot, with sensible defaults

Description A wrapper to create a QQPlot chart of relative returns through time

Usage chart.QQPlot(R, colorset = (1:12), symbolset = 1, xlab = NULL, ylab = NULL, main = NULL, ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns 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 xlab set the x-axis label, as in plot ylab set the y-axis label, as in plot main set the chart title, same as in plot ... any other passthru parameters

Value QQ Plot

Author(s) Peter Carl

References chart.RegressionDiagnostics 71

See Also qqplot

Examples

chart.RegressionDiagnostics regression diagnostics charts

Description

Usage chart.RegressionDiagnostics(R, Rb)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns Rb return vector of the benchmark asset

Details

Value chart of regression stats to help you validate the regression outputs

Author(s) Peter Carl

References

See Also charts.RollingRegression chart.RollingRegression chart.Histogram chart.QQPlot chart.Boxplot 72 chart.RelativePerformance

Examples

chart.RelativePerformance relative performance chart between multiple return series

Description A wrapper to create a chart of relative returns through time

Usage chart.RelativePerformance(Ra, Rb, main = "Relative Performance", xaxis = TRUE, colorset = (1:12), legend.loc = NULL, ylog = FALSE, ...)

Arguments Ra a 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 legend.loc 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 ... any other passthru parameters

Value chart of relative returns

Author(s) Peter Carl

References

See Also chart.RiskReturnScatter 73

Examples # First we get the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,])

edhec.zoo = zoo(edhec, order.by = rownames(edhec)) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Then align the dates as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y")

# Finally, plot it chart.RelativePerformance(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE], colorset=rich8equal, legend.loc="bottomright", lwd=2)

chart.RiskReturnScatter 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 chart.RiskReturnScatter(R, rf = 0, main = "Annualized Return and Risk", add.names = TRUE, xlab = "Annualized Risk", ylab = "Annualized Return", method = "calc", add.sharpe = c(1, 2, 3), add.boxplots = FALSE, colorset = 1, symbolset = 1, darken = FALSE, legend.loc = NULL, xlim = NULL, ylim = NULL, ...)

Arguments R a 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 add.names 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 Used to select the risk parameter to use in the chart.BarVaR. May be any of: modVaR - uses CF modified VaR VaR - uses traditional Value at Risk StdDev - monthly standard deviation of trailing 12 month returns 74 chart.RiskReturnScatter

add.sharpe 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., sharpe.ratio = NULL). add.boxplots 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 darken if true, draws the chart elements in "darkgray" rather than "gray". Makes it easier to print for some printers. legend.loc 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 ... any other passthru parameters

Details

Value scatter chart with Return on one axis and some Risk measure on the other axis

Note Code inspired by a chart on: http://zoonek2.free.fr/UNIX/48_R/03.html

Author(s) Peter Carl

References

See Also

Examples data(edhec) chart.RiskReturnScatter(edhec, rf = .04/12) chart.RiskReturnScatter(edhec, rf = .04/12, add.boxplots = TRUE) chart.RollingCorrelation 75

chart.RollingCorrelation chart rolling correlation fo multiple assets

Description A wrapper to create a chart of rolling correlation metrics in a line chart

Usage chart.RollingCorrelation(Ra, Rb, width = 12, xaxis = TRUE, legend.loc = NULL, colorset = (1:12), na.pad = FALSE, ...)

Arguments Ra a 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 legend.loc 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 na.pad 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

Details

Value chart rolling period correlations of one or more assets

Note

Author(s) Peter Carl

References 76 chart.RollingMean

See Also

Examples # First we get the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,])

edhec.zoo = zoo(edhec, order.by = rownames(edhec)) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Then align the dates as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y")

# Finally, plot it chart.RollingCorrelation(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE], colorset=rich8equal, legend.loc="bottomright", lwd=2, width=24)

chart.RollingMean chart the rolling mean return

Description A wrapper to create a rolling mean return chart with 95% confidence bands.

Usage chart.RollingMean(R, width = 12, xaxis = TRUE, ylim = NULL, na.pad = FALSE, ...)

Arguments R a 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 na.pad 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

Value A timeseries line charts of the rolling mean, with error bars chart.RollingPerformance 77

Author(s) Peter Carl

References

See Also

Examples data(edhec) chart.RollingMean(edhec[, 9, drop = FALSE])

chart.RollingPerformance 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 chart.RollingPerformance(R, width = 12, xaxis = TRUE, legend.loc = NULL, colorset = (1:12), FUN = "Return.annualized", na.pad = TRUE, type = "l", pch = NULL, lty = 1, bg = NULL, cex = 1, lwd = 1, xlim = NULL, ylim = NULL, log = "", main = paste(width,"-Month Rolling Performance", sep=""), sub = NULL, xlab = NULL, ylab = NULL, ann = par("ann"), axes = TRUE, frame.plot = axes, panel.first = NULL, panel.last = NULL, asp = NA, ylog = FALSE, event.lines = NULL, event.labels = NULL, period.areas = NULL, event.color = "darkgray", period.color = "lightgray", darken = FALSE , date.format = "%m/%y", ...)

Arguments R a 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 CAPM.beta won’t work, but Return.annualized will) na.pad 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. ylog TRUE/FALSE set the y-axis to logarithmic scale, similar to plot, default FALSE date.format re-format the dates for the xaxis; the default is "%m/%y" legend.loc places a legend into one of nine locations on the chart: bottomright, bottom, bottomleft, left, topleft, top, topright, right, or center. main set the chart title, same as in plot event.lines If not null, vertical lines will be drawn to indicate that an event happened during that time period. event.lines should be a list of dates (e.g., c("09/03","05/06")) formatted the same as date.format. This function matches the re-formatted row names (dates) with the events.list, so to get a match the formatting needs to be correct. 78 chart.RollingPerformance

event.labels if not null and event.lines is not null, this will apply a list of text labels (e.g., c("This Event", "That Event") to the vertical lines drawn event.color draws the event described in event.labels in the color specified period.areas these are shaded areas described by start and end dates in the same format as the date.format. This is provided as a list of pairs, e.g., list(c("10/26","11/27"), c("08/29","03/33")) See the examples below. period.color draws the shaded region described by period.areas in the color specified type set the chart type, same as in plot xaxis if true, draws the x axis ylab set the y-axis label, same as in plot xlab set the x-axis label, same as in plot xlim set the x-axis limit, same as in plot ylim set the y-axis limit, same as in plot pch symbols to use, see also plot lty set the line type, same as in plot lwd set the line width, same as in plot darken if true, draws the chart elements in "darkgray" rather than "gray". Makes it easier to print for some printers. colorset color palette to use, set by default to rational choices bg Describe cex Describe log Describe sub Describe ann Describe axes Describe frame.plot Describe panel.first Describe panel.last Describe asp Describe ... any other passthru parameters

Value A timeseries line chart of the calculated series

Author(s) Peter Carl

References chart.RollingRegression 79

See Also charts.RollingPerformance

Examples data(edhec) chart.RollingPerformance(edhec[, 1:3], width = 24) chart.RollingPerformance(edhec[, 1:3], width = 24, colorset = rich8equal, lwd = 2, legend.loc = "topleft")

chart.RollingRegression A wrapper to create charts of relative regression performance through time

Description A wrapper to create a chart of relative regression performance through time A group of charts in charts.RollingRegression displays alpha, beta, and R-squared esti- mates in three aligned charts in a single device.

Usage chart.RollingRegression(Ra, Rb, width = 12, rf = 0, attribute = c("Beta","Alpha","R-Squared"), main = paste("Rolling ", width, "-Month ", attribute, sep = ""), xaxis = TRUE, colorset = (1:12), legend.loc = NULL, na.pad = TRUE, ...) charts.RollingRegression(Ra, Rb, width = 12, rf = 0, darken = FALSE, main = NULL, ...)

Arguments Ra a 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 width number of periods to apply rolling function window over attribute one of "Beta","Alpha","R-Squared" for which attribute to show 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 darken TRUE/FALSE whether or not to darken the color palette for better printing on some printers legend.loc places a legend into one of nine locations on the chart: bottomright, bottom, bottomleft, left, topleft, top, topright, right, or center. na.pad 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 80 chart.RollingRegression

Details The atribute parameter is probably the most confusing. In mathematical terms, the different choices yeild 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

Value A timeseries line chart of the calculated series

Note Most inputs are the same as "plot" and are principally included so that some sensible defaults could be set.

Author(s) Peter Carl

References

See Also chart.RegressionDiagnostics

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) rf.zoo = download.RiskFree(start = start, end = end) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) time(rf.zoo) = as.yearmon(time(rf.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y") time(rf.zoo) = as.Date(time(rf.zoo),format="%b %Y")

chart.RollingRegression(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE], rf = rf.zoo) charts.RollingRegression(data.zoo[, 1, drop=FALSE], data.zoo[, 2, drop=FALSE], rf = rf.zoo) chart.Scatter 81

chart.Scatter wrapper to draw scatter plot with sensible defaults

Description Draws a scatter chart. This is another chart "primitive", since it only contains a set of sensible defaults. This function is intended to be used in a wrapper that is written for a particular purpose. This is just a handy way to standardize the formatting of multiple charts.

Usage chart.Scatter(x, y, reference.grid = TRUE, main = "Title", ylab = NULL, xlab = NULL, xlim = NA, ylim = NA, colorset = 1, symbolset = 1, darken = FALSE, legend.loc = NULL, ylog = FALSE, ...)

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 reference.grid 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 darken if true, draws the chart elements in "darkgray" rather than "gray". Makes it easier to print for some printers. legend.loc 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 ... any other passthru parameters

Value Draws a graph of type "scatter" with some sensible defaults.

Note Most inputs are the same as "plot" and are principally included so that some sensible defaults could be set. 82 chart.TimeSeries

Author(s) Peter Carl

References

See Also plot

Examples data(edhec) chart.Scatter(edhec[,1],edhec[,2])

chart.TimeSeries Creates a time series chart with some extensions.

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.

Usage chart.TimeSeries(R, reference.grid = TRUE, xaxis = TRUE, type = "l", lty = 1, lwd = 1, main = "Title", ylab = NULL, xlab = "Date", date.format = "%m/%y", xlim = NULL, ylim = NULL, event.lines = NULL, event.labels = NULL, period.areas = NULL, event.color = "darkgray", period.color = "lightgray", colorset = (1:12), pch = (1:12), darken = FALSE, legend.loc = NULL, ylog = FALSE, ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns reference.grid if true, draws a grid aligned with the points on the x and y axes xaxis if true, draws the x axis 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 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 date.format 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 chart.TimeSeries 83

event.lines If not null, vertical lines will be drawn to indicate that an event happened during that time period. event.lines should be a list of dates (e.g., c("09/03","05/06")) formatted the same as date.format. This function matches the re-formatted row names (dates) with the events.list, so to get a match the formatting needs to be correct. event.labels if not null and event.lines 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. period.areas these are shaded areas described by start and end dates in the same format as the date.format. This is provided as a list of pairs, e.g., list(c("10/26","11/27"), c("08/29","03/33")) See the examples below. event.color draws the event described in event.labels in the color specified period.color draws the shaded region described by period.areas in the color specified colorset color palette to use, set by default to rational choices pch symbols to use, see also plot darken if true, draws the chart elements in "darkgray" rather than "gray". Makes it easier to print for some printers. legend.loc 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 ... any other passthru parameters

Details This function is intended to be used in a wrapper that is written for a particular purpose.

Value Draws a timeseries plot of type "line" with some sensible defaults.

Note

Author(s) Peter Carl

References

See Also plot 84 charts.PerformanceSummary

Examples

# These are start and end dates, formatted the same way as the default axis labels cycles.dates = list( c("10/26","11/27"), c("08/29","03/33"), c("05/37","06/38"), c("02/45","10/45"), c("11/48","10/49"), c("07/53","05/54"), c("08/57","04/58"), c("04/60","02/61"), c("12/69","11/70"), c("11/73","03/75"), c("01/80","07/80"), c("07/81","11/82"), c("07/90","03/91"), c("03/01","11/01")) # Event lists - FOR BEST RESULTS, KEEP THESE DATES IN ORDER risk.dates = c( "10/87", "02/94", "07/97", "08/98", "10/98", "07/00", "09/01") risk.labels = c( "Black Monday", "Bond Crash", "Asian Crisis", "Russian Crisis", "LTCM", "Tech Bubble", "Sept 11") data(edhec) #use subset instead of accessing the column directly to preserve row and column names R=subset(edhec,select="Funds.of.Funds") Return.cumulative = cumprod.column(1+R) - 1 chart.TimeSeries(Return.cumulative) chart.TimeSeries(Return.cumulative, colorset = "darkblue", legend.loc = "bottomright", period.areas = cycles.dates, period.color = "lightblue", event.lines = risk.dates, event.labels = risk.labels, event.color = "red", lwd = 2)

charts.PerformanceSummary Create combined wealth index, period performance, and drawdown chart

Description For a set of returns, create a wealth index chart, bars for monthly performance, and underwater chart for drawdown. charts.PerformanceSummary 85

Usage charts.PerformanceSummary(R, rf = 0, main = NULL, method = c("ModifiedVaR","VaR","StdDev"), width = 0, event.labels = NULL, ylog = FALSE, wealth.index = FALSE, gap = 12, begin = c("first", "axis"), ...)

Arguments R a 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 method Used to select the risk parameter to use in the chart.BarVaR. May be any of: • modifiedVaR - uses Cornish-Fisher modified VaR, • VaR - uses traditional Value at Risk, • StdDev - monthly standard deviation of trailing 12 month returns. 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. passthru to chart.CumReturns event.labels TRUE/FALSE whether or not to display lines and labels for historical market shock events wealth.index if wealth.index is TRUE, shows the "value of $1", starting the cumulation of returns at 1 rather than zero width number of periods to apply rolling function window over gap numeric number of periods from start of series to use to train risk calculation ylog TRUE/FALSE set the y-axis to logarithmic scale, similar to plot, default FALSE ... any other passthru parameters

Details

Value A stack of three related timeseries charts.

Note Most inputs are the same as "plot" and are principally included so that some sensible defaults could be set.

Author(s) Peter Carl 86 charts.RollingPerformance

References

See Also chart.CumReturns chart.BarVaR chart.Drawdown

Examples data(edhec) charts.PerformanceSummary(edhec[,c("Funds.of.Funds","Long.Short.Equity")])

charts.RollingPerformance 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 charts.RollingPerformance(R, width = 12, rf = 0, main = NULL, trim = TRUE, event.labels = NULL, ...)

Arguments R a 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 trim TRUE/FALSE, whether to keep alignment caused by NA’s event.labels TRUE/FALSE whether or not to display lines and labels for historical market shock events ... any other passthru parameters

Value A stack of three related timeseries line charts

Author(s) Peter Carl checkData 87

References

See Also chart.RollingPerformance

Examples

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 emphseem more fun- gible. It allows the user to pass in a data object without being concerned that the function requires a matrix, data.frame, or timeSeries object. By using this, the function "knows" what data format it has to work with.

Usage checkData(x, method = c("zoo","matrix","vector"), na.rm = FALSE, quiet = TRUE, ...) checkDataMatrix(x, na.rm = TRUE, quiet = TRUE, ...) checkDataVector(x, na.rm = TRUE, quiet = TRUE, ...) checkDataZoo(x, na.rm = TRUE, quiet = TRUE, ...)

Arguments x a vector, matrix, data frame, timeSeries or zoo object to be checked and coerced na.rm TRUE/FALSE Remove NA’s from the data? quiet TRUE/FALSE if false, it will throw warnings when errors are noticed, default TRUE method type of coerced data object to return, one of c("zoo","matrix","vector"), default "zoo" ... any other passthru parameters

Details The checkData function grew out of three older functions: checkDataMatrix,checkDataVector, and checkDataZoo. All three of these functions are provided as wrappers to checkData for backwards compatibility and for clarity inside existing code. It is worth noting that the older check- Data* functions set na.rm=TRUE by default. The user is free to specify a value for this parameter to change the behavior. 88 cum.utils

Value checkDataMatrix returns a data.frame checkDataVector returns a vector checkDataZoo returns a zoo object checkData will make a reasonable assumption, or return the object requested by method

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)

cum.utils wrapper to calculate cumprod on all columns in a matrix

Description calculate cumulative values for the observation series given, including multicolumn extensions to cummax and cumprod

cummax.column cumulative maxima by column, useful for drawdowns cumprod.column cumulative product by column, useful for compound returns

A prior version of thesefunctions included specific NA handling. This was removed due to a conflict with the general cumulative functions in the R core. Please be aware that you may have issues with series of different lengths, and may need to explicitly handle NAs as a result. download.RiskFree 89

Usage cumprod.column(x) cummax.column(x)

Arguments x a vector, matrix, data frame, timeSeries or zoo object of observations

Value transformed matrix of cumprod’s or cummax’s

Author(s) Peter Carl

See Also cumprod cummax

download.RiskFree download 13-week US Treasury Bill Prices and calculate 13-week US Treasury Bill returns

Description This function downloads daily/monthly 13-week US Treasury Bill prices as the risk free asset using get.hist.quote for "îrx"ˆ and calculate returns using CalculateReturns as a good proxy for the Risk Free Rate.

Usage download.RiskFree(start = "1998-01-01", end = NULL, compression=c("m","d"))

Arguments start start date in YYYY-mm-dd format, default "1998-01-01" end end date in YYYY-mm-dd format compression "m" for monthly returns and "d" for daily returns, default monthly, as passthru to get.hist.quote

Details 90 download.SP500PriceReturns

Value matrix of simple or compound returns on the 13-week US Treasury Bill at the daily/monthly scale specified

Note

Author(s) Peter Carl

References

See Also CalculateReturns download.SP500PriceReturns get.hist.quote

Examples rf = download.RiskFree(start = "1997-12-01", end = "2007-01-01") class(rf) head(rf)

download.SP500PriceReturns download S & P Prices and calculate S & P returns

Description This function downloads daily/monthly S & P 500 prices using get.hist.quote for "gspc"ˆ and calculate S & P returns using CalculateReturns

Usage download.SP500PriceReturns(start = "1998-01-01", end = NULL, compression=c("m","d"), method=c("compound","simple"))

Arguments start start date in YYYY-mm-dd format, default "1998-01-01" end end date in YYYY-mm-dd format compression "m" for monthly returns and "d" for daily returns, default monthly, as passthru to get.hist.quote method "simple" or "compound" as a passthru to CalculateReturns, default com- pound edhec 91

Value matrix of simple or compound returns on the S & P 500 at the daily/monthly scale specified

Author(s) Peter Carl

See Also CalculateReturns download.RiskFree get.hist.quote

Examples sp500 = download.SP500PriceReturns(start = "1996-12-31", end = "2007-01-01") class(sp500) head(sp500)

edhec EDHEC-Risk Hedge Fund Style Indices

Description EDHEC composite hedge fund style index returns. 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 consultancies and an executive education arm. Clients of these derivative activities include many of the leading organisations throughout Europe.” see http://www.edhec-risk.com/about_us Data used in PerformanceAnalytics and related publications with the kind permission of the EDHEC Risk and Asset Management Research Center.

Usage edhec

Format CSV conformed into a data.frame with monthly observations 92 findDrawdowns

Source http://www.edhec-risk.com/indexes/pure_style

References

About EDHEC Alternative Indexes. December 16, 2003. EDHEC-Risk. http://www.edhec-risk.com/indexes/pure_style/about Vaissie Mathieu. A Detailed Analysis of the Construction Methods and Management Principles of Hedge Fund Indices. October 2003. EDHEC. http://www.edhec-risk.com/site_edhecrisk/public/indexes/EDHEC_Publications/ RISKReview1072705188065793513

Examples

data(edhec)

#preview the data head(edhec)

#summary period statistics summary(edhec)

#cumulative index returns tail(cumprod.column(1+edhec),1)

findDrawdowns Find the drawdowns and drawdown levels in a timeseries.

Description

findDrawdowns will find the starting period, the ending period, and the amount and length of the drawdown. Often used with sortDrawdowns to get the largest drawdowns. Drawdowns will calculate the drawdown levels as percentages, for use in chart.Drawdown.

Usage findDrawdowns(R) Drawdowns(R)

Arguments

R a vector, matrix, data frame, timeSeries or zoo object of asset returns managers 93

Value unordered list

return depth of drawdown from starting period to ending period length length in periods

Author(s) Peter Carl findDrawdowns modified with permission from function by Sankalp Upadhyay

References

See Also sortDrawdowns maxDrawdown sortDrawdowns table.Drawdowns table.DownsideRisk chart.Drawdown

Examples data(edhec) R=edhec[,"Funds.of.Funds"] findDrawdowns(R) sortDrawdowns(findDrawdowns(R))

managers Hypothetical Alternative Asset Manager Data and Fixed Income Benchmarks

Description A data frame 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. 94 maxDrawdown

Usage managers

Format CSV conformed into a data.frame with monthly observations

Source

References

Examples data(managers)

#preview the data head(managers)

#summary period statistics summary(managers)

#cumulative returns tail(cumprod.column(1+managers),1)

maxDrawdown caclulate the maximum drawdown from peak equity

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)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns

Value maximum drawdown mean.utils 95

Author(s) Peter Carl

References

See Also findDrawdowns sortDrawdowns table.Drawdowns table.DownsideRisk chart.Drawdown

Examples data(edhec) R=edhec[,"Funds.of.Funds"] maxDrawdown(R)

mean.utils calculate attributes relative to the mean of the observation series given, including geometric, stderr, LCL and UCL

Description

mean.geometric geometric mean mean.stderr standard error of the mean (S.E. mean) mean.LCL lower confidence level (LCL) of the mean mean.UCL upper confidence level (UCL) of the mean

Usage mean.geometric(x, ...) mean.stderr(x, ...) mean.UCL(x, ci = 0.95, ...) mean.LCL(x, ci = 0.95, ...)

Arguments x a vector, matrix, data frame, or time series to calculate the modified mean statis- tic over 96 moment.fourth

ci the confidence interval to use ... any other passthru parameters

Value numeric value for the mean function called

Author(s) Peter Carl

See Also sd mean

Examples data(edhec) mean.geometric(edhec[,"Funds.of.Funds"]) mean.stderr(edhec[,"Funds.of.Funds"]) mean.UCL(edhec[,"Funds.of.Funds"]) mean.LCL(edhec[,"Funds.of.Funds"])

moment.fourth calculate the fourth mathematical moment of the return function

Description The fourth mathematical moment of the return function. Favre and Renaldo use this as separate from kurtosis in developing a four-moment CAPM model.

Usage moment.fourth(R, na.rm = FALSE)

Arguments R return vector of the portfolio na.rm TRUE/FALSE Remove NA’s from the returns?

Value fourth mathematical moment of the distribution

Author(s) Brian G. Peterson moment.third 97

References Favre, L. and Renaldo, A. How to Price Hedge Funds: From Two- to Four-Moment CAPM. October 2003. UBS and Edhec Business School.

See Also moment.third

Examples

moment.third calculate the third mathematical moment of the return function

Description The third mathematical moment of the return function. Favre and Renaldo use this as separate from skewness in developing a four-moment CAPM model.

Usage moment.third(R, na.rm = FALSE)

Arguments R return vector of the portfolio na.rm TRUE/FALSE Remove NA’s from the returns?

Value third moment of the return series

Author(s) Brian G. Peterson

References Favre, L. and Renaldo, A., October 2003. How to Price Hedge Funds: From Two- to Four-Moment CAPM. UBS and Edhec Business School.

See Also moment.fourth

Examples 98 rollingCorrelation

rollingCorrelation rolling training period covariance/correlation

Description This is a wrapper for providing n-period trailing correlations for the data provided.

Usage rollingCorrelation(Ra, Rj, width, trim = TRUE, na.rm = FALSE, ...)

Arguments Ra a vector, matrix, data frame, timeSeries or zoo object of asset returns Rj a vector, matrix, data frame, timeSeries or zoo object of asset returns width the number of periods over which a function is to be calculated. Use the value zero (0) to roll the statistic from inception trim TRUE/FALSE, whether to keep alignment caused by NA’s na.rm TRUE/FALSE Remove NA’s from the returns? ... any other passthru parameters

Details Example: head(rollingCorrelation(manager.ts@Data[,1],edhec.ts@Data,n=12))

Convertible Arbitrage CTA Global Distressed 2003-11-28 0.2591101 0.2762218 0.7516556 2003-12-31 0.2162078 0.2477113 0.7452179 2004-01-30 0.3918575 0.3489062 0.7562063 2004-02-27 0.5331404 0.3905645 0.7088004 2004-03-31 0.5730389 0.3010877 0.5694478 2004-04-30 0.5146946 0.3762283 0.4374524

Value A data.table of n-period trailing correlations for each column in y.

Note Inspired by fMultivar rollFun written by Diethelm Wurtz. Assumes that Ra and Rj are sequenced exactly the same and are regular. Currently assumes that BOTH Ra and Rj are provided @todo: Allow either a matrix or data frame for ’Ra’ or give both ’Ra’ and ’Rj’ like cov rollingFunction 99

Author(s)

Peter Carl

References

See Also

cov

Examples

#head(rollingCorrelation(manager.ts@Data[,1],edhec.ts@Data,n=12))

rollingFunction wrapper to apply functions over a rolling period

Description

This is a wrapper for providing n-period trailing calculations for the data and functions provided.

Usage

rollingFunction(R, width, trim = TRUE, na.rm = TRUE, digits = 4, rf = 0, FUN = "mean", ...)

Arguments

R a vector, matrix, data frame, timeSeries or zoo object of asset returns width the number of periods over which a function is to be calculated. Use the value zero (0) to roll the statistic from inception trim TRUE/FALSE, whether to keep alignment caused by NA’s na.rm TRUE/FALSE Remove NA’s from the returns? digits number of digits to round results to rf risk free rate, in same period as your returns FUN function to apply rolling period over ... any other passthru parameters 100 rollingFunction

Details

Examples:

> rollingFunction(gg.ts[,1],n=3,FUN="Return.annualized") Manager 2002-02-28 0.0306 2002-03-31 0.0521 2002-04-30 0.0387 ...

> rollingFunction(gg.ts[,1],n=3,trim=FALSE,FUN="Return.annualized") Manager 2001-12-31 NA 2002-01-31 NA 2002-02-28 0.0306 2002-03-31 0.0521 2002-04-30 0.0387 ... > rollingFunction(gg.ts[,1],n=3,trim=FALSE,FUN="SharpeRatio.annualized") Manager 2001-12-31 NA 2002-01-31 NA 2002-02-28 1.5302 2002-03-31 4.3768 2002-04-30 6.9640 ... > rollingFunction(gg.ts[,1],n=3,trim=FALSE,FUN="SharpeRatio.annualized",rf=.03/12) Manager 2001-12-31 NA 2002-01-31 NA 2002-02-28 0.0298 2002-03-31 1.8587 2002-04-30 1.5598

Value

results over a rolling period

Note

Inspired by rollFun written by Diethelm Wurtz. We’ve extended the idea to all the columns provided.

Author(s)

Peter Carl rollingRegression 101

References

See Also rollFun

Examples

rollingRegression Rolling Regression on Returns

Description calculates rolling regression statistics on a return stream.

Usage rollingRegression(formula, data, width, ...)

Arguments formula regression formula for lm data data set for lm width size of the window over which to roll ... any other passthru parameters

Value

Note This code was posted by Douglas Bates to the R-help mailing list in response to a question posted by Ajay Shah. For the full discussion, see: http://www.mail-archive.com/r-help@ stat.math.ethz.ch/msg19544.html

Author(s) Douglas Bates

References http://www.mail-archive.com/[email protected]/msg19544.html 102 rollingStat

See Also lm apply

Examples

rollingStat wrapper to apply any function over a rolling time window

Description Function to apply any time series function over a rolling period, say the last three months. Pass in the function name as FUN, e.g., FUN = "mean". Useful for passing in several periods and functions for comparing different series.

Usage rollingStat(R, period = 3, trim = TRUE, FUN, ...)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns period the number of periods over which to calculate the statistic. Setting the period to 0 calculates the statistic "from inception" or using all of the data passed in trim TRUE/FALSE, whether to keep alignment caused by NA’s FUN function to apply over e.g., FUN = "mean" or FUN = "Return.cumulative" ... any other passthru parameters

Details

Value

Author(s) Peter Carl

References sortDrawdowns 103

See Also

Examples # Example includes how to pass in arguements to the function - must be in order: # > rollingStat(gg.ts@Data[,1],period=12,FUN="SharpeRatio.annualized",rf=.03/12) # [1] 1.476426 # > rollingStat(gg.ts@Data[,1],period=3,FUN="SharpeRatio.annualized",rf=.03/12) # [1] 6.804358 # > rollingStat(gg.ts@Data[,1],period=3,FUN="SharpeRatio.annualized",rf=0) # [1] 8.253612

sortDrawdowns order list of drawdowns from worst to best

Description sortDrawdowns(findDrawdowns(R)) Gives the drawdowns in order of worst to best

Usage sortDrawdowns(runs)

Arguments runs pass in runs array from findDrawdowns to be sorted

Value sorted list

return depth of drawdown from starting period to ending period length length in periods

Author(s) Peter Carl modified with permission from prototype function by Sankalp Upadhyay

References 104 statsTable

See Also DownsideDeviation maxDrawdown findDrawdowns sortDrawdowns chart.Drawdown table.Drawdowns table.DownsideRisk

Examples data(edhec) R=edhec[,"Funds.of.Funds"] findDrawdowns(R) sortDrawdowns(findDrawdowns(R))

statsTable 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. 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).

Usage statsTable(R, metrics = c("mean", "sd"), metricsNames = c("Average Return", "Standard Deviation"), ...)

Arguments R a 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 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), DownsideDeviation(x,MAR=0),maxDrawdown(x)) metricsNames = c("Semi Deviation", "Gain Deviation", "Loss Deviation", paste("Downside Devia- tion (MAR=",MAR*scale*100,"%)", sep=""), paste("Downside Deviation (rf=",rf*scale*100,"%)", sep=""), paste("Downside Deviation (0%)", sep=""), "Maximum Drawdown" ) table.AnnualizedReturns 105

Here’s how it’s working right now: > statsTable(monthlyReturns.ts,metrics=c("VaR.CornishFisher","mean"), metricsNames=c("modVaR","mean"),p=.95)

Actual S&P500TR modVaR 0.04186461 0.06261451 mean 0.00945000 0.01013684

Passing in attributes doesn’t quite work corrently. The issue is apparent in: > statsTable(monthlyReturns.ts,metrics=c("VaR.CornishFisher", "VaR.CornishFisher"), metricsNames=c("Modified VaR","Traditional VaR"), modified=c(TRUE,FALSE))

Actual S&P500TR Modified VaR 0.06340849 0.09334976 Traditional VaR 0.06340849 0.09334976

Warning messages: 1: the condition has length > 1 and only the first element will be used in: if (modified) 2: the condition has length > 1 and only the first element will be used in: if (modified) 3: the condition has length > 1 and only the first element will be used in: if (modified) 4: the condition has length > 1 and only the first element will be used in: if (modified)

Value A table with calculated metrics for each column

Author(s) Peter Carl

References

Examples

table.AnnualizedReturns Annualized Returns Summary: Statistics and Stylized Facts

Description Table of Annualized Return, Annualized Std Dev, and Annualized Sharpe

Usage table.AnnualizedReturns(R, ci = 0.95, scale = 12, rf = 0, digits = 4) 106 table.CAPM

Arguments

R a 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 digits number of digits to round results to

Value

A table of estimates of annualized returns and risk measures

Author(s)

Peter Carl

References

See Also Return.annualized StdDev.annualized SharpeRatio.annualized

Examples

table.CAPM Asset-Pricing Model Summary: Statistics and Stylized Facts

Description

Takes a set of returns and relates them to a market benchmark. Provides a set of measures related to the excess return single index model, or CAPM.

Usage table.CAPM(Ra, Rb, scale = 12, rf = 0, digits = 4) table.CAPM 107

Arguments Ra a vector of returns to test, e.g., the asset to be examined Rb a matrix, data.frame, 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, but cannot yet be used to show statistics for a set of assets against a benchmark.

Value A data frame with columns named for the columns in Rb and rows containing statistics.

Author(s) Peter Carl

References

See Also CAPM.alpha CAPM.beta TrackingError ActivePremium InformationRatio TreynorRatio

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) rf.zoo = download.RiskFree(start = start, end = end) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) 108 table.Correlation

time(rf.zoo) = as.yearmon(time(rf.zoo)) data.zoo = merge(edhec.zoo[,9,drop=FALSE],sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y") time(rf.zoo) = as.Date(time(rf.zoo),format="%b %Y")

table.CAPM(data.zoo[,1,drop=FALSE], data.zoo[,2,drop=FALSE], rf = rf.zoo)

table.Correlation calculate correlalations of multicolumn data

Description This is a wrapper for calculating correlation and significance against each column of the data pro- vided.

Usage table.Correlation(Ra, Rb, trim = TRUE, na.rm = FALSE, ...)

Arguments Ra a vector of returns to test, e.g., the asset to be examined Rb a matrix, data.frame, or timeSeries of benchmark(s) to test the asset against. trim TRUE/FALSE, whether to keep alignment caused by NA’s na.rm TRUE/FALSE Remove NA’s from the returns? ... any other passthru parameters

Value A dataframe with correlation and significance against each column of the data provided as Rb.

Note

Author(s) Peter Carl

References

See Also table.DownsideRisk 109

Examples # First we load the data data(edhec) edhec.length = dim(edhec)[1] start = rownames(edhec[1,]) start end = rownames(edhec[edhec.length,]) edhec.zoo = zoo(edhec, order.by = rownames(edhec)) rf.zoo = download.RiskFree(start = start, end = end) sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", end = end)

# Now we have to align it as "monthly" data time(edhec.zoo) = as.yearmon(time(edhec.zoo)) time(sp500.zoo) = as.yearmon(time(sp500.zoo)) time(rf.zoo) = as.yearmon(time(rf.zoo)) data.zoo = merge(edhec.zoo,sp500.zoo) time(data.zoo) = as.Date(time(data.zoo),format="%b %Y") time(rf.zoo) = as.Date(time(rf.zoo),format="%b %Y")

table.Correlation(data.zoo[,14,drop=FALSE],data.zoo[,1:13]) ctable = table.Correlation(data.zoo[,14,drop=FALSE],data.zoo[,1:13], conf.level=.99) dotchart(ctable[,1],labels=rownames(ctable),xlim=c(-1,1))

table.DownsideRisk Downside Risk Summary: Statistics and Stylized Facts

Description Creates estimates of various downside risk measures.

Usage table.DownsideRisk(R, ci = 0.95, scale = 12, rf = 0, MAR = 0.1/12, p = 0.99, digits = 4)

Arguments R a 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

Details 110 table.Drawdowns

Value

A dataframe organized as a table of estimates of downside risk measures for comparison across multiple instruments or funds.

Author(s)

Peter Carl

References

See Also DownsideDeviation maxDrawdown VaR.CornishFisher VaR.Beyond VaR.traditional StdDev

Examples

data(edhec) table.DownsideRisk(edhec,rf=.04/12, MAR =.05/12, p=.95)

table.Drawdowns Worst Drawdowns Summary: Statistics and Stylized Facts

Description

Creates table showing statistics for the worst drawdowns.

Usage table.Drawdowns(R, top= 5, ...)

Arguments

R a vector, matrix, data frame, timeSeries or zoo object of asset returns top the number of drawdowns to include ... any other passthru parameters table.HigherMoments 111

Details From Trough To Depth Length To Trough Recovery 2001-02-28 2002-09-30 2003-08-31 -0.10746342 31 20 11 1998-07-31 1998-08-31 1998-11-30 -0.05576688 5 2 3 2006-05-31 2006-07-31 2006-11-30 -0.03385062 7 3 4 2000-04-30 2000-05-31 2000-06-30 -0.02960503 3 2 1 2004-04-30 2004-08-31 2004-11-30 -0.02839620 8 5 3

Value A data.frame organized as a table of drawdown statistics.

Author(s) Peter Carl

References

See Also DownsideDeviation maxDrawdown findDrawdowns sortDrawdowns chart.Drawdown table.DownsideRisk

Examples data(edhec) table.Drawdowns(edhec[,"Long.Short.Equity"]) table.Drawdowns(edhec[,"Relative.Value"])

table.Drawdowns(download.SP500PriceReturns(end="2006-12-31")) # note that this example shows a drawdown that has not yet ended

table.HigherMoments Higher Moments Summary: Statistics and Stylized Facts

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. 112 table.HigherMoments

Usage

table.HigherMoments(Ra, Rb, scale = 12, rf = 0, digits = 4, method = "moment")

Arguments

Ra a 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

Value

table of summary statistics

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 kurtosis

Examples table.MonthlyReturns 113

table.MonthlyReturns Monthly Returns Summary: Statistics and Stylized Facts

Description Returns a basic set of statistics that match the period of the data passed in (e.g., monthly returns will get monthly statistics)

Usage table.MonthlyReturns(R, ci = 0.95, digits = 4)

Arguments R a 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.

Value Data frame of columns named to the columns of the data passed in, and rows names for the calcu- lated statistics calculated.

Note

Author(s) Peter Carl

References

See Also 114 table.Returns

Examples data(edhec) table.MonthlyReturns(edhec[,1:3]) t(table.MonthlyReturns(edhec))

table.Returns Monthly and Calendar year Return table

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.

Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec Year 2003 -1.05 -3.16 -1.07 7.99 8.97 1.49 -2.03 -0.79 4.32 -0.89 -1.21 3.05 15.83 2004 1.83 -0.70 2.45 0.36 0.13 -1.92 0.66 -1.74 -1.37 -0.08 3.90 -0.52 2.87 2005 2.00 1.28 -1.04 -0.18 1.64 1.91 4.24 1.92 -1.63 1.45 -0.35 0.00 11.68 2006 2.10 NA NA NA NA NA NA NA NA NA NA NA 2.10

Usage table.Returns(R, digits = 1, as.perc = TRUE)

Arguments R a vector, matrix, data frame, timeSeries or zoo object of asset returns digits number of digits to round results to for presentation as.perc TRUE/FALSE if TRUE, multiply simple returns by 100 to get %

Value table of returns

Note This function assumes monthly returns, and does not currently have handling for other scales. This function defaults to the first column as the returns to be formatted, but the function will format the column specified.

Author(s) Peter Carl

References table.RollingPeriods 115

See Also

Examples data(edhec) table.Returns(edhec) t(table.Returns(edhec)) table.Returns(edhec[,c(13,2,4)])

table.RollingPeriods Rolling Periods Summary: Statistics and Stylized Facts

Description A table of estimates of rolling period return measures

Usage table.RollingPeriods(R, periods = subset(c(3, 6, 9, 12, 18, 24, 36, 48),c(3, 6, 9, 12, 18, 24, 36, 48) < length(as.matrix(R[,1]))), scale = 12, rf = 0, FUNCS = c("mean", "sd"), digits = 4, ...)

Arguments R a 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) 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) FUNCS list of functions to apply the rolling period to digits number of digits to round results to ... any other passthru parameters

Value A table of estimates of rolling period return measures 116 table.RollingPeriods

Author(s) Peter Carl

References

See Also

Examples data(edhec) table.RollingPeriods(edhec[,10:13], FUNCS=c("SharpeRatio","VaR.CornishFisher"),periods=c(12,24,36)) Index

∗Topic datasets download.RiskFree, 87 edhec, 89 download.SP500PriceReturns, managers, 91 88 ∗Topic distribution DownsideDeviation, 15 ActivePremium, 1 findDrawdowns, 90 apply.fromstart, 56 InformationRatio, 17 apply.rolling, 57 KellyRatio, 18 BetaCoKurtosis, 3 maxDrawdown, 92 BetaCoSkewness, 4 mean.utils, 93 BetaCoVariance, 5 moment.fourth, 94 CalculateReturns, 11 moment.third, 95 CalmarRatio, 12 Omega, 19 CAPM.alpha, 6 Return.annualized, 33 CAPM.beta, 7 Return.cumulative, 34 CAPM.utils, 9 Return.excess, 35 chart.Bar, 58 rollingCorrelation, 96 chart.BarVaR, 59 rollingFunction, 97 chart.Boxplot, 61 rollingRegression, 99 chart.Correlation, 62 rollingStat, 100 chart.Correlation.color, 63 sd.multiperiod, 44 chart.CumReturns, 64 SemiDeviation, 37 chart.Histogram, 66 SharpeRatio, 38 chart.QQPlot, 68 SharpeRatio.annualized, 39 chart.RegressionDiagnostics, SharpeRatio.modified, 41 69 sortDrawdowns, 101 chart.RelativePerformance, 70 SortinoRatio, 42 chart.RiskReturnScatter, 71 statsTable, 102 chart.RollingCorrelation, 73 table.AnnualizedReturns, 103 chart.RollingMean, 74 table.CAPM, 104 chart.RollingPerformance, 75 table.Correlation, 106 chart.RollingRegression, 77 table.DownsideRisk, 107 chart.Scatter, 79 table.Drawdowns, 108 chart.TimeSeries, 80 table.HigherMoments, 109 charts.PerformanceSummary, 82 table.MonthlyReturns, 111 charts.RollingPerformance, 84 table.Returns, 112 checkData, 85 table.RollingPeriods, 113 CoKurtosis, 13 TrackingError, 45 CoSkewness, 14 TreynorRatio, 46 cum.utils, 86 UpDownRatios, 48

117 118 INDEX

UpsidePotentialRatio, 49 chart.RegressionDiagnostics, VaR.Beyond, 51 69 VaR.CornishFisher, 52 chart.RelativePerformance, 70 VaR.Marginal, 55 chart.RiskReturnScatter, 71 ∗Topic hplot chart.RollingCorrelation, 73 chart.Bar, 58 chart.RollingMean, 74 chart.BarVaR, 59 chart.RollingPerformance, 75 chart.Boxplot, 61 chart.RollingRegression, 77 chart.Correlation, 62 chart.Scatter, 79 chart.Correlation.color, 63 chart.TimeSeries, 80 chart.CumReturns, 64 charts.PerformanceSummary, 82 chart.Histogram, 66 charts.RollingPerformance, 84 chart.QQPlot, 68 checkData, 85 chart.RegressionDiagnostics, CoKurtosis, 13 69 CoSkewness, 14 chart.RelativePerformance, 70 cum.utils, 86 chart.RiskReturnScatter, 71 download.RiskFree, 87 chart.RollingCorrelation, 73 download.SP500PriceReturns, chart.RollingMean, 74 88 chart.RollingPerformance, 75 DownsideDeviation, 15 chart.RollingRegression, 77 findDrawdowns, 90 chart.Scatter, 79 InformationRatio, 17 chart.TimeSeries, 80 KellyRatio, 18 charts.PerformanceSummary, 82 maxDrawdown, 92 charts.RollingPerformance, 84 mean.utils, 93 ∗Topic internal moment.fourth, 94 PerformanceAnalytics-internal, moment.third, 95 21 Omega, 19 ∗Topic models Return.annualized, 33 ActivePremium, 1 Return.cumulative, 34 apply.fromstart, 56 Return.excess, 35 apply.rolling, 57 rollingCorrelation, 96 BetaCoKurtosis, 3 rollingFunction, 97 BetaCoSkewness, 4 rollingRegression, 99 BetaCoVariance, 5 rollingStat, 100 CalculateReturns, 11 sd.multiperiod, 44 CalmarRatio, 12 SemiDeviation, 37 CAPM.alpha, 6 SharpeRatio, 38 CAPM.beta, 7 SharpeRatio.annualized, 39 CAPM.utils, 9 SharpeRatio.modified, 41 chart.Bar, 58 sortDrawdowns, 101 chart.BarVaR, 59 SortinoRatio, 42 chart.Boxplot, 61 statsTable, 102 chart.Correlation, 62 table.AnnualizedReturns, 103 chart.Correlation.color, 63 table.CAPM, 104 chart.CumReturns, 64 table.Correlation, 106 chart.Histogram, 66 table.DownsideRisk, 107 chart.QQPlot, 68 table.Drawdowns, 108 INDEX 119

table.HigherMoments, 109 download.SP500PriceReturns, table.MonthlyReturns, 111 88 table.Returns, 112 DownsideDeviation, 15 table.RollingPeriods, 113 findDrawdowns, 90 TrackingError, 45 InformationRatio, 17 TreynorRatio, 46 KellyRatio, 18 UpDownRatios, 48 maxDrawdown, 92 UpsidePotentialRatio, 49 mean.utils, 93 VaR.Beyond, 51 moment.fourth, 94 VaR.CornishFisher, 52 moment.third, 95 VaR.Marginal, 55 Omega, 19 ∗Topic multivariate Return.annualized, 33 ActivePremium, 1 Return.cumulative, 34 apply.fromstart, 56 Return.excess, 35 apply.rolling, 57 rollingCorrelation, 96 BetaCoKurtosis, 3 rollingFunction, 97 BetaCoSkewness, 4 rollingRegression, 99 BetaCoVariance, 5 rollingStat, 100 CalculateReturns, 11 sd.multiperiod, 44 CalmarRatio, 12 SemiDeviation, 37 CAPM.alpha, 6 SharpeRatio, 38 CAPM.beta, 7 SharpeRatio.annualized, 39 CAPM.utils, 9 SharpeRatio.modified, 41 chart.Bar, 58 sortDrawdowns, 101 chart.BarVaR, 59 SortinoRatio, 42 chart.Boxplot, 61 statsTable, 102 chart.Correlation, 62 table.AnnualizedReturns, 103 chart.Correlation.color, 63 table.CAPM, 104 chart.CumReturns, 64 table.Correlation, 106 chart.Histogram, 66 table.DownsideRisk, 107 chart.QQPlot, 68 table.Drawdowns, 108 chart.RegressionDiagnostics, table.HigherMoments, 109 69 table.MonthlyReturns, 111 chart.RelativePerformance, 70 table.Returns, 112 chart.RiskReturnScatter, 71 table.RollingPeriods, 113 chart.RollingCorrelation, 73 TrackingError, 45 chart.RollingMean, 74 TreynorRatio, 46 chart.RollingPerformance, 75 UpDownRatios, 48 chart.RollingRegression, 77 UpsidePotentialRatio, 49 chart.Scatter, 79 VaR.Beyond, 51 chart.TimeSeries, 80 VaR.CornishFisher, 52 charts.PerformanceSummary, 82 VaR.Marginal, 55 charts.RollingPerformance, 84 ∗Topic package checkData, 85 PerformanceAnalytics-package, CoKurtosis, 13 23 CoSkewness, 14 ∗Topic ts cum.utils, 86 ActivePremium, 1 download.RiskFree, 87 apply.fromstart, 56 120 INDEX

apply.rolling, 57 Return.annualized, 33 BetaCoKurtosis, 3 Return.cumulative, 34 BetaCoSkewness, 4 Return.excess, 35 BetaCoVariance, 5 rollingCorrelation, 96 CalculateReturns, 11 rollingFunction, 97 CalmarRatio, 12 rollingRegression, 99 CAPM.alpha, 6 rollingStat, 100 CAPM.beta, 7 sd.multiperiod, 44 CAPM.utils, 9 SemiDeviation, 37 chart.Bar, 58 SharpeRatio, 38 chart.BarVaR, 59 SharpeRatio.annualized, 39 chart.Boxplot, 61 SharpeRatio.modified, 41 chart.Correlation, 62 sortDrawdowns, 101 chart.Correlation.color, 63 SortinoRatio, 42 chart.CumReturns, 64 statsTable, 102 chart.Drawdown, 65 table.AnnualizedReturns, 103 chart.Histogram, 66 table.CAPM, 104 chart.QQPlot, 68 table.Correlation, 106 chart.RegressionDiagnostics, table.DownsideRisk, 107 69 table.Drawdowns, 108 chart.RelativePerformance, 70 table.HigherMoments, 109 chart.RiskReturnScatter, 71 table.MonthlyReturns, 111 chart.RollingCorrelation, 73 table.Returns, 112 table.RollingPeriods chart.RollingMean, 74 , 113 TrackingError chart.RollingPerformance, 75 , 45 TreynorRatio chart.RollingRegression, 77 , 46 UpDownRatios chart.Scatter, 79 , 48 UpsidePotentialRatio, 49 chart.TimeSeries, 80 VaR.Beyond, 51 charts.PerformanceSummary, 82 VaR.CornishFisher, 52 charts.RollingPerformance, 84 VaR.Marginal, 55 checkData, 85 CoKurtosis , 13 ActivePremium, 1, 10, 17, 25, 39, 40, 105 CoSkewness , 14 aggregate, 23 cum.utils, 86 allsymbols download.RiskFree, 87 (PerformanceAnalytics-internal), download.SP500PriceReturns, 21 88 apply, 32, 57, 58, 100 DownsideDeviation, 15 apply.fromstart, 32, 56 edhec, 89 apply.rolling, 32, 57 findDrawdowns, 90 InformationRatio, 17 BetaCoK (BetaCoKurtosis), 3 KellyRatio, 18 BetaCoKurtosis, 3, 14, 110 managers, 91 BetaCoS (BetaCoSkewness), 4 maxDrawdown, 92 BetaCoSkewness, 4, 15, 110 mean.utils, 93 BetaCoV (BetaCoVariance), 5 moment.fourth, 94 BetaCoVariance, 5, 7, 8, 110 moment.third, 95 bluefocus Omega, 19 (PerformanceAnalytics-internal), INDEX 121

21 charts.RollingRegression bluemono (chart.RollingRegression), (PerformanceAnalytics-internal), 77 21 checkData, 31, 85 bond.dates checkDataMatrix (checkData), 85 (PerformanceAnalytics-internal),checkDataVector (checkData), 85 21 checkDataZoo (checkData), 85 bond.labels closedsymbols (PerformanceAnalytics-internal), (PerformanceAnalytics-internal), 21 21 boxplot, 61 CoKurtosis, 3, 13, 26, 110 CoSkewness, 4, 14, 26, 110 CalculateReturns, 11, 23, 24, 31, 87–89 cov, 96, 97 CalmarRatio, 12 cum.utils, 86 CAPM.alpha, 6, 8, 10, 25, 105 cummax, 87 CAPM.beta, 5, 6, 7, 9, 10, 25, 29, 47, 75, 105 cummax.column, 32, 86 CAPM.CML, 25 cummax.column (cum.utils), 86 CAPM.CML (CAPM.utils), 9 cumprod, 87 CAPM.CML.slope, 25 cumprod.column, 32, 86 CAPM.RiskPremium, 25 cumprod.column (cum.utils), 86 CAPM.RiskPremium (CAPM.utils), 9 CVaR, 30, 52, 55 CAPM.SML.slope, 25 CVaRplus, 30, 51, 52 CAPM.SML.slope (CAPM.utils), 9 cycles.dates CAPM.utils, 6, 8, 9 (PerformanceAnalytics-internal), chart.Bar, 27, 58 21 chart.BarVaR, 27, 59, 84 chart.Boxplot, 28, 30, 61, 69 dark6equal chart.Correlation, 28, 62, 63 (PerformanceAnalytics-internal), chart.Correlation.color, 28, 62, 63 21 chart.CumReturns, 27, 64, 83, 84 dark8equal chart.Drawdown, 27, 29, 65, 84, 90, 91, (PerformanceAnalytics-internal), 93, 102, 109 21 chart.Histogram, 26, 28, 66, 69 download.RiskFree, 32, 87, 89 chart.QQPlot, 26, 28, 29, 68, 69 download.SP500PriceReturns, 32, 88, chart.RegressionDiagnostics, 28, 88 69, 78 DownsideDeviation, 15, 29, 37, 43, 50, chart.RelativePerformance, 27, 70 102, 108, 109 chart.RiskReturnScatter, 27, 71 Drawdowns (findDrawdowns), 90 chart.RollingCorrelation, 28, 73 chart.RollingMean, 28, 74 Ecdf, 21 chart.RollingPerformance, 28, 75, 85 edhec, 32, 89, 91 chart.RollingRegression, 28, 69, 77 equity.dates chart.Scatter, 27, 79 (PerformanceAnalytics-internal), chart.TimeSeries, 59, 60, 65, 66, 80 21 charts.PerformanceSummary, 27, 82 equity.labels charts.RollingPerformance, 28, 77, (PerformanceAnalytics-internal), 84 21 charts.RollingRegression, 28, 69 expression, 21 122 INDEX factanal, 26 mean.geometric (mean.utils), 93 fillsymbols mean.LCL, 24, 93 (PerformanceAnalytics-internal),mean.LCL (mean.utils), 93 21 mean.stderr, 24, 93 findDrawdowns, 29, 66, 90, 93, 102, 109 mean.stderr (mean.utils), 93 mean.UCL, 25, 93 get.hist.quote, 31, 87–89 mean.UCL (mean.utils), 93 greenfocus mean.utils, 93 (PerformanceAnalytics-internal),min, 25 21 modifiedVaR, 29, 31 greenmono modifiedVaR (VaR.CornishFisher), (PerformanceAnalytics-internal), 52 21 modSharpe (SharpeRatio.modified), grey6mono 41 (PerformanceAnalytics-internal),moment.fourth, 94, 95 21 moment.third, 95, 95 grey8mono (PerformanceAnalytics-internal),nclass.FD, 67 21 nclass.scott, 67 nclass.Sturges, 67 hist, 66, 67 Omega, 19, 29 InformationRatio, 2, 10, 17, 25, 29, opensymbols 38–40, 43, 46, 50, 105 (PerformanceAnalytics-internal), KellyRatio, 18, 25 21 kurtosis, 3, 14, 26, 55, 110 PerformanceAnalytics legend, 22, 23 (PerformanceAnalytics-package), legend 23 (PerformanceAnalytics-internal),PerformanceAnalytics-internal, 21 21 PerformanceAnalytics-package, 23 linesymbols pfolioReturn, 24 (PerformanceAnalytics-internal),plot, 27, 59, 60, 65–68, 70–72, 74–76, 21 78–81, 83 lm, 99, 100 plotmath, 22 points, 22 macro.dates portfolio.optim, 29 (PerformanceAnalytics-internal),princomp, 26 21 macro.labels qnorm, 30, 52 (PerformanceAnalytics-internal),qqplot, 69 21 quantile, 25, 52 managers, 91 MarkowitzPortfolio, 29 rainbow10equal max, 25 (PerformanceAnalytics-internal), maxDrawdown, 13, 29, 66, 91, 92, 102, 108, 21 109 rainbow12equal mean, 24, 94 (PerformanceAnalytics-internal), mean.geometric, 24, 93 21 INDEX 123 rainbow6equal SemiVariance (SemiDeviation), 37 (PerformanceAnalytics-internal),set6equal 21 (PerformanceAnalytics-internal), rainbow8equal 21 (PerformanceAnalytics-internal),set8equal 21 (PerformanceAnalytics-internal), range, 25 21 rcorr, 25 SharpeRatio, 9, 10, 12, 17, 25, 29, 38, 40, redfocus 42, 43, 47, 50 (PerformanceAnalytics-internal),SharpeRatio.annualized, 24, 29, 39, 21 39, 104 redmono SharpeRatio.modified, 12, 13, 29, 41, (PerformanceAnalytics-internal), 54, 55 21 skewness, 4, 15, 26, 55 Return.annualized, 2, 13, 24, 33, 35, 57, solve.QP, 29 75, 104 sortDrawdowns, 29, 66, 90, 91, 93, 101, Return.cumulative, 11, 34, 34 102, 109 Return.excess, 24, 35 SortinoRatio, 25, 29, 39, 40, 42, 47, 49, rich10equal 50 (PerformanceAnalytics-internal),statsTable, 102 21 std (sd.multiperiod), 44 rich12equal StdDev, 108 (PerformanceAnalytics-internal),StdDev (sd.multiperiod), 44 21 StdDev.annualized, 104 rich6equal SterlingRatio (CalmarRatio), 12 (PerformanceAnalytics-internal),strwidth, 22 21 SystematicBeta (BetaCoVariance), 5 rich8equal SystematicKurtosis, 26 (PerformanceAnalytics-internal),SystematicKurtosis 21 (BetaCoKurtosis), 3 risk.dates SystematicSkewness, 26 (PerformanceAnalytics-internal),SystematicSkewness 21 (BetaCoSkewness), 4 risk.labels SystematicVariance (PerformanceAnalytics-internal), (BetaCoVariance), 5 21 rollapply, 57, 58 table.AnnualizedReturns, 27, 103 rollFun, 96, 98, 99 table.CAPM, 27, 104 rollingCorrelation, 96 table.Correlation, 27, 62, 63, 106 rollingFunction, 28, 97 table.DownsideRisk, 27, 66, 91, 93, rollingRegression, 99 102, 107, 109 rollingStat, 28, 100 table.Drawdowns, 27, 66, 91, 93, 102, 108 table.HigherMoments, 27, 109 sd, 25, 28, 45, 94 table.MonthlyReturns, 24, 27, 111 sd.annualized, 24, 28 table.Returns, 27, 112 sd.annualized (sd.multiperiod), 44 table.RollingPeriods, 27, 113 sd.multiperiod, 28, 44 tim10equal SemiDeviation, 29, 37, 43, 50 (PerformanceAnalytics-internal), SemiVariance, 26, 29, 43, 50 21 124 INDEX tim12equal (PerformanceAnalytics-internal), 21 tim6equal (PerformanceAnalytics-internal), 21 tim8equal (PerformanceAnalytics-internal), 21 TrackingError, 2, 10, 17, 25, 39, 40, 45, 46, 105 TreynorRatio, 29, 46, 105 tsbootstrap, 30

UpDownRatios, 29, 48 UPR (UpsidePotentialRatio), 49 UpsidePotentialRatio, 12, 13, 25, 29, 49

VaR, 30, 53, 55, 60 VaR (VaR.CornishFisher), 52 var, 26 VaR.backtest, 30, 53, 55 VaR.Beyond, 30, 51, 55, 108 VaR.CornishFisher, 31, 42, 52, 52, 56, 60, 108 VaR.gpd, 30, 53, 55 VaR.Marginal, 31, 55, 55 VaR.mean, 54 VaR.norm, 30, 53, 55 VaR.traditional, 30, 52–54, 108 xy.coords, 21