[Returnanalytics-commits] r2697 - pkg/FactorAnalytics/R

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Fri Aug 2 02:13:20 CEST 2013


Author: chenyian
Date: 2013-08-02 02:13:20 +0200 (Fri, 02 Aug 2013)
New Revision: 2697

Removed:
   pkg/FactorAnalytics/R/FactorAnalytics-package.R
   pkg/FactorAnalytics/R/factorModelFactorRiskDecomposition.r
   pkg/FactorAnalytics/R/factorModelGroupRiskDecomposition.r
   pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r
   pkg/FactorAnalytics/R/factorModelPortfolioRiskDecomposition.r
   pkg/FactorAnalytics/R/factorModelRiskAttribution.r
   pkg/FactorAnalytics/R/factorModelRiskDecomposition.r
   pkg/FactorAnalytics/R/factorModelSimulation.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/qCornishFisher.R
   pkg/FactorAnalytics/R/rCornishFisher.R
   pkg/FactorAnalytics/R/scenarioPredictions.r
   pkg/FactorAnalytics/R/scenarioPredictionsPortfolio.r
   pkg/FactorAnalytics/R/style.QPfit.R
   pkg/FactorAnalytics/R/style.fit.R
   pkg/FactorAnalytics/R/table.RollingStyle.R
Modified:
   pkg/FactorAnalytics/R/
Log:
ignore functions that haven't reviewed yet. 


Property changes on: pkg/FactorAnalytics/R
___________________________________________________________________
Modified: svn:ignore
   - bootstrapFactorESdecomposition.r
bootstrapFactorVaRdecomposition.r
chart.RollingStyle.R
chart.Style.R
covEWMA.R
dCornishFisher.R
plot.MacroFactorModel.r
print.MacroFactorModel.r
summary.MacroFactorModel.r

   + FactorAnalytics-package.R
bootstrapFactorESdecomposition.r
bootstrapFactorVaRdecomposition.r
chart.RollingStyle.R
chart.Style.R
covEWMA.R
dCornishFisher.R
factorModelFactorRiskDecomposition.r
factorModelGroupRiskDecomposition.r
factorModelPerformanceAttribution.r
factorModelPortfolioRiskDecomposition.r
factorModelRiskAttribution.r
factorModelRiskDecomposition.r
factorModelSimulation.r
impliedFactorReturns.R
modifiedEsReport.R
modifiedIncrementalES.R
modifiedIncrementalVaR.R
modifiedPortfolioEsDecomposition.R
modifiedPortfolioVaRDecomposition.R
modifiedVaRReport.R
nonparametricEsReport.R
nonparametricIncrementalES.R
nonparametricIncrementalVaR.R
nonparametricPortfolioEsDecomposition.R
nonparametricPortfolioVaRDecomposition.R
nonparametricVaRReport.R
normalEsReport.R
normalIncrementalES.R
normalIncrementalVaR.R
normalPortfolioEsDecomposition.R
normalPortfolioVaRDecomposition.R
normalVaRReport.R
pCornishFisher.R
plot.MacroFactorModel.r
print.MacroFactorModel.r
qCornishFisher.R
rCornishFisher.R
scenarioPredictions.r
scenarioPredictionsPortfolio.r
style.QPfit.R
style.fit.R
summary.MacroFactorModel.r
table.RollingStyle.R


Deleted: pkg/FactorAnalytics/R/FactorAnalytics-package.R
===================================================================
--- pkg/FactorAnalytics/R/FactorAnalytics-package.R	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/FactorAnalytics-package.R	2013-08-02 00:13:20 UTC (rev 2697)
@@ -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/R/factorModelFactorRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelFactorRiskDecomposition.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelFactorRiskDecomposition.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -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/R/factorModelGroupRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelGroupRiskDecomposition.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelGroupRiskDecomposition.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -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
-## 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)
-}

Deleted: pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelPerformanceAttribution.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -1,292 +0,0 @@
-# performance attribution
-# Yi-An Chen
-# July 30, 2012
-
-
-
-#' Compute BARRA-type performance attribution
-#' 
-#' Decompose total returns or active returns into returns attributed to factors
-#' and specific returns. Class of FM.attribution is generated and generic
-#' function \code{plot} and \code{summary} can be used.
-#' 
-#' total returns can be decomposed into returns attributed to factors and
-#' specific returns. \eqn{R_t = \sum_j e_{jt} * f_{jt} +
-#' u_t},t=1..T,\eqn{e_{jt}} is exposure to factor j and \eqn{f_{jt}} is factor
-#' j. The returns attributed to factor j is \eqn{e_{jt} * f_{jt}} and portfolio
-#' specific returns is \eqn{u_t}
-#' 
-#' @param fit Class of "MacroFactorModel", "FundamentalFactorModel" or
-#' "statFactorModel".
-#' @param benchmark a zoo, vector or data.frame provides benchmark time series
-#' returns.
-#' @param ...  Other controled variables for fit methods.
-#' @return an object of class \code{FM.attribution} containing
-#' @returnItem cum.ret.attr.f N X J matrix of cumulative return attributed to
-#' factors.
-#' @returnItem cum.spec.ret 1 x N vector of cumulative specific returns.
-#' @returnItem attr.list list of time series of attributed returns for every
-#' portfolio.
-#' @author Yi-An Chen.
-#' @references Grinold,R and Kahn R, \emph{Active Portfolio Management},
-#' McGraw-Hill.
-#' @examples
-#' 
-#' \dontrun{
-#' data(managers.df)
-#' ret.assets = managers.df[,(1:6)]
-#' factors    = managers.df[,(7:9)]
-#' fit.macro <- fitMacroeconomicFactorModel(ret.assets,factors,fit.method="OLS", factor.set = 3,
-#'                                          variable.selection="all subsets",decay.factor = 0.95)
-#' # withoud benchmark
-#' fm.attr <- factorModelPerformanceAttribution(fit.macro)
-#' 
-#' }
-#' 
-factorModelPerformanceAttribution <- 
-  function(fit,benchmark=NULL,...) {
-   
-    # input
-    # fit      :   Class of MacroFactorModel, FundamentalFactorModel and statFactorModel
-    # benchmark: benchmark returns, default is NULL. If benchmark is provided, active returns 
-    #            is used.
-    # ...      : controlled variables for fitMacroeconomicsFactorModel and fitStatisticalFactorModel 
-    # output
-    # class of "FMattribution" 
-    #    
-    # plot.FMattribution     
-    # summary.FMattribution    
-    # print.FMattribution    
-    require(zoo)
-   
-    if (class(fit) !="MacroFactorModel" & class(fit) !="FundamentalFactorModel" 
-        & class(fit) != "StatFactorModel")
-    {
-      stop("Class has to be MacroFactorModel.")
-    }
-    
-  # MacroFactorModel chunk  
-    
-  if (class(fit) == "MacroFactorModel")  {
-    
-  # if benchmark is provided
-  
-    if (!is.null(benchmark)) {
-    ret.assets =  fit$ret.assets - benchmark
-    fit = fitMacroeconomicFactorModel(ret.assets=ret.assets,...)
-    }
-# return attributed to factors
-    cum.attr.ret <- fit$beta.mat
-    cum.spec.ret <- fit$alpha.vec
-    factorName = colnames(fit$beta.mat)
-    fundName = rownames(fit$beta.mat)
-    
-    attr.list <- list()
-    
-    for (k in fundName) {
-    fit.lm = fit$asset.fit[[k]]
-   
-    ## extract information from lm object
-    date <- names(fitted(fit.lm))
-   
-    actual.z = zoo(fit.lm$model[1], as.Date(date))
- 
-
-# attributed returns
-# active portfolio management p.512 17A.9 
-    
-  cum.ret <-   Return.cumulative(actual.z)
-  # setup initial value
-  attr.ret.z.all <- zoo(, as.Date(date))
-  for ( i in factorName ) {
-  
-    if (fit$beta.mat[k,i]==0) {
-    cum.attr.ret[k,i] <- 0
-  attr.ret.z.all <- merge(attr.ret.z.all,zoo(rep(0,length(date)),as.Date(date)))  
-  } else {
-  attr.ret.z <- actual.z - zoo(as.matrix(fit.lm$model[i])%*%as.matrix(fit.lm$coef[i]),
-                               as.Date(date))  
-  cum.attr.ret[k,i] <- cum.ret - Return.cumulative(actual.z-attr.ret.z)  
-  attr.ret.z.all <- merge(attr.ret.z.all,attr.ret.z)
-  }
-  
-  }
-    
-  # specific returns    
-    spec.ret.z <- actual.z - zoo(as.matrix(fit.lm$model[,-1])%*%as.matrix(fit.lm$coef[-1]),
-                                 as.Date(date))
-    cum.spec.ret[k] <- cum.ret - Return.cumulative(actual.z-spec.ret.z)
-  attr.list[[k]] <- merge(attr.ret.z.all,spec.ret.z)
-   colnames(attr.list[[k]]) <- c(factorName,"specific.returns")
-    }
-
-    
-  }    
-    
-if (class(fit) =="FundamentalFactorModel" ) {
-  # if benchmark is provided
-  
-  if (!is.null(benchmark)) {
-   stop("use fitFundamentalFactorModel instead")
-  }
-  # return attributed to factors
-  factor.returns <- fit$factor.rets[,-1]
-  factor.names <- names(fit$factor.rets[,-1])
-  dates <- as.character(unique(fit$exposure.data[,"DATE"]))
-  exposure <- fund.fit$exposure.data
-  ticker <- names(fit$resids)
- 
-  N <- length(ticker)
-  J <- length(factor.names)
-  t <- length(dates)
-  # array arranges in N X J X t 
-  # N is assets names, J is factors, t is time
-  attr.ret <- array(,dim=c(N,J,t),dimnames=list(ticker,factor.names,dates))
-  for (i in dates) {
-    idx = which(exposure[,"DATE"]==i)
-    for (j in factor.names) {
-  attr.ret[,j,i] <- exposure[idx,j]*coredata(factor.returns[as.Date(i)])[,j]
-  }
-  }
-  
-  # specific returns
-  # zoo class 
-  intercept <- fit$factor.rets[,1]
-  resids <- fit$resids
-  spec.ret.z <- resids + intercept 
-   
-  #cumulative return attributed to factors
-  cum.attr.ret <- matrix(,nrow=length(ticker),ncol=length(factor.names),
-                         dimnames=list(ticker,factor.names))
-  cum.spec.ret <- rep(0,length(ticker))
-  names(cum.spec.ret) <- ticker
-  
-  # arrange returns data
-  actual <- fund.fit$returns.data
-  # N <- length(assets.names)
-  # t <- length(dates)
-  # array arranges in N X t 
-  # N is assets names, J is factors, t is time
-  actual.ret <- array(,dim=c(N,t),dimnames=list(ticker,dates))
-  for (i in dates) {
-    idx = which(actual[,"DATE"]==i)
-    actual.ret[,i] <- actual[idx,"RETURN"]  
-  }  
-  
-  # make returns as zoo 
-  actual.z.all <- zoo(,as.Date(dates))  
-  for (k in ticker) {
-    actual.z <- zoo(actual.ret[k,],as.Date(dates))
-    actual.z.all <- merge(actual.z.all,actual.z)
-  }
-  colnames(actual.z.all) <- ticker
-  
-  
-  
-  # make list of every asstes and every list contains return attributed to factors 
-  # and specific returns 
-  attr.list <- list()
-    for (k in ticker){
-  attr.ret.z.all <- zoo(,as.Date(dates))
-  # cumulative returns
-  cum.ret <-   Return.cumulative(actual.z.all[,k])
-    for (j in factor.names) {
-   attr.ret.z <- zoo(attr.ret[k,j,],as.Date(dates) )
-   attr.ret.z.all <- merge(attr.ret.z.all,attr.ret.z)
-   cum.attr.ret[k,j] <- cum.ret - Return.cumulative(actual.z.all[,k]-attr.ret.z)
-   }
-  attr.list[[k]] <- merge(attr.ret.z.all,spec.ret.z[,k])
-   colnames(attr.list[[k]]) <- c(factor.names,"specific.returns") 
-   cum.spec.ret[k] <- cum.ret - Return.cumulative(actual.z.all[,k]-spec.ret.z[,k])
-  
-    }
-  
-}
-    
-    if (class(fit) == "StatFactorModel") {
-      
-      # if benchmark is provided
-      
-      if (!is.null(benchmark)) {
-        x =  fit$asset.ret - benchmark
-        fit = fitStatisticalFactorModel(x=x,...)
-      }
-      # return attributed to factors
-      cum.attr.ret <- t(fit$loadings)
-      cum.spec.ret <- fit$r2
-      factorName = rownames(fit$loadings)
-      fundName = colnames(fit$loadings)
-     
-      # create list for attribution
-      attr.list <- list()
-      # pca method
-          
-      if ( dim(fit$asset.ret)[1] > dim(fit$asset.ret)[2] ) {
-        
-      
-      for (k in fundName) {
-        fit.lm = fit$asset.fit[[k]]
-        
-        ## extract information from lm object
-        date <- names(fitted(fit.lm))
-        # probably needs more general Date setting
-        actual.z = zoo(fit.lm$model[1], as.Date(date))
-        
-        
-        # attributed returns
-        # active portfolio management p.512 17A.9 
-        
-        cum.ret <-   Return.cumulative(actual.z)
-        # setup initial value
-        attr.ret.z.all <- zoo(, as.Date(date))
-        for ( i in factorName ) {
-                
-            attr.ret.z <- actual.z - zoo(as.matrix(fit.lm$model[i])%*%as.matrix(fit.lm$coef[i]),
-                                         as.Date(date))  
-            cum.attr.ret[k,i] <- cum.ret - Return.cumulative(actual.z-attr.ret.z)  
-            attr.ret.z.all <- merge(attr.ret.z.all,attr.ret.z)
-        
-          
-        }
-        
-        # specific returns    
-        spec.ret.z <- actual.z - zoo(as.matrix(fit.lm$model[,-1])%*%as.matrix(fit.lm$coef[-1]),
-                                     as.Date(date))
-        cum.spec.ret[k] <- cum.ret - Return.cumulative(actual.z-spec.ret.z)
-        attr.list[[k]] <- merge(attr.ret.z.all,spec.ret.z)
-        colnames(attr.list[[k]]) <- c(factorName,"specific.returns")
-      }
-      } else {
-      # apca method
-#         fit$loadings # f X K
-#         fit$factors  # T X f
-        
-        dates <- rownames(fit$factors)
-        for ( k in fundName) {
-          attr.ret.z.all <- zoo(, as.Date(date))
-          actual.z <- zoo(fit$asset.ret[,k],as.Date(dates))
-          cum.ret <-   Return.cumulative(actual.z)
-          for (i in factorName) {
-       attr.ret.z <- zoo(fit$factors[,i] * fit$loadings[i,k], as.Date(dates) )
-       attr.ret.z.all <- merge(attr.ret.z.all,attr.ret.z)
-       cum.attr.ret[k,i] <- cum.ret - Return.cumulative(actual.z-attr.ret.z)
-        }
-         spec.ret.z <- actual.z - zoo(fit$factors%*%fit$loadings[,k],as.Date(dates))
-          cum.spec.ret[k] <- cum.ret - Return.cumulative(actual.z-spec.ret.z)
-        attr.list[[k]] <- merge(attr.ret.z.all,spec.ret.z)
-          colnames(attr.list[[k]]) <- c(factorName,"specific.returns")  
-        }
-                
-        
-        } 
-          
-    }
-    
-    
-    
-    ans = list(cum.ret.attr.f=cum.attr.ret,
-               cum.spec.ret=cum.spec.ret,
-               attr.list=attr.list)
-class(ans) = "FM.attribution"      
-return(ans)
-    }

Deleted: pkg/FactorAnalytics/R/factorModelPortfolioRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelPortfolioRiskDecomposition.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelPortfolioRiskDecomposition.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -1,74 +0,0 @@
-## 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

Deleted: pkg/FactorAnalytics/R/factorModelRiskAttribution.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelRiskAttribution.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelRiskAttribution.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -1,59 +0,0 @@
-# Yi-An Chen
-# July 5, 2012
-
-factorModelRiskAttribution <- 
-  function(fit) {
-    class = class(fit,benchmark,start,end,Full.sample=TRUE)
-  # input
- # class:   Class has to be either MacroFactorModel, FundmentalFactorModel
- #          or StatFactorModel 
- # benchmark: benchmark returns, default is equally weighted portfolio   
- # start :  Start of trailling period. 
- # end   :  End of trailling period.  
- # Full.sample: Is full sample included in the analysis. Default is TRUE.   
-  
- # output
- # class of "FMattribution" 
- #    
- # plot.FMattribution     
- # summary.FMattribution    
- # print.FMattribution    
-  if (class !="MacroFactorModel" && class !="FundmentalFactorModel"
-      && class != "StatFactorModel")
-    {
-    stop("Class has to be either MacroFactorModel, FundmentalFactorModel
-         or StatFactorModel")
-  }
-    # get portfolio names and factor names
-    manager.names = colnames(fit.macro$ret.assets)
-    factor.names  = colnames(fit.macro$factors)
-    
-  # beginning of switching  
-    switch(class,
-    MacroFactorModel={ 
-      for (i in manager.names) {
-      
-      total.ret = fit$ret.assets
-      total.sd = sd(total)
-      active.ret = benchmark - fit$ret.assets
-      active.sd = ad(active)
-      expected.active.ret = beta.mat%*%fit.macro$factors - benchmark
-      exceptional.active.ret = active- expected.active.ret
-      Market.timing
-      Risk.indexes
-      Industries
-      Asset.selection
-      Trading
-      Transaction.cost
-      }
-        
-        },       
-    FundmentalFactorModel={
-      print("test 2")
-    },
-    StatFactorModel={
-      
-    }       
-           
-           )
-  }
\ No newline at end of file

Deleted: pkg/FactorAnalytics/R/factorModelRiskDecomposition.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelRiskDecomposition.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelRiskDecomposition.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -1,44 +0,0 @@
-## 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)
-}

Deleted: pkg/FactorAnalytics/R/factorModelSimulation.r
===================================================================
--- pkg/FactorAnalytics/R/factorModelSimulation.r	2013-08-02 00:11:09 UTC (rev 2696)
+++ pkg/FactorAnalytics/R/factorModelSimulation.r	2013-08-02 00:13:20 UTC (rev 2697)
@@ -1,74 +0,0 @@
-
-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)
-    ## where beta = fitted factor model parameters, F(t) = risk factors, e(t) = residuals,
-    ## and theta = parameters of residual distribution D. If D = normal, then theta =
[TRUNCATED]

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


More information about the Returnanalytics-commits mailing list