\documentclass[12pt,letterpaper,english]{article}
\usepackage{times}
\usepackage[T1]{fontenc}
\IfFileExists{url.sty}{\usepackage{url}}
                      {\newcommand{\url}{\texttt}}
\usepackage{babel}
\usepackage{noweb}
%\usepackage[ae,hyper]{Rd}
%\usepackage{Sweave}
\usepackage[ae,hyper]{/usr/lib/R/share/texmf/Rd}
\usepackage{/usr/lib/R/share/texmf/Sweave}


%\VignetteIndexEntry{PerformanceAnalytics Statistical Technique Overview}
%\VignetteDepends{PerformanceAnalytics}
%\VignetteKeywords{returns, performance, risk, benchmark, portfolio}
%\VignettePackage{PerformanceAnalytics}

%%%%%%%%%%%%%%%%%%%%%% End Setup Lines

\begin{document}

\title{\pkg{PerformanceAnalytics} Statistical Technique Overview}
\author {Peter Carl \& Brian G. Peterson}


\makeatletter
\makeatother
\maketitle

\begin{abstract}
  This vignette gives a brief overview of statistical techniques implemented
  in \pkg{PerformanceAnalytics}. For a more complete overview of the package's functionality
  and extensibility see the manual pages.  We develop the examples using data
  for six (hypothetical) managers, asset class indices, and EDHEC data.
\end{abstract}

%\tableofcontents

\HeaderA{PerformanceAnalytics-package}{Econometric tools for performance and risk analysis.}{PerformanceAnalytics.Rdash.package}
\begin{Description}\relax
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.
\end{Description}
\begin{Details}\relax
\Tabular{rl}{
Package: & PerformanceAnalytics\\
Type: & Package\\
Version: & 0.9.5\\
Date: & 2007-06-29\\
License: & GPL\\
Copyright: & (c) 2004-2007  and \\
URL: & \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 \code{\LinkA{CalculateReturns}{CalculateReturns}} for calculating returns from prices, and be aware that the \code{\LinkA{aggregate}{aggregate}} function has methods for \code{tseries} and \code{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 \code{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.
\end{Details}
\begin{Section}{Performance Analysis}
Performance measurement is the first step down a longer road.  When discussing performance at an abstract level, terms such as \dQuote{return} and \dQuote{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: \dQuote{How much could I lose?}  Portfolio construction and risk budgeting are two sides of the same coin: \dQuote{How do I maximize my expected gain and avoid going broke?}  But before we can approach those questions we first have to ask: \dQuote{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 \emph{right} answer delivered in these metrics and charts.  What there will be is an accretion of evidence, organized to \emph{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 \dQuote{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 \dQuote{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 \code{PerformanceAnalytics} library focuses on returns.  See \code{\LinkA{CalculateReturns}{CalculateReturns}} for converting net asset values or prices into returns, either discrete or continuous.  Many papers and theories refer to \dQuote{excess returns}: we have implemented the most common methods of calculating excess returns in function \code{\LinkA{Return.excess}{Return.excess}}.

See \code{\LinkA{pfolioReturn}{pfolioReturn}} in package \code{fPortfolio} for calculating returns from a portfolio of instruments with a combination of historical returns and a weighting vector.  See package \code{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 \code{\LinkA{Return.annualized}{Return.annualized}}, \code{\LinkA{sd.annualized}{sd.annualized}}, and \code{\LinkA{SharpeRatio.annualized}{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 \code{\LinkA{table.MonthlyReturns}{table.MonthlyReturns}} include:
\\
\Tabular{ll}{
\code{\LinkA{mean}{mean}}  &  arithmetic mean \\
\code{\LinkA{mean.geometric}{mean.geometric}} & geometric mean \\
\code{\LinkA{mean.stderr}{mean.stderr}} & standard error of the mean (S.E. mean) \\
\code{\LinkA{mean.LCL}{mean.LCL}} & lower confidence level (LCL) of the mean \\
\code{\LinkA{mean.UCL}{mean.UCL}} & upper confidence level (UCL) of the mean \\
\code{\LinkA{quantile}{quantile}}  & for calculating various quantiles of the distribution \\
\code{\LinkA{min}{min}}  & minimum return \\
\code{\LinkA{max}{max}}  & maximum return \\
\code{\LinkA{range}{range}} & range of returns \\
\code{length(R)}  & number of observations \\
\code{sum(is.na(R))} & number of NA's \\
}

\emph{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 \Cite{Portfolio Selection}.  It also encompasses CAPM, below, the efficient market hypothesis, and all forms of quantitative portfolio construction and optimization.

\emph{The Capital Asset Pricing Model (CAPM)}, initially developed by \Cite{William Sharpe in 1964}, provides a justification for passive or index investing by positing that assets that are not on the efficient frontier will either rise or lower in price until they are on the efficient frontier of the market portfolio. The \code{\LinkA{CAPM.RiskPremium}{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.  \code{\LinkA{CAPM.alpha}{CAPM.alpha}} is the degree to which the assets returns are not due to the return that could be captured from the market. Conversely, \code{\LinkA{CAPM.beta}{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 \code{\LinkA{CAPM.CML}{CAPM.CML}} relates the excess expected return on an efficient market portfolio to its risk (represented in CAPM by \code{\LinkA{sd}{sd}} ).  The slope of the CML, \code{\LinkA{CAPM.CML.slope}{CAPM.CML.slope}}, is the Sharpe Ratio for the market portfolio. The Security Market Line is constructed by calculating the line of \code{\LinkA{CAPM.RiskPremium}{CAPM.RiskPremium}} over \code{\LinkA{CAPM.beta}{CAPM.beta}}.  For the benchmark asset this will be 1 over the risk premium of the benchmark asset. The slope of the SML, primarily for plotting purposes, is given by \code{\LinkA{CAPM.SML.slope}{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 \code{\LinkA{ActivePremium}{ActivePremium}}, which is the investment's annualized return minus the benchmark's annualized return. A closely related measure is the \code{\LinkA{TrackingError}{TrackingError}}, which  measures the unexplained portion of the investment's performance relative to a benchmark. The \code{\LinkA{InformationRatio}{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 \code{\LinkA{KellyRatio}{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 \code{\LinkA{InformationRatio}{InformationRatio}} to describe the \dQuote{edge} an investment would have over a random strategy or distribution.

\code{\LinkA{InformationRatio}{InformationRatio}}, \code{\LinkA{KellyRatio}{KellyRatio}}, \code{\LinkA{SharpeRatio}{SharpeRatio}}, \code{\LinkA{SortinoRatio}{SortinoRatio}}, \code{\LinkA{UpsidePotentialRatio}{UpsidePotentialRatio}}, Spearman Rank Correlation provided by \code{\LinkA{rcorr}{rcorr}} and other methods discussed here are all methods of rank-ordering relative performance. \Cite{Alexander and Dimitriu(2004) in \dQuote{The Art of Investing in 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 \dQuote{buckets} of target instruments will have significant overlap.  This observation specifically supports the point made early in this document regarding \dQuote{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 examining 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 \code{\LinkA{chart.QQPlot}{chart.QQPlot}} and \code{\LinkA{chart.Histogram}{chart.Histogram}} will quickly give you a feel for whether or not you are looking at a normally distributed return history.  Differences between \code{\LinkA{var}{var}} and \code{\LinkA{SemiVariance}{SemiVariance}} will help you identify \code{\LinkA{skewness}{skewness}} in the returns.  Skewness measures the degree of asymmetry in the return distribution.  Positive Skewness indicates that more of the returns are positive, negative skewness indicates that more of the returns are negative.  An investor should in most cases prefer a positively skewed asset to a similar (style, industry, region) asset that has a negative skewness. Kurtosis measures the concentration of the returns in any given part of the distribution (as you should see visually in a histogram).  The \code{\LinkA{kurtosis}{kurtosis}} function will by default return what is referred to as \dQuote{excess kurtosis}, where 0 is a normal distribution, other methods of calculating kurtosis than \code{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 \code{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 diversify 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 \code{\LinkA{skewness}{skewness}} and \code{\LinkA{kurtosis}{kurtosis}} provided by package \code{fBasics}.  Increasing skewness and decreasing kurtosis of the target portfolio probably 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 market conditions in much the way that minimizing covariance and systematic beta will mark a well diversified portfolio in a mean-variance framework.  See \code{\LinkA{CoSkewness}{CoSkewness}} and \code{\LinkA{CoKurtosis}{CoKurtosis}} for the co-moments and \code{\LinkA{SystematicSkewness}{SystematicSkewness}} and \code{\LinkA{SystematicKurtosis}{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 \emph{analysis} in this summary section, but it is also important to note that we have \emph{not} covered performance \emph{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 \dQuote{factor analysis} where \dQuote{risk factors} are used to retrospectively explain sources of risk, and through regression and other analytical methods \emph{predict} future period returns and risk based on factor drivers.  These are well covered in chapters on factor analysis in \Cite{Zivot and Wang(2006)} and also in the \R{} functions \code{\LinkA{factanal}{factanal}} for basic factor analysis and \code{\LinkA{princomp}{princomp}} for Principal Component Analysis.  The authors feel that financial engineers and analysts would benefit from some wrapping of this functionality focused on finance, but the capabilities already available from the base functions are quite powerful.
\end{Section}
\begin{Section}{Summary Tabular Data}
Summary statistics are then the necessary aggregation and reduction of these (potentially thousands) 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 returns organized by month and cumulated by calendar year is usually presented as a table, such as in \code{\LinkA{table.CalendarReturns}{table.CalendarReturns}}.  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:
\Tabular{rl}{
\code{\LinkA{table.MonthlyReturns}{table.MonthlyReturns}} &  provides a statistical summary of the monthly returns themselves  \\
\code{\LinkA{table.AnnualizedReturns}{table.AnnualizedReturns}} &  calculates aggregate returns and risk (usually used in graphics, see below)  \\
\code{\LinkA{table.CAPM}{table.CAPM}} &  a collection of statistics offered by practitioners of Modern Portfolio Theory  \\
\code{\LinkA{table.HigherMoments}{table.HigherMoments}} &  metrics for evaluating diversification potential by comparing higher moments \\
\code{\LinkA{table.DownsideRisk}{table.DownsideRisk}} &  statistics for those wanting to compare the extent of observed losses  \\
\code{\LinkA{table.Drawdowns}{table.Drawdowns}} &  data on the length and depth of the worst drawdowns  \\
\code{\LinkA{table.Correlation}{table.Correlation}} & a table arranged for comparing correlations  \\
\code{\LinkA{table.RollingPeriods}{table.RollingPeriods}} & calculates statistics over varying periods of time  \\
}
\end{Section}
\begin{Section}{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 output of \R{} default graphics functions such as \code{\LinkA{plot}{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 \code{\LinkA{chart.CumReturns}{chart.CumReturns}}.  Individual period returns may be helpful for identifying problematic periods, such as in \code{\LinkA{chart.Bar}{chart.Bar}}.  Risk measures can be helpful when overlaid on the period returns, to display the bounds at which losses may be expected.  See \code{\LinkA{chart.BarVaR}{chart.BarVaR}} and the following section on Risk Analysis.  More information can be conveyed when such charts are displayed together, as in \code{\LinkA{charts.PerformanceSummary}{charts.PerformanceSummary}}, which combines the performance data with detail on downside risk (see \code{\LinkA{chart.Drawdown}{chart.Drawdown}}).

Two-dimensional charts can also be useful while remaining easy to understand.  \code{\LinkA{chart.Scatter}{chart.Scatter}} is a utility scatter chart with some additional attributes that are used in \code{\LinkA{chart.RiskReturnScatter}{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 \code{\LinkA{chart.RelativePerformance}{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 chart is less important than the slope of the line.  If the slope is positive, the first asset is outperforming 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.  \code{\LinkA{chart.Boxplot}{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 returns 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.  \code{\LinkA{chart.Histogram}{chart.Histogram}} and \code{\LinkA{chart.QQPlot}{chart.QQPlot}} are two charts from the RMetrics packages with only small modifications.

Rolling performance is typically used as a way to assess stability of a return stream.  Although perhaps 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 \code{\LinkA{chart.RollingPerformance}{chart.RollingPerformance}}, which is a way to display different metrics over rolling time periods.  \code{\LinkA{chart.RollingMean}{chart.RollingMean}} is a specific example of a rolling mean and one standard deviation bands.  A group of related metrics is offered in \code{\LinkA{charts.RollingPerformance}{charts.RollingPerformance}}.  These charts use utility functions such as \code{\LinkA{rollingFunction}{rollingFunction}} and \code{\LinkA{rollingStat}{rollingStat}}.  \code{\LinkA{chart.RollingCorrelation}{chart.RollingCorrelation}} shows how correlations change over rolling periods.  \code{\LinkA{chart.RollingRegression}{chart.RollingRegression}} displays the coefficients of a linear model fitted over rolling periods.  A group of charts in \code{\LinkA{charts.RollingRegression}{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.  \code{\LinkA{chart.RegressionDiagnostics}{chart.RegressionDiagnostics}}, \code{\LinkA{chart.Correlation}{chart.Correlation}}, and \code{\LinkA{chart.Correlation.color}{chart.Correlation.color}} are examples.  The latter two are slight modifications of code from the package \code{MASS} and the \R{} \code{base}.  See their documentation for more information.

We have been greatly inspired by other peoples' work, some of which is on display at \url{http://addictedtor.free.fr/}.  Particular inspiration came from Dirk Eddelbuettel and John Bollinger for their work at \url{http://addictedtor.free.fr/graphiques/RGraphGallery.php?graph=65}.
\end{Section}
\begin{Section}{Risk Analysis}
Many methods have been proposed to measure, monitor, and control the risks of a diversified portfolio. Perhaps a few definitions are in order on how different risks are generally classified. \emph{Market Risk} is the risk to the portfolio from a decline in the market price of instruments in the portfolio.  \emph{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.  \emph{Credit Risk} is also sometimes called \emph{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 \emph{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 univariate standard deviation on a portfolio.  See \code{\LinkA{sd}{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 \code{\LinkA{sd.annualized}{sd.annualized}}, or the equivalent function \code{\LinkA{sd.multiperiod}{sd.multiperiod}} for scaling to an arbitrary number of periods.  Many assets, including hedge funds, commodities, options, and even most common stocks over a sufficiently long period, do not follow a normal distribution.  For such 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 \code{\LinkA{SemiVariance}{SemiVariance}} would be a better measure of risk than variance.  See \Cite{Zin, Markowitz, Zhao(2006)} \url{http://papers.ssrn.com/sol3/papers.cfm?abstract_id=910640}.  This measure is also called \code{\LinkA{SemiDeviation}{SemiDeviation}}.  The more general case of downside deviation is implemented in the function \code{\LinkA{DownsideDeviation}{DownsideDeviation}}, as proposed by \Cite{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 \code{\LinkA{solve.QP}{solve.QP}} or \code{\LinkA{portfolio.optim}{portfolio.optim}} or \code{\LinkA{MarkowitzPortfolio}{MarkowitzPortfolio}}. Use of semivariance or many other risk measures will not necessarily create a smooth ellipse, causing significant additional difficulties for the portfolio manager trying to build an optimal portfolio.  We'll leave a more complete treatment and implementation of portfolio optimization techniques for another time.

Another very widely used downside risk measures is analysis of drawdowns, or loss from peak value achieved. The simplest method is to check the \code{\LinkA{maxDrawdown}{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 \code{\LinkA{findDrawdowns}{findDrawdowns}} and \code{\LinkA{sortDrawdowns}{sortDrawdowns}} in order from worst/major to smallest/minor. The \code{\LinkA{UpDownRatios}{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 \code{\LinkA{chart.Drawdown}{chart.Drawdown}}.

One of the most commonly used and cited measures of the risk/reward tradeoff of an investment or portfolio is the \code{\LinkA{SharpeRatio}{SharpeRatio}}, which measures return over standard deviation.  If you are comparing multiple assets using Sharpe, you should use \code{\LinkA{SharpeRatio.annualized}{SharpeRatio.annualized}}. It is important to note that William Sharpe now recommends \code{\LinkA{InformationRatio}{InformationRatio}} preferentially to the original Sharpe Ratio. The \code{\LinkA{SortinoRatio}{SortinoRatio}} utilizes mean return over \code{\LinkA{DownsideDeviation}{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 \code{\LinkA{DownsideDeviation}{DownsideDeviation}} as the denominator in \code{\LinkA{UpsidePotentialRatio}{UpsidePotentialRatio}}. \Cite{Favre and Galeano(2002)} propose utilizing the ratio of expected excess return over the Cornish-Fisher \code{\LinkA{modifiedVaR}{modifiedVaR}} to produce \code{\LinkA{SharpeRatio.modified}{SharpeRatio.modified}}. \code{\LinkA{TreynorRatio}{TreynorRatio}} is also similar to the Sharpe Ratio, except it uses \code{\LinkA{CAPM.beta}{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 \code{\LinkA{Omega}{Omega}}.  Omega analytically constructs a cumulative distribution function, in a manner similar to \code{\LinkA{chart.QQPlot}{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 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 \code{\LinkA{tsbootstrap}{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 \code{\LinkA{chart.Boxplot}{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.
\end{Section}
\begin{Section}{Value at Risk - VaR}
\emph{Traditional mean-VaR}:
In the early 90's, academic literature started referring to \dQuote{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 distribution and the probability quantile of the distribution calculated using \code{\LinkA{qnorm}{qnorm}}. The negative return at the correct quantile (usually 95\% or 99\%), is the non-parametric VaR estimate.  J.P. Morgan's RiskMetrics parametric mean-VaR was published in 1994 and this methodology for estimating parametric mean-VaR has become what people are generally referring to as \dQuote{VaR} and what we have implemented as \code{\LinkA{VaR.traditional}{VaR.traditional}}.  See \Cite{Return to RiskMetrics: Evolution of a Standard}\url{http://www.riskmetrics.com/r2rovv.html}, \code{fPortfolio} has also implemented traditional mean-VaR as the \code{\LinkA{VaR}{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 \R{} package \code{VaR} contains methods for simulating and estimating lognormal \code{\LinkA{VaR.norm}{VaR.norm}} and generalized Pareto \code{\LinkA{VaR.gpd}{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 \code{\LinkA{VaR.backtest}{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.

\emph{Conditional VaR and Beyond VaR}:
The \code{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 \code{\LinkA{CVaR}{CVaR}} and \code{\LinkA{CVaRplus}{CVaRplus}}.  Expected Shortfall attempts to measure the magnitude of the average loss exceeding the traditional mean-VaR. Expected Shortfall has proven to be a reasonable risk predictor for many asset classes.  See \Cite{Uryasev(2000)} and \Cite{Sherer and Martin(2005)} for more information on Conditional Value at Risk.  A similar measure called Beyond VaR implemented here as \code{\LinkA{VaR.Beyond}{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 \code{\LinkA{CVaRplus}{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.

\emph{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. \Cite{Huisman(1999)} and \Cite{Favre and Galleano(2002)} propose to overcome this extensively documented failing of traditional VaR by directly incorporating the higher moments of the return distribution into the VaR calculation.  This new VaR measure incorporates 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 \dQuote{Cornish-Fisher VaR} or \dQuote{Modified VaR}.  We provide this measure as function \code{\LinkA{VaR.CornishFisher}{VaR.CornishFisher}} with equivalent alias \code{\LinkA{modifiedVaR}{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 finance 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.

\emph{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 \code{\LinkA{VaR.Marginal}{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 \Cite{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 \emph{not} subadditive.  \Cite{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 \Cite{Bali and Gokcan(2004)} who conclude that \dQuote{the VaR estimations based on the generalized Pareto distribution and the Cornish-Fisher approximation perform best}.
\end{Section}
\begin{Section}{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 \code{\LinkA{checkData}{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.  \code{\LinkA{checkData}{checkData}} may also save you time and trouble in your own code and functions outside of the functionality provided by the \code{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 function \code{\LinkA{CalculateReturns}{CalculateReturns}} to address this by taking a stream of prices and calculating simple or compounded returns from the price vector. The excellent \code{tseries} library includes the function \code{\LinkA{get.hist.quote}{get.hist.quote}} for retrieving market data from online sources.  Many of the functions in PerformanceAnalytics require either a benchmark or a risk free rate, and many practitioners 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 S\&P 500 returns in the \code{\LinkA{download.SP500PriceReturns}{download.SP500PriceReturns}} and the 13-day US Treasury Bill in \code{\LinkA{download.RiskFree}{download.RiskFree}}.

We also provide wrappers for cumulative maxima of the returns in a multicolumn series in \code{\LinkA{cummax.column}{cummax.column}} and for the cumulative product (compound return) in \code{\LinkA{cumprod.column}{cumprod.column}}.   \R's built-in \code{\LinkA{apply}{apply}} function in enormously powerful, but is can be tricky to use with timeseries data, so we have provided wrapper functions to \code{\LinkA{apply.fromstart}{apply.fromstart}} and \code{\LinkA{apply.rolling}{apply.rolling}} to make handling of \dQuote{from inception} and \dQuote{rolling window} calculations easier.
\end{Section}
\begin{Section}{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 multivariate 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.
\end{Section}
\begin{Section}{Acknowledgments}
Data series \code{\LinkA{edhec}{edhec}} used in \code{PerformanceAnalytics} and related publications with the kind permission of the EDHEC Risk and Asset Management Research Center. \\
\url{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 functions.

Thanks to the R-SIG-Finance community without whom this library would not be possible.
\end{Section}
\begin{Author}
Brian G. Peterson \\
Peter Carl \\
Maintainer:  \email{brian@braverock.com}
\end{Author}

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

CRAN task view on Empirical Finance \\ \url{http://cran.r-project.org/src/contrib/Views/Econometrics.html}

Grant Farnsworth's Econometrics in R \\ \url{http://cran.r-project.org/doc/contrib/Farnsworth-EconometricsInR.pdf}

Collection of R charts and graphs \\ \url{http://addictedtor.free.fr/graphiques/}



\begin{Schunk}
\begin{Sinput}
> data(managers)
> head(managers)
\end{Sinput}
\begin{Soutput}
            HAM1 HAM2    HAM3    HAM4 HAM5 HAM6 EDHEC.LS.EQ SP500.TR US.10Y.TR
Jan 1996  0.0100   NA  0.0359  0.0208   NA   NA          NA   0.0340   0.00380
Feb 1996  0.0215   NA  0.0295  0.0231   NA   NA          NA   0.0093  -0.03532
Mar 1996  0.0226   NA  0.0253 -0.0053   NA   NA          NA   0.0096  -0.01057
Apr 1996  0.0008   NA  0.0478  0.0200   NA   NA          NA   0.0147  -0.01739
May 1996  0.0158   NA  0.0337  0.0122   NA   NA          NA   0.0258  -0.00543
Jun 1996 -0.0086   NA -0.0293 -0.0089   NA   NA          NA   0.0038   0.01507
         US.3m.TR
Jan 1996  0.00456
Feb 1996  0.00398
Mar 1996  0.00371
Apr 1996  0.00428
May 1996  0.00443
Jun 1996  0.00412
\end{Soutput}
\begin{Sinput}
> data(edhec)
> head(edhec)
\end{Sinput}
\begin{Soutput}
         Convertible.Arbitrage CTA.Global Distressed.Securities
Jan 1997                0.0119     0.0393                0.0178
Feb 1997                0.0123     0.0298                0.0122
Mar 1997                0.0078    -0.0021               -0.0012
Apr 1997                0.0086    -0.0170                0.0030
May 1997                0.0156    -0.0015                0.0233
Jun 1997                0.0212     0.0085                0.0217
         Emerging.Markets Equity.Market.Neutral Event.Driven
Jan 1997           0.0791                0.0189       0.0213
Feb 1997           0.0525                0.0101       0.0084
Mar 1997          -0.0120                0.0016      -0.0023
Apr 1997           0.0119                0.0119      -0.0005
May 1997           0.0315                0.0189       0.0346
Jun 1997           0.0581                0.0165       0.0258
         Fixed.Income.Arbitrage Global.Macro Long.Short.Equity Merger.Arbitrage
Jan 1997                 0.0191       0.0573            0.0281           0.0150
Feb 1997                 0.0122       0.0175           -0.0006           0.0034
Mar 1997                 0.0109      -0.0119           -0.0084           0.0060
Apr 1997                 0.0130       0.0172            0.0084          -0.0001
May 1997                 0.0118       0.0108            0.0394           0.0197
Jun 1997                 0.0108       0.0218            0.0223           0.0231
         Relative.Value Short.Selling Funds.of.Funds
Jan 1997         0.0180       -0.0166         0.0317
Feb 1997         0.0118        0.0426         0.0106
Mar 1997         0.0010        0.0778        -0.0077
Apr 1997         0.0122       -0.0129         0.0009
May 1997         0.0173       -0.0737         0.0275
Jun 1997         0.0198       -0.0065         0.0225
\end{Soutput}
\end{Schunk}

\HeaderA{ActivePremium}{Active Premium}{ActivePremium}
\keyword{ts}{ActivePremium}
\keyword{multivariate}{ActivePremium}
\keyword{distribution}{ActivePremium}
\keyword{models}{ActivePremium}
\begin{Description}\relax
The return on an investment's annualized return minus the benchmark's annualized return.

Active Premium = Investment's annualized return - Benchmark's annualized return
\end{Description}
\begin{Usage}
\begin{verbatim}
ActivePremium(Ra, Rb, scale = 12)
\end{verbatim}
\end{Usage}
\begin{References}\relax
Sharpe, W.F. The Sharpe Ratio,\emph{Journal of Portfolio Management},Fall 1994, 49-58.
\end{References}

\code{\LinkA{InformationRatio}{InformationRatio}}
\code{\LinkA{TrackingError}{TrackingError}}
\code{\LinkA{Return.annualized}{Return.annualized}}

\begin{Examples}
\begin{Schunk}
\begin{Sinput}
> edhec.length = dim(edhec)[1]
> start = rownames(edhec[1, ])
> start
\end{Sinput}
\begin{Soutput}
[1] "1997-01-31"
\end{Soutput}
\begin{Sinput}
> end = rownames(edhec[edhec.length, ])
> edhec.zoo = zoo(edhec, order.by = rownames(edhec))
> sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", 
+     end = end)
\end{Sinput}
\begin{Soutput}
time series ends   2006-12-01
\end{Soutput}
\begin{Sinput}
> 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])
\end{Sinput}
\begin{Soutput}
[1] 0.06384714
\end{Soutput}
\end{Schunk}
\end{Examples}

\HeaderA{BetaCoKurtosis}{systematic kurtosis of an asset to the initial portfolio}{BetaCoKurtosis}
\begin{Description}\relax
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.
\end{Description}
\begin{Details}\relax
\deqn{K_{a,b}=\frac{CoK_{a,b}}{S_{a}}=\frac{\sum((R_{a}-\bar{R_{a}})(R_{b}-\bar{R_{b}})^{3})}{\sum(R_{a}-\bar{R_{a}})^{4}}{BCoK(Ra,Rb)=CoK(Ra,Rb)/kurtosis(Ra)}}{}
\end{Details}
\begin{References}\relax
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
\end{References}

\code{\LinkA{CoKurtosis}{CoKurtosis}}
\code{\LinkA{kurtosis}{kurtosis}}

\HeaderA{BetaCoSkewness}{systematic skewness of an asset to an initial portfolio}{BetaCoSkewness}
\begin{Description}\relax
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.
\end{Description}
\begin{Details}\relax
\deqn{S_{a,b}=\frac{CoS_{a,b}}{S_{a}}=\frac{\sum((R_{a}-\bar{R_{a}})(R_{b}-\bar{R_{b}})^{2})}{\sum(R_{a}-\bar{R_{a}})^{3}}}{BCoS=CoS(Ra,Rb)/skew(Ra)}
\end{Details}
\begin{References}\relax
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
\end{References}

\code{\LinkA{CoSkewness}{CoSkewness}}
\code{\LinkA{skewness}{skewness}}

\begin{Examples}
\end{Examples}

\HeaderA{BetaCoVariance}{systematic beta of an asset to an initial portfolio}{BetaCoVariance}
\begin{Description}\relax
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 \code{\LinkA{CAPM.beta}{CAPM.beta}}
\end{Description}
\begin{Details}\relax
Systematic Beta \eqn{\beta_{a,b}}{BCoV(a,b)}

\eqn{\beta_{a,b}=\frac{CoV_{a,b}}{\sigma_{a}}=\frac{\sum((R_{a}-\bar{R_{a}})(R_{b}-\bar{R_{b}}))}{\sum(R_{a}-\bar{R_{a}})^{2}}}{BetaCoV=cov(a,b)/var(b)}

Ruppert(2004) reports that this equation will give the estimated slope of the linear regression of \eqn{R_{a}}{Ra}on \eqn{R_{b}}{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)
\end{Details}
\begin{References}\relax
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. \emph{Statistics and Finance, an Introduction}. Springer. 2004.
\end{References}

\code{\LinkA{CAPM.beta}{CAPM.beta}}


\HeaderA{CAPM.alpha}{calculate CAPM alpha}{CAPM.alpha}
\begin{Description}\relax
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.
\end{Description}
\begin{References}\relax
Sharpe, W.F. Capital Asset Prices: A theory of market equilibrium under conditions of risk. \emph{Journal of finance}, vol 19, 1964, 425-442. \\
Ruppert, David. \emph{Statistics and Finance, an Introduction}. Springer. 2004. \\
\end{References}

\code{\LinkA{CAPM.beta}{CAPM.beta}}
\code{\LinkA{CAPM.utils}{CAPM.utils}}

\begin{Examples}
\begin{Schunk}
\begin{Sinput}
> edhec.length = dim(edhec)[1]
> start = rownames(edhec[1, ])
> start
\end{Sinput}
\begin{Soutput}
[1] "1997-01-31"
\end{Soutput}
\begin{Sinput}
> end = rownames(edhec[edhec.length, ])
> edhec.zoo = zoo(edhec, order.by = rownames(edhec))
> rf.zoo = download.RiskFree(start = start, end = end)
\end{Sinput}
\begin{Soutput}
time series ends   2006-12-01
\end{Soutput}
\begin{Sinput}
> sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", 
+     end = end)
\end{Sinput}
\begin{Soutput}
time series ends   2006-12-01
\end{Soutput}
\begin{Sinput}
> 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)
\end{Sinput}
\begin{Soutput}
[1] 0.005772605
\end{Soutput}
\end{Schunk}
\end{Examples}

\HeaderA{CAPM.beta}{calculate CAPM beta}{CAPM.beta}
\begin{Description}\relax
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 \code{\LinkA{BetaCoVariance}{BetaCoVariance}}
\end{Description}
\begin{Details}\relax
\deqn{\beta_{a,b}=\frac{CoV_{a,b}}{\sigma_{a}}=\frac{\sum((R_{a}-\bar{R_{a}})(R_{b}-\bar{R_{b}}))}{\sum(R_{a}-\bar{R_{a}})^{2}}}{cov(Ra,Rb)/var(Ra)}

Ruppert(2004) reports that this equation will give the estimated slope of the linear regression of \eqn{R_{a}}{Ra} on \eqn{R_{b}}{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)
\end{Details}
\begin{References}\relax
Sharpe, W.F. Capital Asset Prices: A theory of market equilibrium under conditions of risk. \emph{Journal of finance}, vol 19, 1964, 425-442. \\
Ruppert, David. \emph{Statistics and Finance, an Introduction}. Springer. 2004. \\
\end{References}

\code{\LinkA{BetaCoVariance}{BetaCoVariance}}
\code{\LinkA{CAPM.alpha}{CAPM.alpha}}
\code{\LinkA{CAPM.utils}{CAPM.utils}}

\begin{Examples}
\begin{Schunk}
\begin{Sinput}
> edhec.length = dim(edhec)[1]
> start = rownames(edhec[1, ])
> start
\end{Sinput}
\begin{Soutput}
[1] "1997-01-31"
\end{Soutput}
\begin{Sinput}
> end = rownames(edhec[edhec.length, ])
> edhec.zoo = zoo(edhec, order.by = rownames(edhec))
> rf.zoo = download.RiskFree(start = start, end = end)
\end{Sinput}
\begin{Soutput}
time series ends   2006-12-01
\end{Soutput}
\begin{Sinput}
> sp500.zoo = download.SP500PriceReturns(start = "1996-12-31", 
+     end = end)
\end{Sinput}
\begin{Soutput}
time series ends   2006-12-01
\end{Soutput}
\begin{Sinput}
> 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.beta(data.zoo[, 1, drop = FALSE], data.zoo[, 2, drop = FALSE], 
+     rf = rf.zoo)
\end{Sinput}
\begin{Soutput}
[1] 0.3328777
\end{Soutput}
\end{Schunk}
\end{Examples}

\HeaderA{CAPM.utils}{utility functions for CAPM CML, SML, and RiskPremium}{CAPM.utils}
\begin{Description}\relax
The Capital Asset Pricing Model, from which the popular \code{\LinkA{SharpeRatio}{SharpeRatio}} is derived, is a theory of market equilibrium.
These utility functions provide values for various measures proposed in the CAPM.
\end{Description}
\begin{Details}\relax
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 \code{\LinkA{CAPM.beta}{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.

\code{CAPM.RiskPremium} is the premium returned to the investor over the risk free asset

\deqn{\overline{(R_{a}-R_{f})}}{mean(Ra-rf)}

\code{CAPM.CML} calculates the expected return of the asset against the benchmark Capital Market Line

\code{CAPM.CML.slope} calculates the slope of the Capital Market Line for looking at how a particular asset compares to the CML

\code{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
\end{Details}
\begin{References}\relax
Sharpe, W.F. The Sharpe Ratio,\emph{Journal of Portfolio Management},Fall 1994, 49-58. \\
Sharpe, W.F. Capital Asset Prices: A theory of market equilibrium under conditions of risk. \emph{Journal of finance}, vol 19, 1964, 425-442. \\
Ruppert, David. \emph{Statistics and Finance, an Introduction}. Springer. 2004. \\
\end{References}

\code{\LinkA{CAPM.beta}{CAPM.beta}}
\code{\LinkA{CAPM.alpha}{CAPM.alpha}}
\code{\LinkA{SharpeRatio}{SharpeRatio}}
\code{\LinkA{InformationRatio}{InformationRatio}}
\code{\LinkA{TrackingError}{TrackingError}}
\code{\LinkA{ActivePremium}{ActivePremium}}

\begin{Examples}
\begin{Schunk}
\begin{Sinput}
> edhec.length = dim(edhec)[1]
> start = rownames(edhec[1, ])
> start
\end{Sinput}
\begin{Soutput}
[1] "1997-01-31"
\end{Soutput}
\begin{Sinput}
> end = rownames(edhec[edhec.length, ])
> rf = download.RiskFree(start = start, end = end)
\end{Sinput}
\begin{Soutput}
time series ends   2006-12-01
\end{Soutput}
\begin{Sinput}
> Rb = edhec[, "Funds.of.Funds"]
> CAPM.CML.slope(Rb, rf)