[Returnanalytics-commits] r3550 - pkg/FactorAnalytics/sandbox/R
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Sat Nov 15 00:22:06 CET 2014
Author: gyollin
Date: 2014-11-15 00:22:05 +0100 (Sat, 15 Nov 2014)
New Revision: 3550
Removed:
pkg/FactorAnalytics/sandbox/R/FactorAnalytics-package.R
pkg/FactorAnalytics/sandbox/R/bootstrapFactorESdecomposition.r
pkg/FactorAnalytics/sandbox/R/bootstrapFactorVaRdecomposition.r
pkg/FactorAnalytics/sandbox/R/chart.RollingStyle.R
pkg/FactorAnalytics/sandbox/R/chart.Style.R
pkg/FactorAnalytics/sandbox/R/covEWMA.R
pkg/FactorAnalytics/sandbox/R/factorModelFactorRiskDecomposition.r
pkg/FactorAnalytics/sandbox/R/factorModelGroupRiskDecomposition.r
pkg/FactorAnalytics/sandbox/R/factorModelPortfolioRiskDecomposition.r
pkg/FactorAnalytics/sandbox/R/factorModelRiskAttribution.r
pkg/FactorAnalytics/sandbox/R/factorModelRiskDecomposition.r
pkg/FactorAnalytics/sandbox/R/factorModelSimulation.r
pkg/FactorAnalytics/sandbox/R/impliedFactorReturns.R
pkg/FactorAnalytics/sandbox/R/modifiedEsReport.R
pkg/FactorAnalytics/sandbox/R/modifiedIncrementalES.R
pkg/FactorAnalytics/sandbox/R/modifiedIncrementalVaR.R
pkg/FactorAnalytics/sandbox/R/modifiedPortfolioEsDecomposition.R
pkg/FactorAnalytics/sandbox/R/modifiedPortfolioVaRDecomposition.R
pkg/FactorAnalytics/sandbox/R/modifiedVaRReport.R
pkg/FactorAnalytics/sandbox/R/nonparametricEsReport.R
pkg/FactorAnalytics/sandbox/R/nonparametricIncrementalES.R
pkg/FactorAnalytics/sandbox/R/nonparametricIncrementalVaR.R
pkg/FactorAnalytics/sandbox/R/nonparametricPortfolioEsDecomposition.R
pkg/FactorAnalytics/sandbox/R/nonparametricPortfolioVaRDecomposition.R
pkg/FactorAnalytics/sandbox/R/nonparametricVaRReport.R
pkg/FactorAnalytics/sandbox/R/normalEsReport.R
pkg/FactorAnalytics/sandbox/R/normalIncrementalES.R
pkg/FactorAnalytics/sandbox/R/normalIncrementalVaR.R
pkg/FactorAnalytics/sandbox/R/normalPortfolioEsDecomposition.R
pkg/FactorAnalytics/sandbox/R/normalPortfolioVaRDecomposition.R
pkg/FactorAnalytics/sandbox/R/normalVaRReport.R
pkg/FactorAnalytics/sandbox/R/portfolioSdDecomposition.R
pkg/FactorAnalytics/sandbox/R/scenarioPredictions.r
pkg/FactorAnalytics/sandbox/R/scenarioPredictionsPortfolio.r
pkg/FactorAnalytics/sandbox/R/style.QPfit.R
pkg/FactorAnalytics/sandbox/R/style.fit.R
pkg/FactorAnalytics/sandbox/R/table.RollingStyle.R
Log:
Cleaning up unused file
Deleted: pkg/FactorAnalytics/sandbox/R/FactorAnalytics-package.R
===================================================================
--- pkg/FactorAnalytics/sandbox/R/FactorAnalytics-package.R 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/FactorAnalytics-package.R 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,132 +0,0 @@
-
-
-#' Functions for Cornish-Fisher density, CDF, random number simulation and
-#' quantile.
-#'
-#' \code{dCornishFisher} Computes Cornish-Fisher density from two term
-#' Edgeworth expansion given mean, standard deviation, skewness and excess
-#' kurtosis. \code{pCornishFisher} Computes Cornish-Fisher CDF from two term
-#' Edgeworth expansion given mean, standard deviation, skewness and excess
-#' kurtosis. \code{qCornishFisher} Computes Cornish-Fisher quantiles from two
-#' term Edgeworth expansion given mean, standard deviation, skewness and excess
-#' kurtosis. \code{rCornishFisher} simulate observations based on
-#' Cornish-Fisher quantile expansion given mean, standard deviation, skewness
-#' and excess kurtosis.
-#'
-#' CDF(q) = Pr(sqrt(n)*(x_bar-mu)/sigma < q)
-#'
-#' @aliases rCornishFisher dCornishFisher pCornishFisher qCornishFisher
-#' @param n scalar, number of simulated values in rCornishFisher. Sample length
-#' in density,distribution,quantile function.
-#' @param sigma scalar, standard deviation.
-#' @param skew scalar, skewness.
-#' @param ekurt scalar, excess kurtosis.
-#' @param seed set seed here. Default is \code{NULL}.
-#' @param x,q vector of standardized quantiles. See detail.
-#' @param p vector of probabilities.
-#' @return n simulated values from Cornish-Fisher distribution.
-#' @author Eric Zivot and Yi-An Chen.
-#' @references A.DasGupta, "Asymptotic Theory of Statistics and Probability",
-#' Springer Science+Business Media,LLC 2008 Thomas A.Severini, "Likelihood
-#' Methods in Statistics", Oxford University Press, 2000
-#' @examples
-#'
-#' # generate 1000 observation from Cornish-Fisher distribution
-#' rc <- rCornishFisher(1000,1,0,5)
-#' hist(rc,breaks=100,freq=FALSE,main="simulation of Cornish Fisher Distribution",
-#' xlim=c(-10,10))
-#' lines(seq(-10,10,0.1),dnorm(seq(-10,10,0.1),mean=0,sd=1),col=2)
-#' # compare with standard normal curve
-#'
-#' # example from A.dasGupta p.188 exponential example
-#' # x is iid exp(1) distribution, sample size = 5
-#' # then x_bar is Gamma(shape=5,scale=1/5) distribution
-#' q <- c(0,0.4,1,2)
-#' # exact cdf
-#' pgamma(q/sqrt(5)+1,shape=5,scale=1/5)
-#' # use CLT
-#' pnorm(q)
-#' # use edgeworth expansion
-#' pCornishFisher(q,n=5,skew=2,ekurt=6)
-#'
-#' @name CornishFisher
-NULL
-
-
-
-
-
-#' Hypothetical Alternative Asset Manager and Benchmark Data
-#'
-#' a data.frame format from managers dataset from package PerformanceAnalytics,
-#' containing 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. Monthly returns for all series end in December 2006 and
-#' begin at different periods starting from January 1997.
-#'
-#'
-#' @name managers.df
-#' @docType data
-#' @keywords datasets
-#' @examples
-#'
-#' data(managers.df)
-#' ## maybe str(managers.df) ; plot(managers.df) ...
-#'
-NULL
-
-
-
-
-
-#' Monthly Stock Return Data || Portfolio of Weekly Stock Returns
-#'
-#' sfm.dat: This is a monthly "data.frame" object from January 1978 to December
-#' 1987, with seventeen columns representing monthly returns of certain assets,
-#' as in Chapter 2 of Berndt (1991). sfm.apca.dat: This is a weekly
-#' "data.frame" object with dimension 182 x 1618, which runs from January 8,
-#' 1997 to June 28, 2000 and represents the stock returns on 1618 U.S. stocks.
-#'
-#' CITCRP monthly returns of Citicorp. CONED monthly returns of Consolidated
-#' Edison. CONTIL monthly returns of Continental Illinois. DATGEN monthly
-#' returns of Data General. DEC monthly returns of Digital Equipment Company.
-#' DELTA monthly returns of Delta Airlines. GENMIL monthly returns of General
-#' Mills. GERBER monthly returns of Gerber. IBM monthly returns of
-#' International Business Machines. MARKET a value-weighted composite monthly
-#' returns based on transactions from the New York Stock Exchange and the
-#' American Exchange. MOBIL monthly returns of Mobile. PANAM monthly returns
-#' of Pan American Airways. PSNH monthly returns of Public Service of New
-#' Hampshire. TANDY monthly returns of Tandy. TEXACO monthly returns of
-#' Texaco. WEYER monthly returns of Weyerhauser. RKFREE monthly returns on
-#' 30-day U.S. Treasury bills.
-#'
-#' @name stat.fm.data
-#' @aliases sfm.dat sfm.apca.dat
-#' @docType data
-#' @references Berndt, E. R. (1991). The Practice of Econometrics: Classic and
-#' Contemporary. Addison-Wesley Publishing Co.
-#' @source S+FinMetrics Berndt.dat & folio.dat
-#' @keywords datasets
-NULL
-
-
-
-
-
-#' constructed NYSE 447 assets from 1996-01-01 through 2003-12-31.
-#'
-#' constructed NYSE 447 assets from 1996-01-01 through 2003-12-31.
-#'
-#' Continuous data: PRICE, RETURN, VOLUME, SHARES.OUT, MARKET.EQUITY,LTDEBT,
-#' NET.SALES, COMMON.EQUITY, NET.INCOME, STOCKHOLDERS.EQUITY, LOG.MARKETCAP,
-#' LOG.PRICE, BOOK2MARKET Categorical data: GICS, GICS.INDUSTRY, GICS.SECTOR
-#' Identi
cation data: DATE, PERMNO, TICKER.x
-#'
-#' @name stock
-#' @docType data
-#' @references Guy Yullen and Yi-An Chen
-#' @keywords datasets
-NULL
-
-
-
Deleted: pkg/FactorAnalytics/sandbox/R/bootstrapFactorESdecomposition.r
===================================================================
--- pkg/FactorAnalytics/sandbox/R/bootstrapFactorESdecomposition.r 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/bootstrapFactorESdecomposition.r 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,83 +0,0 @@
-bootstrapFactorESdecomposition <- function(bootData, beta.vec, sig2.e, tail.prob = 0.01,
- method=c("average"),
- VaR.method=c("HS", "CornishFisher")) {
-## Compute factor model ES decomposition based on Euler's theorem given bootstrap data
-## and factor model parameters.
-## The partial derivative of ES wrt factor beta is computed
-## as the expected factor return given fund return is less than or equal to portfolio VaR
-## VaR is compute either as the sample quantile or as an estimated quantile
-## using the Cornish-Fisher expansion
-## inputs:
-## bootData B x (k+2) matrix of bootstrap data. First column contains the fund returns,
-## second through k+1 columns contain factor returns, k+2 column contain residuals
-## scaled to have variance 1.
-## beta.vec k x 1 vector of factor betas
-## sig2.e scalar, residual variance from factor model
-## tail.prob scalar tail probability
-## method character, method for computing marginal ES. Valid choices are
-## "average" for approximating E[Fj | R<=VaR]
-## VaR.method character, method for computing VaR. Valid choices are "HS" for
-## historical simulation (empirical quantile); "CornishFisher" for
-## modified VaR based on Cornish-Fisher quantile estimate. Cornish-Fisher
-## computation is done with the VaR.CornishFisher in the PerformanceAnalytics
-## package
-## output:
-## Output:
-## A list with the following components:
-## ES.fm scalar, bootstrap ES value for fund reported as a positive number
-## mcES.fm k+1 x 1 vector of factor marginal contributions to ES
-## cES.fm k+1 x 1 vector of factor component contributions to ES
-## pcES.fm k+1 x 1 vector of factor percent contributions to ES
-## Remarks:
-## The factor model has the form
-## R(t) = beta'F(t) + e(t) = beta.star'F.star(t)
-## where beta.star = (beta, sig.e)' and F.star(t) = (F(t)', z(t))'
-## By Euler's theorem
-## ES.fm = sum(cES.fm) = sum(beta.star*mcES.fm)
-## References:
-## 1. Hallerback (2003), "Decomposing Portfolio Value-at-Risk: A General Analysis",
-## The Journal of Risk 5/2.
-## 2. Yamai and Yoshiba (2002). "Comparative Analyses of Expected Shortfall and
-## Value-at-Risk: Their Estimation Error, Decomposition, and Optimization
-## Bank of Japan.
-## 3. Meucci (2007). "Risk Contributions from Generic User-Defined Factors," Risk.
- require(PerformanceAnalytics)
- VaR.method = VaR.method[1]
- bootData = as.matrix(bootData)
- ncol.bootData = ncol(bootData)
- beta.names = c(names(beta.vec), "residual")
- #beta.vec = as.vector(beta.vec)
- beta.star.vec = c(beta.vec, sqrt(sig2.e))
- names(beta.star.vec) = beta.names
-
- if (VaR.method == "HS") {
- VaR.fm = quantile(bootData[, 1], prob=tail.prob)
- idx = which(bootData[, 1] <= VaR.fm)
- ES.fm = -mean(bootData[idx, 1])
- } else {
- VaR.fm = -VaR.CornishFisher(bootData[, 1], p=(1-tail.prob))
- idx = which(bootData[, 1] <= pVaR)
- ES.fm = -mean(bootData[idx, 1])
- }
- ##
- ## compute marginal contribution to ES
- ##
- if (method == "average") {
- ## compute marginal ES as expected value of factor return given fund
- ## return is less than or equal to VaR
- mcES.fm = -as.matrix(colMeans(bootData[idx, -1]))
- } else {
- stop("invalid method")
- }
-
-## compute correction factor so that sum of weighted marginal ES adds to portfolio ES
-#cf = as.numeric( ES.fm / sum(mcES.fm*beta.star.vec) )
-#mcES.fm = cf*mcES.fm
-cES.fm = mcES.fm*beta.star.vec
-pcES.fm = cES.fm/ES.fm
-ans = list(ES.fm = ES.fm,
- mcES.fm = mcES.fm,
- cES.fm = cES.fm,
- pcES.fm = pcES.fm)
-return(ans)
-}
Deleted: pkg/FactorAnalytics/sandbox/R/bootstrapFactorVaRdecomposition.r
===================================================================
--- pkg/FactorAnalytics/sandbox/R/bootstrapFactorVaRdecomposition.r 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/bootstrapFactorVaRdecomposition.r 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,90 +0,0 @@
-bootstrapFactorVaRdecomposition <- function(bootData, beta.vec, sig2.e, h=NULL, tail.prob = 0.01,
- method=c("average"),
- VaR.method=c("HS", "CornishFisher")) {
-## Compute factor model VaR decomposition based on Euler's theorem given bootstrap data
-## and factor model parameters.
-## The partial derivative of VaR wrt factor beta is computed
-## as the expected factor return given fund return is equal to portfolio VaR
-## VaR is compute either as the sample quantile or as an estimated quantile
-## using the Cornish-Fisher expansion
-## inputs:
-## bootData B x (k+2) matrix of bootstrap data. First column contains the fund returns,
-## second through k+1 columns contain factor returns, k+2 column contain residuals
-## scaled to have variance 1.
-## beta.vec k x 1 vector of factor betas
-## sig2.e scalar, residual variance from factor model
-## h integer, number of obvs on each side of VaR. Default is h=round(sqrt(B)/2)
-## tail.prob scalar tail probability
-## method character, method for computing marginal VaR. Valid choices are
-## "average" for approximating E[Fj | R=VaR]
-## VaR.method character, method for computing VaR. Valid choices are "HS" for
-## historical simulation (empirical quantile); "CornishFisher" for
-## modified VaR based on Cornish-Fisher quantile estimate. Cornish-Fisher
-## computation is done with the VaR.CornishFisher in the PerformanceAnalytics
-## package
-## output:
-## Output:
-## A list with the following components:
-## VaR.fm scalar, bootstrap VaR value for fund reported as a positive number
-## mcVaR.fm k+1 x 1 vector of factor marginal contributions to VaR
-## cVaR.fm k+1 x 1 vector of factor component contributions to VaR
-## pcVaR.fm k+1 x 1 vector of factor percent contributions to VaR
-## Remarks:
-## The factor model has the form
-## R(t) = beta'F(t) + e(t) = beta.star'F.star(t)
-## where beta.star = (beta, sig.e)' and F.star(t) = (F(t)', z(t))'
-## By Euler's theorem
-## VaR.fm = sum(cVaR.fm) = sum(beta.star*mcVaR.fm)
-## References:
-## 1. Hallerback (2003), "Decomposing Portfolio Value-at-Risk: A General Analysis",
-## The Journal of Risk 5/2.
-## 2. Yamai and Yoshiba (2002). "Comparative Analyses of Expected Shortfall and
-## Value-at-Risk: Their Estimation Error, Decomposition, and Optimization
-## Bank of Japan.
-## 3. Meucci (2007). "Risk Contributions from Generic User-Defined Factors," Risk.
- require(PerformanceAnalytics)
- VaR.method = VaR.method[1]
- bootData = as.matrix(bootData)
- ncol.bootData = ncol(bootData)
- beta.names = c(names(beta.vec), "residual")
- #beta.vec = as.vector(beta.vec)
- beta.star.vec = c(beta.vec, sqrt(sig2.e))
- names(beta.star.vec) = beta.names
-
- # determine number of obvs to average around VaR
- if (is.null(h)) {
- h = round(sqrt(nrow(bootData)))
- } else h = round(h)
-
- if (VaR.method == "HS") {
- VaR.fm = -quantile(bootData[,1], prob=tail.prob)
- } else {
- VaR.fm = VaR.CornishFisher(bootData[,1], p=(1-tail.prob))
- }
- ##
- ## compute marginal contribution to VaR
- ##
- if (method == "average") {
- ## compute marginal VaR as expected value of fund return given portfolio
- ## return is equal to portfolio VaR
- r.sort = sort(bootData[,1])
- idx.lower = which(r.sort <= -VaR.fm)
- idx.upper = which(r.sort > -VaR.fm)
- r.vals = c(r.sort[tail(idx.lower,n=h)], r.sort[head(idx.upper,n=h)])
- idx = which(bootData[,1] %in% r.vals)
- mcVaR.fm = -as.matrix(colMeans(bootData[idx,-1]))
- } else {
- stop("invalid method")
- }
-
-## compute correction factor so that sum of weighted marginal VaR adds to portfolio VaR
-cf = as.numeric( VaR.fm / sum(mcVaR.fm*beta.star.vec) )
-mcVaR.fm = cf*mcVaR.fm
-cVaR.fm = mcVaR.fm*beta.star.vec
-pcVaR.fm = cVaR.fm/VaR.fm
-ans = list(VaR.fm = VaR.fm,
- mcVaR.fm = mcVaR.fm,
- cVaR.fm = cVaR.fm,
- pcVaR.fm = pcVaR.fm)
-return(ans)
-}
Deleted: pkg/FactorAnalytics/sandbox/R/chart.RollingStyle.R
===================================================================
--- pkg/FactorAnalytics/sandbox/R/chart.RollingStyle.R 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/chart.RollingStyle.R 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,52 +0,0 @@
-chart.RollingStyle <-
-function (R.fund, R.style, method = c("constrained","unconstrained","normalized"), leverage = FALSE, width = 12, main = NULL, space = 0, ...)
-{ # @author Peter Carl
-
- result<-table.RollingStyle(R.fund=R.fund, R.style=R.style, method=method,leverage=leverage,width=width)
-
- if (is.null(main)){
- freq = periodicity(R.fund)
-
- switch(freq$scale,
- minute = {freq.lab = "minute"},
- hourly = {freq.lab = "hour"},
- daily = {freq.lab = "day"},
- weekly = {freq.lab = "week"},
- monthly = {freq.lab = "month"},
- quarterly = {freq.lab = "quarter"},
- yearly = {freq.lab = "year"}
- )
-
- main = paste(colnames(R.fund)[1]," Rolling ", width ,"-",freq.lab," Style Weights", sep="")
- }
-
- chart.StackedBar(result, main = main, space = space, ...)
-
-}
-
-###############################################################################
-# R (http://r-project.org/) Econometrics for Performance and Risk Analysis
-#
-# Copyright (c) 2004-2007 Peter Carl and Brian G. Peterson
-#
-# This library is distributed under the terms of the GNU Public License (GPL)
-# for full details see the file COPYING
-#
-# $Id: chart.RollingStyle.R 1796 2011-01-19 16:18:07Z braverock $
-#
-###############################################################################
-# $Log: not supported by cvs2svn $
-# Revision 1.4 2009-10-15 21:50:19 brian
-# - updates to add automatic periodicity to chart labels, and support different frequency data
-#
-# Revision 1.3 2008-07-11 03:22:01 peter
-# - removed unnecessary function attributes
-#
-# Revision 1.2 2008-04-18 03:59:52 peter
-# - added na.omit to avoid problems with missing data
-#
-# Revision 1.1 2008/02/23 05:55:21 peter
-# - chart demonstrating fund exposures through time
-#
-#
-###############################################################################
Deleted: pkg/FactorAnalytics/sandbox/R/chart.Style.R
===================================================================
--- pkg/FactorAnalytics/sandbox/R/chart.Style.R 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/chart.Style.R 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,195 +0,0 @@
-#' calculate and display effective style weights
-#'
-#' Functions that calculate effective style weights and display the results in
-#' a bar chart. \code{chart.Style} calculates and displays style weights
-#' calculated over a single period. \code{chart.RollingStyle} calculates and
-#' displays those weights in rolling windows through time. \code{style.fit}
-#' manages the calculation of the weights by method. \code{style.QPfit}
-#' calculates the specific constraint case that requires quadratic programming.
-#'
-#' These functions calculate style weights using an asset class style model as
-#' described in detail in Sharpe (1992). The use of quadratic programming to
-#' determine a fund's exposures to the changes in returns of major asset
-#' classes is usually refered to as "style analysis".
-#'
-#' The "unconstrained" method implements a simple factor model for style
-#' analysis, as in: \deqn{Ri = bi1*F1+bi2*F2+...+bin*Fn+ei}{R_i =
-#' b_{i1}F_1+b_{i2}F_2+\dots+b_{in}F_n +e_i} where \eqn{Ri}{R_i} represents the
-#' return on asset i, \eqn{Fj}{F_j} represents each factor, and \eqn{ei}{e_i}
-#' represents the "non-factor" component of the return on i. This is simply a
-#' multiple regression analysis with fund returns as the dependent variable and
-#' asset class returns as the independent variables. The resulting slope
-#' coefficients are then interpreted as the fund's historic exposures to asset
-#' class returns. In this case, coefficients do not sum to 1.
-#'
-#' The "normalized" method reports the results of a multiple regression
-#' analysis similar to the first, but with one constraint: the coefficients are
-#' required to add to 1. Coefficients may be negative, indicating short
-#' exposures. To enforce the constraint, coefficients are normalized.
-#'
-#' The "constrained" method includes the constraint that the coefficients sum
-#' to 1, but adds that the coefficients must lie between 0 and 1. These
-#' inequality constraints require a quadratic programming algorithm using
-#' \code{\link[quadprog]{solve.QP}} from the 'quadprog' package, and the
-#' implementation is discussed under \code{\link{style.QPfit}}. If set to
-#' TRUE, "leverage" allows the sum of the coefficients to exceed 1.
-#'
-#' According to Sharpe (1992), the calculation for the constrained case is
-#' represented as: \deqn{min var(Rf - sum[wi * R.si]) = min var(F - w*S)}{min
-#' \sigma(R_f - \sum{w_i * R_s_i}) = min \sigma(F - w*S)} \deqn{s.t. sum[wi] =
-#' 1; wi > 0}{ s.t. \sum{w_i} = 1; w_i > 0}
-#'
-#' Remembering that:
-#'
-#' \deqn{\sigma(aX + bY) = a^2 \sigma(X) + b^2 \sigma(Y) + 2ab cov(X,Y) =
-#' \sigma(R.f) + w'*V*w - 2*w'*cov(R.f,R.s)}
-#'
-#' we can drop \eqn{var(Rf)}{\sigma(R_f)} as it isn't a function of weights,
-#' multiply both sides by 1/2:
-#'
-#' \deqn{= min (1/2) w'*V*w - C'w}{= min (1/2) w'*V*w - C'w} \deqn{ s.t. w'*e =
-#' 1, w_i > 0}{ s.t. w'*e = 1, w_i > 0}
-#'
-#' Which allows us to use \code{\link[quadprog]{solve.QP}}, which is specified
-#' as: \deqn{min(-d' b + 1/2 b' D b)}{min(-d' b + 1/2 b' D b)} and the
-#' constraints \deqn{ A' b >= b.0 }{ A' b >= b_0 }
-#'
-#' so: b is the weight vector, D is the variance-covariance matrix of the
-#' styles d is the covariance vector between the fund and the styles
-#'
-#' The chart functions then provide a graphical summary of the results. The
-#' underlying function, \code{\link{style.fit}}, provides the outputs of the
-#' analysis and more information about fit, including an R-squared value.
-#'
-#' Styles identified in this analysis may be interpreted as an average of
-#' potentially changing exposures over the period covered. The function
-#' \code{\link{chart.RollingStyle}} may be useful for examining the behavior of
-#' a manager's average exposures to asset classes over time, using a
-#' rolling-window analysis.
-#'
-#' The chart functions plot a column chart or stacked column chart of the
-#' resulting style weights to the current device. Both \code{style.fit} and
-#' \code{style.QPfit} produce a list of data frames containing 'weights' and
-#' 'R.squared' results. If 'model' = TRUE in \code{style.QPfit}, the full
-#' result set is shown from the output of \code{solve.QP}.
-#'
-#' @aliases chart.Style chart.RollingStyle table.RollingStyle style.fit
-#' style.QPfit
-#' @param R.fund matrix, data frame, or zoo object with fund returns to be
-#' analyzed
-#' @param R.style matrix, data frame, or zoo object with style index returns.
-#' Data object must be of the same length and time-aligned with R.fund
-#' @param method specify the method of calculation of style weights as
-#' "constrained", "unconstrained", or "normalized". For more information, see
-#' \code{\link{style.fit}}
-#' @param leverage logical, defaults to 'FALSE'. If 'TRUE', the calculation of
-#' weights assumes that leverage may be used. For more information, see
-#' \code{\link{style.fit}}
-#' @param model logical. If 'model' = TRUE in \code{\link{style.QPfit}}, the
-#' full result set is shown from the output of \code{solve.QP}.
-#' @param selection either "none" (default) or "AIC". If "AIC", then the
-#' function uses a stepwise regression to identify find the model with minimum
-#' AIC value. See \code{\link{step}} for more detail.
-#' @param unstacked logical. If set to 'TRUE' \emph{and} only one row of data
-#' is submitted in 'w', then the chart creates a normal column chart. If more
-#' than one row is submitted, then this is ignored. See examples below.
-#' @param space the amount of space (as a fraction of the average bar width)
-#' left before each bar, as in \code{\link{barplot}}. Default for
-#' \code{chart.RollingStyle} is 0; for \code{chart.Style} the default is 0.2.
-#' @param main set the chart title, same as in \code{\link{plot}}
-#' @param width number of periods or window to apply rolling style analysis
-#' over
-#' @param ylim set the y-axis limit, same as in \code{\link{plot}}
-#' @param \dots for the charting functions, these are arguments to be passed to
-#' \code{\link{barplot}}. These can include further arguments (such as 'axes',
-#' 'asp' and 'main') and graphical parameters (see 'par') which are passed to
-#' 'plot.window()', 'title()' and 'axis'. For the calculation functions, these
-#' are ignored.
-#' @note None of the functions \code{chart.Style}, \code{style.fit}, and
-#' \code{style.QPfit} make any attempt to align the two input data series. The
-#' \code{chart.RollingStyle}, on the other hand, does merge the two series and
-#' manages the calculation over common periods.
-#' @author Peter Carl
-#' @seealso \code{\link{barplot}}, \code{\link{par}}
-#' @references Sharpe, W. Asset Allocation: Management Style and Performance
-#' Measurement Journal of Portfolio Management, 1992, 7-19. See \url{
-#' http://www.stanford.edu/~wfsharpe/art/sa/sa.htm}
-#' @keywords ts multivariate hplot
-#' @examples
-#'
-#' data(edhec)
-#' data(managers)
-#' style.fit(managers[97:132,2,drop=FALSE],edhec[85:120,], method="constrained", leverage=FALSE)
-#' chart.Style(managers[97:132,2,drop=FALSE],edhec[85:120,], method="constrained", leverage=FALSE, unstack=TRUE, las=3)
-#' chart.RollingStyle(managers[,2,drop=FALSE],edhec[,1:11], method="constrained", leverage=FALSE, width=36, cex.legend = .7, colorset=rainbow12equal, las=1)
-#'
-`chart.Style` <-
-function (R.fund, R.style, method = c("constrained", "unconstrained", "normalized"), leverage = FALSE, main = NULL, ylim = NULL, unstacked=TRUE, ...)
-{ # @author Peter Carl
-
- # DESCRIPTION:
- # A wrapper to create a chart of relative returns through time
-
- # R-Squared could deliver adjusted R-Squared if we wanted
-
- # FUNCTION:
-
- # Transform input data to a data frame
- R.fund = checkData(R.fund)
- R.style = checkData(R.style)
- method = method[1]
-
- # Calculate
- result = style.fit(R.fund, R.style, method = method, leverage = leverage)
- weights = t(as.matrix(result$weights))
-
- if(is.null(main))
- main = paste(colnames(R.fund)[1] ," Style Weights", sep="")
-
- if(is.null(ylim))
- if(method == "constrained" & leverage == FALSE) ylim = c(0,1)
- else ylim = NULL
-
- chart.StackedBar(weights, main = main, ylim = ylim, unstacked = unstacked, ...)
-# barplot(weights, main = main, ylim = ylim, ...)
-
-}
-
-###############################################################################
-# R (http://r-project.org/) Econometrics for Performance and Risk Analysis
-#
-# Copyright (c) 2004-2007 Peter Carl and Brian G. Peterson
-#
-# This library is distributed under the terms of the GNU Public License (GPL)
-# for full details see the file COPYING
-#
-# $Id: chart.Style.R 2351 2013-06-18 09:52:27Z braverock $
-#
-###############################################################################
-# $Log: not supported by cvs2svn $
-# Revision 1.7 2008-07-11 03:24:52 peter
-# - fixed error with alignment of results
-#
-# Revision 1.6 2008-04-18 03:58:04 peter
-# - reduced to a wrapper to chart.StackedBar
-#
-# Revision 1.5 2008/02/27 04:05:32 peter
-# - added 'leverage' tag to eliminate sum to one constraint
-# - added cex.names for controlling size of xaxis labels
-#
-# Revision 1.4 2008/02/26 04:49:06 peter
-# - handles single column fits better
-#
-# Revision 1.3 2008/02/26 04:39:40 peter
-# - moved legend and margin control into chart.StackedBar
-# - handles multiple columns
-#
-# Revision 1.2 2008/02/23 05:35:56 peter
-# - set ylim more sensibly depending on method
-#
-# Revision 1.1 2008/02/23 05:32:37 peter
-# - simple bar chart of a fund's exposures to a set of factors, as determined
-# by style.fit
-#
-#
-###############################################################################
Deleted: pkg/FactorAnalytics/sandbox/R/covEWMA.R
===================================================================
--- pkg/FactorAnalytics/sandbox/R/covEWMA.R 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/covEWMA.R 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,79 +0,0 @@
-#' Compute RiskMetrics-type EWMA Covariance Matrix
-#'
-#' Compute time series of RiskMetrics-type EWMA covariance matrices of returns.
-#' Initial covariance matrix is assumed to be the unconditional covariance
-#' matrix.
-#'
-#' The EWMA covariance matrix at time \code{t} is compute as \cr \code{Sigma(t)
-#' = lambda*Sigma(t-1) + (1-lambda)*R(t)t(R(t))} \cr where \code{R(t)} is the
-#' \code{K x 1} vector of returns at time \code{t}.
-#'
-#' @param factors \code{T x K} data.frame containing asset returns, where
-#' \code{T} is the number of time periods and \code{K} is the number of assets.
-#' @param lambda Scalar exponential decay factor. Must lie between between 0
-#' and 1.
-#' @param return.cor Logical, if TRUE then return EWMA correlation matrices.
-#' @return \code{T x K x K} array giving the time series of EWMA covariance
-#' matrices if \code{return.cor=FALSE} and EWMA correlation matrices if
-#' \code{return.cor=TRUE}.
-#' @author Eric Zivot and Yi-An Chen.
-#' @references Zivot, E. and J. Wang (2006), \emph{Modeling Financial Time
-#' Series with S-PLUS, Second Edition}, Springer-Verlag.
-#' @examples
-#'
-#' # compute time vaying covariance of factors.
-#' data(managers.df)
-#' factors = managers.df[,(7:9)]
-#' cov.f.ewma <- covEWMA(factors)
-#' cov.f.ewma[120,,]
-#'
-covEWMA <-
-function(factors, lambda=0.96, return.cor=FALSE) {
-## Inputs:
-## factors N x K numerical factors data. data is class data.frame
-## N is the time length and K is the number of the factors.
-## lambda scalar. exponetial decay factor between 0 and 1.
-## return.cor Logical, if TRUE then return EWMA correlation matrices
-## Output:
-## cov.f.ewma array. dimension is N x K x K.
-## comments:
-## 1. add optional argument cov.start to specify initial covariance matrix
-## 2. allow data input to be data class to be any rectangular data object
-
-
-if (is.data.frame(factors)){
- factor.names = colnames(factors)
- t.factor = nrow(factors)
- k.factor = ncol(factors)
- factors = as.matrix(factors)
- t.names = rownames(factors)
-} else {
- stop("factor data should be saved in data.frame class.")
-}
-if (lambda>=1 || lambda <= 0){
- stop("exponential decay value lambda should be between 0 and 1.")
-} else {
- cov.f.ewma = array(,c(t.factor,k.factor,k.factor))
- cov.f = var(factors) # unconditional variance as EWMA at time = 0
- FF = (factors[1,]- mean(factors)) %*% t(factors[1,]- mean(factors))
- cov.f.ewma[1,,] = (1-lambda)*FF + lambda*cov.f
- for (i in 2:t.factor) {
- FF = (factors[i,]- mean(factors)) %*% t(factors[i,]- mean(factors))
- cov.f.ewma[i,,] = (1-lambda)*FF + lambda*cov.f.ewma[(i-1),,]
- }
-
-}
- # 9/15/11: add dimnames to array
- dimnames(cov.f.ewma) = list(t.names, factor.names, factor.names)
-
- if(return.cor) {
- cor.f.ewma = cov.f.ewma
- for (i in 1:dim(cor.f.ewma)[1]) {
- cor.f.ewma[i, , ] = cov2cor(cov.f.ewma[i, ,])
- }
- return(cor.f.ewma)
- } else{
- return(cov.f.ewma)
- }
-}
-
Deleted: pkg/FactorAnalytics/sandbox/R/factorModelFactorRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/sandbox/R/factorModelFactorRiskDecomposition.r 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/factorModelFactorRiskDecomposition.r 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,53 +0,0 @@
-## factorModelFactorRiskDecomposition.r
-##
-## purpose: Compute factor model factor risk (sd) decomposition for individual
-## fund
-## author: Eric Zivot
-## created: August 13, 2009
-## revision history:
-## July 1, 2010
-## Added comment to inputs
-## June 8, 2010
-## Added percent contribution to risk as output
-
-factorModelFactorRiskDecomposition <- function(beta.vec, factor.cov, sig2.e) {
- ## Inputs:
- ## beta k x 1 vector of factor betas with factor names in the rownames
- ## factor.cov k x k factor excess return covariance matrix
- ## sig2.e scalar, residual variance from factor model
- ## Output:
- ## A list with the following components:
- ## sd.fm scalar, std dev based on factor model
- ## mcr.fm k+1 x 1 vector of factor marginal contributions to risk (sd)
- ## cr.fm k+1 x 1 vector of factor component contributions to risk (sd)
- ## pcr.fm k+1 x 1 vector of factor percent contributions to risk (sd)
- ## Remarks:
- ## The factor model has the form
- ## R(t) = beta'F(t) + e(t) = beta.star'F.star(t)
- ## where beta.star = (beta, sig.e)' and F.star(t) = (F(t)', z(t))'
- ## By Euler's theorem
- ## sd.fm = sum(cr.fm) = sum(beta*mcr.fm)
- beta.names = c(rownames(beta.vec), "residual")
- beta.vec = as.vector(beta.vec)
- beta.star.vec = c(beta.vec, sqrt(sig2.e))
- names(beta.star.vec) = beta.names
- factor.cov = as.matrix(factor.cov)
- k.star = length(beta.star.vec)
- k = k.star - 1
- factor.star.cov = diag(k.star)
- factor.star.cov[1:k, 1:k] = factor.cov
-
- ## compute factor model sd
- sd.fm = as.numeric(sqrt(t(beta.star.vec) %*% factor.star.cov %*% beta.star.vec))
- ## compute marginal and component contributions to sd
- mcr.fm = (factor.star.cov %*% beta.star.vec)/sd.fm
- cr.fm = mcr.fm * beta.star.vec
- pcr.fm = cr.fm/sd.fm
- rownames(mcr.fm) <- rownames(cr.fm) <- rownames(pcr.fm) <- beta.names
- ## return results
- ans = list(sd.fm = sd.fm,
- mcr.fm = mcr.fm,
- cr.fm = cr.fm,
- pcr.fm = pcr.fm)
- return(ans)
-}
Deleted: pkg/FactorAnalytics/sandbox/R/factorModelGroupRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/sandbox/R/factorModelGroupRiskDecomposition.r 2014-11-14 20:12:16 UTC (rev 3549)
+++ pkg/FactorAnalytics/sandbox/R/factorModelGroupRiskDecomposition.r 2014-11-14 23:22:05 UTC (rev 3550)
@@ -1,78 +0,0 @@
-## factorModelGroupRiskDecomposition.r
-##
-## purpose: Compute factor model risk decomposition for individual fund by risk groups
-## Risk groups are equity, rates, credit, fx, commondity, strategy
-##
-## author: Eric Zivot
-## created: July 9, 2009
-## revised: July 9, 2009
-
-factorModelGroupRiskDecomposition <- function(beta.vec, factor.cov, sig2.e,
- equityIds, ratesIds, creditIds,
- fxIds, cmdtyIds, strategyIds) {
-## Inputs:
-## beta k x 1 vector of factor betas
-## factor.cov k x k factor excess return covariance matrix
-## sig2.e scalar, residual variance from factor model
[TRUNCATED]
To get the complete diff run:
svnlook diff /svnroot/returnanalytics -r 3550
More information about the Returnanalytics-commits
mailing list