library(PortfolioAnalytics)12# Use edhec data3data(edhec)45R <- edhec[,1:10]67# Dimensions of data8m <- nrow(R)9N <- ncol(R)1011# Number of factors to use12k <- 31314##### Step 1 #####15fit <- statistical.factor.model(R, k)16names(fit)17beta <- fit$factor_loadings18f <- fit$factor_realizations19res <- fit$residuals2021##### Step 2 #####22# Compute the moments of the factors and idiosyncratic risk factors23# Note: The idiosyncratic factors are the residuals in the model (i.e. the24# unexplained asset return variation)2526# Check for equality with functions from Kris Boudt and functions I have27# included in the package2829# residual moments30denom <- m - k - 131stockM2 <- colSums(res^2) / denom32stockM3 <- colSums(res^3) / denom33stockM4 <- colSums(res^4) / denom3435# Compute the centered factors36# f.centered <- center(f)3738# factor moments39# (k x k)40factorM2 <- cov(f)4142# (k x k^2)43factorM3 <- PerformanceAnalytics:::M3.MM(f)4445# (k x k^3)46factorM4 <- PerformanceAnalytics:::M4.MM(f)4748##### Step 3 #####49# Compute the covariance, coskewness, and cokurtosis estimates from the statistical50# factor model.5152# covariance matrix53all.equal(54PortfolioAnalytics:::covarianceMF(beta, stockM2, factorM2),55extractCovariance(fit)56)5758# coskewness matrix59all.equal(60PortfolioAnalytics:::coskewnessMF(beta, stockM3, factorM3),61extractCoskewness(fit)62)6364# cokurtosis matrix65all.equal(66PortfolioAnalytics:::cokurtosisMF(beta, stockM2,stockM4, factorM2, factorM4),67extractCokurtosis(fit)68)697071