[Returnanalytics-commits] r2090 - in pkg/FactorAnalytics: . FactorAnalytics old FactorAnalytics old/R FactorAnalytics old/data FactorAnalytics old/man FactorAnalytics old/sandbox R data man

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Fri Jun 29 02:36:17 CEST 2012


Author: chenyian
Date: 2012-06-29 02:36:17 +0200 (Fri, 29 Jun 2012)
New Revision: 2090

Added:
   pkg/FactorAnalytics/FactorAnalytics old/
   pkg/FactorAnalytics/FactorAnalytics old/DESCRIPTION
   pkg/FactorAnalytics/FactorAnalytics old/NAMESPACE
   pkg/FactorAnalytics/FactorAnalytics old/R/
   pkg/FactorAnalytics/FactorAnalytics old/R/.Rhistory
   pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorESdecomposition.r
   pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorVaRdecomposition.r
   pkg/FactorAnalytics/FactorAnalytics old/R/chart.RollingStyle.R
   pkg/FactorAnalytics/FactorAnalytics old/R/chart.Style.R
   pkg/FactorAnalytics/FactorAnalytics old/R/factorModelCovariance.r
   pkg/FactorAnalytics/FactorAnalytics old/R/factorModelFactorRiskDecomposition.r
   pkg/FactorAnalytics/FactorAnalytics old/R/factorModelGroupRiskDecomposition.r
   pkg/FactorAnalytics/FactorAnalytics old/R/factorModelPortfolioRiskDecomposition.r
   pkg/FactorAnalytics/FactorAnalytics old/R/factorModelRiskDecomposition.r
   pkg/FactorAnalytics/FactorAnalytics old/R/factorModelSimulation.r
   pkg/FactorAnalytics/FactorAnalytics old/R/scenarioPredictions.r
   pkg/FactorAnalytics/FactorAnalytics old/R/scenarioPredictionsPortfolio.r
   pkg/FactorAnalytics/FactorAnalytics old/R/style.QPfit.R
   pkg/FactorAnalytics/FactorAnalytics old/R/style.fit.R
   pkg/FactorAnalytics/FactorAnalytics old/R/table.RollingStyle.R
   pkg/FactorAnalytics/FactorAnalytics old/data/
   pkg/FactorAnalytics/FactorAnalytics old/data/factors.rda
   pkg/FactorAnalytics/FactorAnalytics old/inst/
   pkg/FactorAnalytics/FactorAnalytics old/man/
   pkg/FactorAnalytics/FactorAnalytics old/man/Style.Rd
   pkg/FactorAnalytics/FactorAnalytics old/sandbox/
   pkg/FactorAnalytics/FactorAnalytics old/sandbox/FF.R
   pkg/FactorAnalytics/FactorAnalytics old/sandbox/factors.csv
   pkg/FactorAnalytics/FactorAnalytics old/sandbox/script.StyleTest.R
   pkg/FactorAnalytics/FactorAnalytics old/tests/
   pkg/FactorAnalytics/R/covEWMA.R
   pkg/FactorAnalytics/R/dCornishFisher.R
   pkg/FactorAnalytics/R/factorModelEsDecomposition.R
   pkg/FactorAnalytics/R/factorModelMonteCarlo.R
   pkg/FactorAnalytics/R/factorModelSdDecomposition.R
   pkg/FactorAnalytics/R/factorModelVaRDecomposition.R
   pkg/FactorAnalytics/R/fitFundamentalFactorModel.R
   pkg/FactorAnalytics/R/fitMacroeconomicFactorModel.R
   pkg/FactorAnalytics/R/fitStatisticalFactorModel.R
   pkg/FactorAnalytics/R/impliedFactorReturns.R
   pkg/FactorAnalytics/R/modifiedEsReport.R
   pkg/FactorAnalytics/R/modifiedIncrementalES.R
   pkg/FactorAnalytics/R/modifiedIncrementalVaR.R
   pkg/FactorAnalytics/R/modifiedPortfolioEsDecomposition.R
   pkg/FactorAnalytics/R/modifiedPortfolioVaRDecomposition.R
   pkg/FactorAnalytics/R/modifiedVaRReport.R
   pkg/FactorAnalytics/R/nonparametricEsReport.R
   pkg/FactorAnalytics/R/nonparametricIncrementalES.R
   pkg/FactorAnalytics/R/nonparametricIncrementalVaR.R
   pkg/FactorAnalytics/R/nonparametricPortfolioEsDecomposition.R
   pkg/FactorAnalytics/R/nonparametricPortfolioVaRDecomposition.R
   pkg/FactorAnalytics/R/nonparametricVaRReport.R
   pkg/FactorAnalytics/R/normalEsReport.R
   pkg/FactorAnalytics/R/normalIncrementalES.R
   pkg/FactorAnalytics/R/normalIncrementalVaR.R
   pkg/FactorAnalytics/R/normalPortfolioEsDecomposition.R
   pkg/FactorAnalytics/R/normalPortfolioVaRDecomposition.R
   pkg/FactorAnalytics/R/normalVaRReport.R
   pkg/FactorAnalytics/R/pCornishFisher.R
   pkg/FactorAnalytics/R/portfolioSdDecomposition.R
   pkg/FactorAnalytics/R/qCornishFisher.R
   pkg/FactorAnalytics/R/rCornishFisher.R
   pkg/FactorAnalytics/data/CRSP.RDATA
   pkg/FactorAnalytics/data/factorAnalytics-Ex.ps
   pkg/FactorAnalytics/data/managers.df.rda
   pkg/FactorAnalytics/data/stat.fm.data.RData
   pkg/FactorAnalytics/data/stock.RDATA
   pkg/FactorAnalytics/man/CornishFisher.Rd
   pkg/FactorAnalytics/man/covEWMA.Rd
   pkg/FactorAnalytics/man/factorModelCovariance.Rd
   pkg/FactorAnalytics/man/factorModelEsDecomposition.Rd
   pkg/FactorAnalytics/man/factorModelMonteCarlo.Rd
   pkg/FactorAnalytics/man/factorModelSdDecomposition.Rd
   pkg/FactorAnalytics/man/factorModelVaRDecomposition.Rd
   pkg/FactorAnalytics/man/fitFundamentalFactorModel.Rd
   pkg/FactorAnalytics/man/fitMacroeconomicFactorModel.Rd
   pkg/FactorAnalytics/man/fitStatisticalFactorModel.Rd
   pkg/FactorAnalytics/man/impliedFactorReturns.Rd
   pkg/FactorAnalytics/man/managers.df.Rd
   pkg/FactorAnalytics/man/modifiedEsReport.Rd
   pkg/FactorAnalytics/man/modifiedIncrementalES.Rd
   pkg/FactorAnalytics/man/modifiedIncrementalVaR.Rd
   pkg/FactorAnalytics/man/modifiedPortfolioEsDecomposition.Rd
   pkg/FactorAnalytics/man/modifiedPortfolioVaRDecomposition.Rd
   pkg/FactorAnalytics/man/modifiedVaRReport.Rd
   pkg/FactorAnalytics/man/nonparametricEsReport.Rd
   pkg/FactorAnalytics/man/nonparametricIncrementalES.Rd
   pkg/FactorAnalytics/man/nonparametricIncrementalVaR.Rd
   pkg/FactorAnalytics/man/nonparametricPortfolioEsDecomposition.Rd
   pkg/FactorAnalytics/man/nonparametricPortfolioVaRDecomposition.Rd
   pkg/FactorAnalytics/man/nonparametricVaRReport.Rd
   pkg/FactorAnalytics/man/normalEsReport.Rd
   pkg/FactorAnalytics/man/normalIncrementalES.Rd
   pkg/FactorAnalytics/man/normalIncrementalVaR.Rd
   pkg/FactorAnalytics/man/normalPortfolioEsDecomposition.Rd
   pkg/FactorAnalytics/man/normalPortfolioVaRDecomposition.Rd
   pkg/FactorAnalytics/man/normalVaRReport.Rd
   pkg/FactorAnalytics/man/portfolioSdDecomposition.Rd
   pkg/FactorAnalytics/man/scenarioPredictions.Rd
   pkg/FactorAnalytics/man/scenarioPredictionsPortfolio.Rd
   pkg/FactorAnalytics/man/stat.fm.data.Rd
   pkg/FactorAnalytics/man/stock.Rd
Modified:
   pkg/FactorAnalytics/DESCRIPTION
   pkg/FactorAnalytics/R/factorModelCovariance.r
   pkg/FactorAnalytics/R/scenarioPredictions.r
   pkg/FactorAnalytics/R/scenarioPredictionsPortfolio.r
Log:


Modified: pkg/FactorAnalytics/DESCRIPTION
===================================================================
--- pkg/FactorAnalytics/DESCRIPTION	2012-06-28 18:09:55 UTC (rev 2089)
+++ pkg/FactorAnalytics/DESCRIPTION	2012-06-29 00:36:17 UTC (rev 2090)
@@ -1,13 +1,11 @@
-Package: FactorAnalytics
-Type: Package
-Title: Functions for performing factor analysis on financial time series
-Version: 0.3
-Date: 2011-01-16
-Author: Peter Carl, Brian G. Peterson, Eric Zivot
-Maintainer: Brian G. Peterson <brian at braverock.com>
-Description: A package of functions that may be used to perform various factor analyses on financial time series.  The package includes functions that 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".
-Depends: R (>= 2.9.0), PerformanceAnalytics (>= 1.0), xts
-Suggests: quadprog, quantreg
-License: GPL
-URL: http://braverock.com/R/
-Copyright: (c) 2004-2011
+Package: factorAnalytics
+Type: Package
+Title: factor analysis
+Version: 1.0
+Date: 2011-07-22
+Author: Eric Zivot and Yi-An Chen
+Maintainer: Yi-An Chen <chenyian at uw.edu>
+Description: An R package for estimation and risk analysis of linear factor models for asset returns and portfolios. It contains three major fitting method for the factor models: fitting macroeconomic factor model, fitting fundamental factor model and fitting statistical factor model and some risk analysis tools like VaR, ES to use the result of the fitting method. It also provides the different type of distribution to fit the fat-tail behavior of the financial returns, including edgeworth expansion type distribution.  
+License: GPL-2
+Depends: robust, robustbase, leaps, lars, zoo, MASS, PerformanceAnalytics, ff, sn, tseries
+LazyLoad: yes
\ No newline at end of file

Added: pkg/FactorAnalytics/FactorAnalytics old/DESCRIPTION
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/DESCRIPTION	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/DESCRIPTION	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,13 @@
+Package: FactorAnalytics
+Type: Package
+Title: Functions for performing factor analysis on financial time series
+Version: 0.3
+Date: 2011-01-16
+Author: Peter Carl, Brian G. Peterson, Eric Zivot
+Maintainer: Brian G. Peterson <brian at braverock.com>
+Description: A package of functions that may be used to perform various factor analyses on financial time series.  The package includes functions that 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".
+Depends: R (>= 2.9.0), PerformanceAnalytics (>= 1.0), xts
+Suggests: quadprog, quantreg
+License: GPL
+URL: http://braverock.com/R/
+Copyright: (c) 2004-2011

Added: pkg/FactorAnalytics/FactorAnalytics old/NAMESPACE
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/NAMESPACE	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/NAMESPACE	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,5 @@
+export(chart.Style)
+export(chart.RollingStyle)
+export(table.RollingStyle)
+export(style.fit)
+export(style.QPfit)
\ No newline at end of file

Added: pkg/FactorAnalytics/FactorAnalytics old/R/.Rhistory
===================================================================
Added: pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorESdecomposition.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorESdecomposition.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorESdecomposition.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,83 @@
+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)
+}

Added: pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorVaRdecomposition.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorVaRdecomposition.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/bootstrapFactorVaRdecomposition.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,90 @@
+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)
+}

Added: pkg/FactorAnalytics/FactorAnalytics old/R/chart.RollingStyle.R
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/chart.RollingStyle.R	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/chart.RollingStyle.R	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,52 @@
+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
+#
+#
+###############################################################################

Added: pkg/FactorAnalytics/FactorAnalytics old/R/chart.Style.R
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/chart.Style.R	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/chart.Style.R	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,70 @@
+`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 1683 2010-04-28 03:23:44Z peter_carl $
+#
+###############################################################################
+# $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
+#
+#
+###############################################################################

Added: pkg/FactorAnalytics/FactorAnalytics old/R/factorModelCovariance.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/factorModelCovariance.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/factorModelCovariance.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,33 @@
+## factorModelCovariance.r
+##
+## purpose: compute covariance matrix from estimated factor model
+## author: Eric Zivot
+## created: November 25, 2008
+## revised: July 20, 2009
+
+factorModelCovariance <- function(beta.mat, factor.cov, sig.e) {
+## Inputs:
+## beta.mat		   	n x k matrix of factor betas
+## factor.cov		  k x k factor excess return covariance matrix
+## sig.e			    n x 1 vector of residual variances from factor model
+## Output:
+## cov.fm			    n x n excess return covariance matrix based on
+##				        estimated factor model
+	beta.mat = as.matrix(beta.mat)
+	factor.cov = as.matrix(factor.cov)
+	sig.e = as.vector(sig.e)
+	if (length(sig.e) > 1) {
+	 D.e = diag(as.vector(sig.e))
+  } else {
+   D.e =  as.matrix(sig.e)
+  }
+	if (ncol(beta.mat) != ncol(factor.cov))
+		stop("beta.mat and factor.cov must have same number of columns")
+		
+	if (nrow(D.e) != nrow(beta.mat))
+		stop("beta.mat and D.e must have same number of rows")
+	cov.fm = beta.mat %*% factor.cov %*% t(beta.mat) + D.e
+	if (any(diag(chol(cov.fm)) == 0))
+    warning("Covariance matrix is not positive definite")
+	return(cov.fm)
+}

Added: pkg/FactorAnalytics/FactorAnalytics old/R/factorModelFactorRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/factorModelFactorRiskDecomposition.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/factorModelFactorRiskDecomposition.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,53 @@
+## 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)
+}

Added: pkg/FactorAnalytics/FactorAnalytics old/R/factorModelGroupRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/factorModelGroupRiskDecomposition.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/factorModelGroupRiskDecomposition.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,78 @@
+## 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
+## equityIds     k1 x 1 vector of equity factor Ids
+## ratesIds      k2 x 1 vector of rates factor Ids
+## creditIds     k3 x 1 vector of credit factor Ids
+## fxIds         k4 x 1 vector of fx factor Ids
+## cmdtyIds      k5 x 1 vector of commodity factor Ids
+## strategyIds   k6 x 1 vector of strategy (blind) factor Ids
+##
+## Output:
+## A list with the following components:
+## var.fm             scalar, variance based on factor model
+## var.systematic     scalar, variance contribution due to factors
+## var.specific       scalar, residual variance contribution
+## var.cov            scalar, variance contribution due to covariances between factor groups
+## var.equity         scalar, variance contribution due to equity factors
+## var.rates          scalar, variance contribution due to rates factors
+## var.credit         scalar, variance contribution due to credit factors
+## var.fx             scalar, variance contribution due to fx factors
+## var.cmdty          scalar, variance contribution due to commodity factors
+## var.strategy       scalar, variance contribution due to strategy (pca) factors
+## Remarks:
+## k1 + ... + k6 = k
+## var.fm = var.systematic + var.specific = sum(var.factors) + var.cov + var.specific
+
+	beta.vec = as.matrix(beta.vec)
+	n.beta = length(beta.vec)
+	n.factors = length(c(equityIds, ratesIds, creditIds, fxIds, cmdtyIds, strategyIds))
+	if (n.beta != n.factors)
+	 stop("Number of supplied factor Ids is not equal to number of betas")
+	factor.cov = as.matrix(factor.cov)
+	
+## compute factor model variance
+  var.systematic = t(beta.vec) %*% factor.cov %*% beta.vec
+	var.fm = var.systematic + sig2.e
+
+## compute factor model variance contributions
+	var.equity = t(beta.vec[equityIds,]) %*% factor.cov[equityIds,equityIds] %*% beta.vec[equityIds,]
+	var.rates = t(beta.vec[ratesIds,]) %*% factor.cov[ratesIds,ratesIds] %*% beta.vec[ratesIds,]
+	var.credit = t(beta.vec[creditIds,]) %*% factor.cov[creditIds,creditIds] %*% beta.vec[creditIds,]
+	var.fx = t(beta.vec[fxIds,]) %*% factor.cov[fxIds,fxIds] %*%  beta.vec[fxIds,]
+	var.cmdty = t(beta.vec[cmdtyIds,]) %*% factor.cov[cmdtyIds,cmdtyIds] %*% beta.vec[cmdtyIds,]
+	if (!is.null(strategyIds)) {
+    var.strategy = t(beta.vec[strategyIds,]) %*% factor.cov[strategyIds,strategyIds] %*% beta.vec[strategyIds,]
+	} else {
+   var.strategy = 0
+  } 
+	 
+# compute covariance contribution	 
+  var.cov = var.systematic - (var.equity + var.rates + var.credit + var.fx + var.cmdty + var.strategy)
+
+## return results
+	ans = list(var.fm=as.numeric(var.fm),
+            var.systematic=as.numeric(var.systematic),
+            var.specific=sig2.e,
+            var.cov=as.numeric(var.cov),
+            var.equity=as.numeric(var.equity),
+            var.rates=as.numeric(var.rates),
+            var.credit=as.numeric(var.credit),
+            var.fx=as.numeric(var.fx),
+            var.cmdty=as.numeric(var.cmdty),
+            var.strategy=var.strategy)
+	return(ans)
+}

Added: pkg/FactorAnalytics/FactorAnalytics old/R/factorModelPortfolioRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/factorModelPortfolioRiskDecomposition.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/factorModelPortfolioRiskDecomposition.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,74 @@
+## factorModelPortfolioRiskDecomposition.r
+##
+## purpose: Compute factor model sd (risk) decomposition for portfolio
+## author: Eric Zivot
+## created: January 21, 2009
+## revised: January 28, 2009
+## references:
+## Qian, Hua and Sorensen (2007) Quantitative Equity Portfolio Management, 
+## chapter 3.
+
+factorModelPortfolioRiskDecomposition <- function(w.vec, beta.mat, factor.cov, sig2.e) {
+## Inputs:
+## w.vec         n x 1 vector of portfolio weights
+## beta.mat		   n x k matrix of factor betas
+## factor.cov		 k x k factor excess return covariance matrix
+## sig2.e			   n x 1 vector of residual variances from factor model
+## Output:
+## cov.fm		     n x n excess return covariance matrxi based on
+##				       estimated factor model
+## Output:
+## A list with the following components:
+## var.p              scalar, portfolio variance based on factor model
+## var.p.systematic   scalar, portfolio variance due to factors
+## var.p.specific     scalar, portfolio variance not explanied by factors
+## var.p.cov          scalar, portfolio variance due to covariance terms
+## var.p.factors      k x 1 vector, portfolio variances due to factors
+## mcr.p              n x 1 vector, marginal contributions to portfolio total risk
+## mcr.p.systematic   n x 1 vector, marginal contributions to portfolio systematic risk
+## mcr.p.specific     n x 1 vector, marginal contributions to portfolio specific risk
+## pcr.p              n x 1 vector, percent contribution to portfolio total risk
+	beta.mat = as.matrix(beta.mat)
+	factor.cov = as.matrix(factor.cov)
+	sig2.e = as.vector(sig2.e)
+	if (length(sig2.e) > 1) {
+	 D.e = diag(as.vector(sig2.e))
+	} else {
+   D.e = as.matrix(sig2.e)
+  } 
+	if (ncol(beta.mat) != ncol(factor.cov))
+		stop("beta.mat and factor.cov must have same number of columns")
+	if (nrow(D.e) != nrow(beta.mat))
+		stop("beta.mat and D.e must have same number of rows")
+ ## compute factor model covariance matrix
+  cov.systematic = beta.mat %*% factor.cov %*% t(beta.mat)
+	cov.fm = cov.systematic + D.e
+	if (any(diag(chol(cov.fm)) == 0))
+    warning("Covariance matrix is not positive definite")
+ ## compute portfolio level variance
+ var.p = as.numeric(t(w.vec) %*% cov.fm %*% w.vec)
+ var.p.systematic = as.numeric(t(w.vec) %*% cov.systematic %*% w.vec)
+ var.p.specific = as.numeric(t(w.vec) %*% D.e %*% w.vec)
+ beta.p = crossprod(w.vec, beta.mat)
+ var.p.factors = beta.p^2 * diag(factor.cov)
+ var.p.cov = var.p.systematic - sum(var.p.factors)
+ 
+ 
+ ## compute marginal contributions to risk
+ mcr.p = (cov.systematic %*% w.vec + D.e %*% w.vec)/sqrt(var.p)
+ mcr.p.systematic = (cov.systematic %*% w.vec + D.e %*% w.vec)/sqrt(var.p.systematic)
+ mcr.p.specific = (D.e %*% w.vec)/sqrt(var.p.specific)
+ ## compute percentage risk contribution
+ pcr.p = (w.vec * mcr.p)/sqrt(var.p)
+ ## return results
+ ans = list(var.p=var.p,
+            var.p.systematic=var.p.systematic,
+            var.p.specific=var.p.specific,
+            var.p.cov=var.p.cov,
+            var.p.factors=var.p.factors,
+            mcr.p=mcr.p,
+            mcr.p.systematic=mcr.p.systematic,
+            mcr.p.specific=mcr.p.specific,
+            pcr.p=pcr.p)
+ return(ans)
+}
\ No newline at end of file

Added: pkg/FactorAnalytics/FactorAnalytics old/R/factorModelRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/factorModelRiskDecomposition.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/factorModelRiskDecomposition.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,44 @@
+## factorModelRiskDecomposition.r
+## 
+## purpose: Compute factor model risk decomposition for individual fund
+## author: Eric Zivot
+## created: January 21, 2009
+## revised: January 28, 2009
+
+factorModelRiskDecomposition <- function(beta.vec, factor.cov, sig2.e) {
+## 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
+## Output:
+## cov.fm		     n x n excess return covariance matrix based on
+##				       estimated factor model
+## Output:
+## A list with the following components:
+## var.fm             scalar, variance based on factor model
+## var.systematic     scalar, variance due to factors
+#  var.specific       scalar, residual variance
+## var.cov            scalar, variance due to covariance contribution
+## var.factors        k x 1 vector of variances due to factors
+## Remarks:
+## var.fm = var.systematic + var.specific = sum(var.factors) + var.cov + var.specific
+
+	beta.vec = as.vector(beta.vec)
+	factor.cov = as.matrix(factor.cov)
+	
+## compute factor model variance
+  	var.systematic = t(beta.vec) %*% factor.cov %*% beta.vec
+	var.fm = var.systematic + sig2.e
+
+## compute factor model variance contributions
+	var.factors = beta.vec^2 * diag(factor.cov)
+  	var.cov = var.systematic - sum(var.factors)
+
+## return results
+	ans = list(var.fm=as.numeric(var.fm),
+            var.systematic=as.numeric(var.systematic),
+            var.specific=sig2.e,
+            var.cov=as.numeric(var.cov),
+            var.factors=var.factors)
+	return(ans)
+}

Added: pkg/FactorAnalytics/FactorAnalytics old/R/factorModelSimulation.r
===================================================================
--- pkg/FactorAnalytics/FactorAnalytics old/R/factorModelSimulation.r	                        (rev 0)
+++ pkg/FactorAnalytics/FactorAnalytics old/R/factorModelSimulation.r	2012-06-29 00:36:17 UTC (rev 2090)
@@ -0,0 +1,74 @@
+
+factorModelSimulation <- function(n.sim=5000, factorBetas, factorData, residualMoments,
+        residual.dist = c("normal","Cornish-Fisher", "skew-t")) {
+    ## Simulate performance for specified funds from fitted factor models
+    ## Simulations are computed using a semi-parametric methodology. Factor performance
+    ## is simulated by bootstrapping with replacement from historical performance, and
+    ## a fitted factor model return conditional on factor performance is computed by
+    ## applying estimated factor model coefficients to the bootstrapped factor performance.
+    ## Residuals are simulated parametrically from one of three distributions: normal
+    ## distribution, Cornish-Fisher distribution, skew-t distribution. Unconditional
+    ## performance is then computed by adding the risidual simulations to the conditional
+    ## performance.
+    ## inputs:
+    ## n.sim            scalar, number of simulations
+    ## factorBetas      n.fund x k matrix of factor model betas for n.fund funds
+    ## factorData       n x k matrix of historical factor performance
+    ## residualMoments  n.fund x 7 vector of residual moments with columns sigma, skew,
+    ##                  ekurt, location, scale, shape, df
+    ## residual.dist    character value indicating the residual distribution. Valid choices
+    ##                  are "normal" for normal distribution; "Cornish-Fisher" for
+    ##                  Cornish-Fisher distribution; "skew-t' for skew-t distribution.
+    ## output:
+    ## n.sim x n.fund matrix of simulated performance.
+    ## Remarks:
+    ## 1. The factor model has the form
+    ## R(t) = beta'F(t) + e(t), e(t) ~ D(0,theta)
[TRUNCATED]

To get the complete diff run:
    svnlook diff /svnroot/returnanalytics -r 2090


More information about the Returnanalytics-commits mailing list