From noreply at r-forge.r-project.org Thu May 1 07:55:09 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 1 May 2014 07:55:09 +0200 (CEST) Subject: [Returnanalytics-commits] r3379 - pkg/PortfolioAnalytics/sandbox/RFinance2014 Message-ID: <20140501055509.1AB2C186ED5@r-forge.r-project.org> Author: rossbennett34 Date: 2014-05-01 07:55:08 +0200 (Thu, 01 May 2014) New Revision: 3379 Removed: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/ pkg/PortfolioAnalytics/sandbox/RFinance2014/data/ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R pkg/PortfolioAnalytics/sandbox/RFinance2014/data_figures/ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R pkg/PortfolioAnalytics/sandbox/RFinance2014/edhec.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/edhec_eda.R pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_figures/ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.md pkg/PortfolioAnalytics/sandbox/RFinance2014/slides.pdf pkg/PortfolioAnalytics/sandbox/RFinance2014/slidy_presentation.html Log: Removing files to prep for cleanup and reorganization to presentation directory Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R 2014-04-28 21:43:21 UTC (rev 3378) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R 2014-05-01 05:55:08 UTC (rev 3379) @@ -1,45 +0,0 @@ -library(PerformanceAnalytics) - -source("data_prep.R") - -##### Equity Data for Example 1 and Example 2 ##### -colors <- c(rep("blue", 15), rep("green", 15), rep("red", 5)) -sd.order <- order(StdDev(equity.data)) - -# boxplot to compare return distributions -# mar(bottom, left, top, right) -# default: par(mar=c(5, 4, 4, 2) + 0.1) -png("data_figures/equity_box.png") -boxplot(coredata(equity.data[,sd.order]), - cex.axis=0.8, las=3, ylab="Returns", pch=18, - col=colors[sd.order], - main="Return Distribution\n(sorted by StdDev)") -legend("topleft", legend=c("Large Cap", "Mid Cap", "Small Cap"), - fill=c("blue", "green", "red"), bty="n", cex=0.8) -dev.off() - -##### edhec Data for Example 3 and Example 4 ##### -p <- 0.95 - -png("data_figures/relative_barvar.png") -charts.BarVaR(R[,1:3], width=60, methods=c("ModifiedES", "ModifiedVaR"), - main="Relative Value") -dev.off() - -png("data_figures/directional_barvar.png") -charts.BarVaR(R[,4:6], width=60, methods=c("ModifiedES", "ModifiedVaR"), - main="Directional") -dev.off() - - -colors <- c(rep("lightblue", 3), rep("red", 3)) -ES.order <- order(ES(R, p=p, invert=FALSE)) - -png("data_figures/edhec_box.png") -boxplot(coredata(R[,ES.order]), - cex.axis=0.8, las=3, ylab="Returns", pch=18, - col=colors[ES.order], - main="Return Distribution\n(sorted by Modified ES (95%))") -legend("topleft", legend=c("Relative Value", "Directional"), - fill=c("lightblue", "red"), bty="n", cex=0.8) -dev.off() Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R 2014-04-28 21:43:21 UTC (rev 3378) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R 2014-05-01 05:55:08 UTC (rev 3379) @@ -1,25 +0,0 @@ - -##### Equity Data for Example 1 and Example 2 ##### -load("data/crsp_weekly.rda") - -equity.data <- cbind(largecap_weekly[,1:15], - midcap_weekly[,1:15], - smallcap_weekly[,1:5]) -market <- largecap_weekly[,21] -Rf <- largecap_weekly[,22] - -##### edhec Data for Example 3 and Example 4 ##### -# Load the updated edhec dataset -load("data/edhec.rda") - -# Prep data for Examples 3 and 4 -R <- edhec[,c("Convertible.Arbitrage", "Equity.Market.Neutral", - "Fixed.Income.Arbitrage", - "CTA.Global", "Emerging.Markets", "Global.Macro")] -# Abreviate column names for convenience and plotting -colnames(R) <- c("CA", "EMN", "FIA", "CTAG", "EM", "GM") - - -# clean up and remove the data we don't need -rm(largecap_weekly, midcap_weekly, smallcap_weekly, microcap_weekly) -rm(edhec) Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/edhec.rda =================================================================== (Binary files differ) Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/edhec_eda.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/edhec_eda.R 2014-04-28 21:43:21 UTC (rev 3378) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/edhec_eda.R 2014-05-01 05:55:08 UTC (rev 3379) @@ -1,78 +0,0 @@ -# script for data analysis - -library(PerformanceAnalytics) -library(lattice) -library(corrplot) - -load("data/edhec.rda") - -head(edhec) -R <- edhec[,1:4] -p <- 0.95 - -first(R) -last(R) - -# plot the timeseries of returns -# plot(as.zoo(edhec)) -xyplot(R, scales=list(y="same")) -charts.BarVaR(R, width=36, methods=c("ModifiedES", "ModifiedVaR")) -dev.off() - -# boxplot to compare return distributions -# mar(bottom, left, top, right) -# default: par(mar=c(5, 4, 4, 2) + 0.1) -par(mar=c(10, 4, 4, 2) + 0.1) -boxplot(coredata(R[,order(ES(R, p=p, invert=FALSE))]), - cex.axis=0.8, las=3, ylab="Returns", pch=18, - main="Return Distribution\n(sorted by Modified ES (95%))") -par(mar=c(5, 4, 4, 2) + 0.1) -dev.off() - -# head(R[,order(ES(R, invert=FALSE))]) -# head(R[,order(StdDev(R))]) -# chart.Boxplot(R[,order(ES(R, invert=FALSE))]) -# chart.Boxplot(R[,order(StdDev(R))]) -# boxplot(coredata(R), col=c(2:5), cex.names=0.8, las=3) - -# chart the distribution of returns -for(i in 1:ncol(R)){ - chart.Histogram(R[,i], methods=c("add.density", "add.normal"), - colorset=c("lightgray", "black", "blue")) - legend("topleft", legend=c("kernel density estimate", "normal"), - lty=c(1,1), col=c("black", "blue"), bty="n") - Sys.sleep(1) -} - - -# chart the correlation and covariance -# from http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html -cor.mtest <- function(mat, conf.level = 0.95) { - mat <- as.matrix(mat) - n <- ncol(mat) - p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n) - diag(p.mat) <- 0 - diag(lowCI.mat) <- diag(uppCI.mat) <- 1 - for (i in 1:(n - 1)) { - for (j in (i + 1):n) { - tmp <- cor.test(mat[, i], mat[, j], conf.level = conf.level) - p.mat[i, j] <- p.mat[j, i] <- tmp$p.value - lowCI.mat[i, j] <- lowCI.mat[j, i] <- tmp$conf.int[1] - uppCI.mat[i, j] <- uppCI.mat[j, i] <- tmp$conf.int[2] - } - } - return(list(p.mat, lowCI.mat, uppCI.mat)) -} -res <- cor.mtest(R) - -corrplot(cor(R), p.mat=res[[1]], main="Correlation", - sig.level=0.05, tl.cex=0.8) - -# corrplot(M, method="number", bg="gray", tl.cex=0.8) -# corrplot.mixed(M, bg="gray", tl.cex=0.8) - -# If I compare sample min variance portfolio to a ledoit-shrinkage or robust, -# I should use plotcov to compare covaiance matrices - - - Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile 2014-04-28 21:43:21 UTC (rev 3378) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile 2014-05-01 05:55:08 UTC (rev 3379) @@ -1,63 +0,0 @@ -# http://robjhyndman.com/hyndsight/makefiles/ -# https://www.cs.umd.edu/class/fall2002/cmsc214/Tutorial/makefile.html - -# List the R files used -RFILES := data_prep.R data_analysis.R optimize.R optimization_analysis.R - -# Rout indicator files to show R file has run -# R CMD BATCH will generate .Rout files after running -OUT_FILES:= $(RFILES:.R=.Rout) - - -all: $(OUT_FILES) slidy_presentation.html presentation.Rmd - -# Generate slidy presentation from markdown file -slidy_presentation.html: $(RFILES) $(OUT_FILES) presentation.md - pandoc -t slidy -s --mathjax presentation.md -o slidy_presentation.html - -# Generate slidy presentation from markdown file -slides.pdf: $(RFILES) $(OUT_FILES) presentation.md - pandoc -t -S beamer ?-slide-level 2 presentation.md -o slides.pdf - -# Generate markdown file from R markdown file -presentation.md: presentation.Rmd - Rscript -e "library(knitr); knit('presentation.Rmd')" - -# Data analysis script -data_analysis.Rout: data_analysis.R - R CMD BATCH --vanilla data_analysis.R - -# Optimization analysis script to analyze results of optimization -optimization_analysis.Rout: optimization_analysis.R optimize.R - R CMD BATCH --vanilla optimization_analysis.R - -# Run optimizations -optimize.Rout: optimize.R - R CMD BATCH --vanilla optimize.R - -# Data prep -data_prep.Rout: data_prep.R - R CMD BATCH --vanilla data_prep.R - -lwShrink.Rout: R/lwShrink.R - R CMD BATCH --vanilla R/lwShrink.R - -charting.Rout: R/charting.R - R CMD BATCH --vanilla R/charting.R - -# Use Rscript to run the necessary R files as an alternative to R CMD BATCH -runR: - Rscript data_prep.R - Rscript data_analysis.R - Rscript optimize.R - Rscript optimization_analysis.R - -clean: - rm -f *.Rout - rm -f data_figures/*.png - rm -f optimization_figures/*.png - rm -f optimization_results/*.rda - rm -f *.md - rm -f *.html - rm -f cache/* - \ No newline at end of file Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R 2014-04-28 21:43:21 UTC (rev 3378) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R 2014-05-01 05:55:08 UTC (rev 3379) @@ -1,199 +0,0 @@ -library(PortfolioAnalytics) -library(methods) - -source("R/charting.R") - -# Set the directory where the optimization results are saved -results.dir <- "optimization_results" -figures.dir <- "optimization_figures" - - -##### Example 1 ##### -load(paste(results.dir, "opt.minVarSample.rda", sep="/")) -load(paste(results.dir, "opt.minVarLW.rda", sep="/")) - -# Chart the weights through time -png(paste(figures.dir, "weights_minVarSample.png", sep="/")) -chart.Weights(opt.minVarSample, main="minVarSample Weights", legend.loc=NULL) -dev.off() - -w1 <- nvd3WeightsPlot(opt.minVarSample) -save(w1, file=paste(figures.dir, "w1.rda", sep="/")) - - -png(paste(figures.dir, "weights_minVarLW.png", sep="/")) -chart.Weights(opt.minVarLW, main="minVarLW Weights", legend.loc=NULL) -dev.off() - -w2 <- nvd3WeightsPlot(opt.minVarLW) -save(w2, file=paste(figures.dir, "w2.rda", sep="/")) - -# Compute the returns and chart the performance summary -ret.minVarSample <- summary(opt.minVarSample)$portfolio_returns -ret.minVarRobust <- summary(opt.minVarLW)$portfolio_returns -ret.minVar <- cbind(ret.minVarSample, ret.minVarRobust) -colnames(ret.minVar) <- c("Sample", "LW") - -png(paste(figures.dir, "ret_minVar.png", sep="/")) -charts.PerformanceSummary(ret.minVar) -dev.off() - -##### Example 2 ##### -load(paste(results.dir, "opt.dn.rda", sep="/")) - -png(paste(figures.dir, "opt_dn.png", sep="/")) -plot(opt.dn, main="Dollar Neutral Portfolio", risk.col="StdDev", neighbors=10) -dev.off() - - -# chart.RiskReward(opt, risk.col="StdDev", neighbors=25) -# chart.Weights(opt, plot.type="bar", legend.loc=NULL) -# wts <- extractWeights(opt) -# t(wts) %*% betas -# sum(abs(wts)) -# sum(wts[wts > 0]) -# sum(wts[wts < 0]) -# sum(wts != 0) - -##### Example 3 ##### -load(file=paste(results.dir, "opt.minES.rda", sep="/")) -load(file=paste(results.dir, "bt.opt.minES.rda", sep="/")) - -# ES(R, portfolio_method="component", weights=extractWeights(opt.minES[[1]])) -# extractObjectiveMeasures(opt.minES) - -# extract objective measures, out, and weights -xtract <- extractStats(opt.minES) - -# get the 'mean' and 'ES' columns from each element of the list -xtract.mean <- unlist(lapply(xtract, function(x) x[,"mean"])) -xtract.ES <- unlist(lapply(xtract, function(x) x[,"ES"])) - - -png(paste(figures.dir, "opt_minES.png", sep="/")) -# plot the feasible space -par(mar=c(7,4,4,1)+0.1) -plot(xtract.ES, xtract.mean, col="gray", - main="Minimum ES Portfolios", - xlab="ES", ylab="Mean", - ylim=c(0.005, 0.007), - xlim=c(0.015, 0.085)) - -# min ES -points(x=opt.minES[[1]]$objective_measures$ES$MES, - y=opt.minES[[1]]$objective_measures$mean, - pch=15, col="purple") -text(x=opt.minES[[1]]$objective_measures$ES$MES, - y=opt.minES[[1]]$objective_measures$mean, - labels="Min ES", pos=1, col="purple", cex=0.8) - -# min ES with risk budget upper limit on component contribution to risk -points(x=opt.minES[[2]]$objective_measures$ES$MES, - y=opt.minES[[2]]$objective_measures$mean, - pch=15, col="black") -text(x=opt.minES[[2]]$objective_measures$ES$MES, - y=opt.minES[[2]]$objective_measures$mean, - labels="Min ES RB", pos=4, col="black", cex=0.8) - -# min ES with equal (i.e. min concentration) component contribution to risk -points(x=opt.minES[[3]]$objective_measures$ES$MES, - y=opt.minES[[3]]$objective_measures$mean, - pch=15, col="darkgreen") -text(x=opt.minES[[3]]$objective_measures$ES$MES, - y=opt.minES[[3]]$objective_measures$mean, - labels="Min ES EqRB", pos=4, col="darkgreen", cex=0.8) -par(mar=c(5,4,4,1)+0.1) -dev.off() - -# Chart the risk contribution -#chart.RiskBudget(opt.minES[[1]], risk.type="percentage", neighbors=10) -png(paste(figures.dir, "rb_minES.png", sep="/")) -chart.RiskBudget(opt.minES[[2]], main="Risk Budget Limit", - risk.type="percentage", neighbors=10) -dev.off() - -png(paste(figures.dir, "eqrb_minES.png", sep="/")) -chart.RiskBudget(opt.minES[[3]], main="Equal ES Component Contribution", - risk.type="percentage", neighbors=10) -dev.off() - -# Plot the risk contribution of portfolio 1 through time -png(paste(figures.dir, "risk_minES.png", sep="/")) -chart.RiskBudget(bt.opt.minES[[1]], main="Min ES Risk Contribution", - risk.type="percentage") -dev.off() -# Plot the risk contribution of portfolio 1 through time -png(paste(figures.dir, "weights_minES.png", sep="/")) -chart.Weights(bt.opt.minES[[1]], main="Min ES Weights") -dev.off() - -# Plot the risk contribution of portfolio 3 through time -png(paste(figures.dir, "risk_minESRB.png", sep="/")) -chart.RiskBudget(bt.opt.minES[[2]], main="Min ES RB Risk Contribution", - risk.type="percentage") -dev.off() -# Plot the weights of portfolio 2 through time -png(paste(figures.dir, "weights_minESRB.png", sep="/")) -chart.Weights(bt.opt.minES[[2]], main="Min ES RB Weights") -dev.off() - -# Plot the risk contribution of portfolio 3 through time -png(paste(figures.dir, "risk_minESEqRB.png", sep="/")) -chart.RiskBudget(bt.opt.minES[[3]], main="Min ES EqRB Risk Contribution", - risk.type="percentage") -dev.off() -# Plot the weights of portfolio 3 through time -png(paste(figures.dir, "weights_minESEqRB.png", sep="/")) -chart.Weights(bt.opt.minES[[3]], main="Min ES EqRB Weights") -dev.off() - -# Extract the returns from each element and chart the performance summary -ret.bt.opt <- do.call(cbind, lapply(bt.opt.minES, - function(x) summary(x)$portfolio_returns)) -colnames(ret.bt.opt) <- c("min ES", "min ES RB", "min ES Eq RB") - -png(paste(figures.dir, "ret_minES.png", sep="/")) -charts.PerformanceSummary(ret.bt.opt) -dev.off() - -### -# interactive plot of risk budgets through time using nvd3 -# nvd3RiskPlot(bt.opt.minES[[1]]) -# nvd3RiskPlot(bt.opt.minES[[2]]) -# nvd3RiskPlot(bt.opt.minES[[3]]) -### - -##### Example 4 ##### -load(file=paste(results.dir, "opt.crra.rda", sep="/")) -load(file=paste(results.dir, "bt.opt.crra.rda", sep="/")) - -CRRA <- function(R, weights, lambda, sigma, m3, m4){ - weights <- matrix(weights, ncol=1) - M2.w <- t(weights) %*% sigma %*% weights - M3.w <- t(weights) %*% m3 %*% (weights %x% weights) - M4.w <- t(weights) %*% m4 %*% (weights %x% weights %x% weights) - term1 <- 0.5 * lambda * M2.w - term2 <- (1 / 6) * lambda * (lambda + 1) * M3.w - term3 <- (1 / 24) * lambda * (lambda + 1) * (lambda + 2) * M4.w - out <- -term1 + term2 - term3 - out -} - -# Chart the optimization in Risk-Reward space -png(paste(figures.dir, "crra_RR_ES.png", sep="/")) -chart.RiskReward(opt.crra, risk.col="ES") -# dev.off() - -png(paste(figures.dir, "crra_RR_StdDev.png", sep="/")) -chart.RiskReward(opt.crra, risk.col="StdDev") -dev.off() - -# Compute the portfolio returns with rebalancing -ret.crra <- summary(bt.opt.crra)$portfolio_returns -colnames(ret.crra) <- "CRRA" - -# Plot the performance summary of the returns from example 3 and CRRA -png(paste(figures.dir, "ret_crra.png", sep="/")) -charts.PerformanceSummary(cbind(ret.bt.opt, ret.crra), main="Optimization Performance") -dev.off() - Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R 2014-04-28 21:43:21 UTC (rev 3378) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R 2014-05-01 05:55:08 UTC (rev 3379) @@ -1,449 +0,0 @@ -# script used to run the portfolio optimizations - -# Examples to consider -# Example 1: Consider a portfolio of stocks. Full investment and long -# only (or box) constraints. Objective to minimize portfolio variance. -# Demonstrate a custom moments function to compare a sample covariance -# matrix estimate and a robust covariance matrix estimate. An alternative -# to a MCD estimate is ledoit-wolf shrinkage, DCC GARCH model, -# factor model, etc. - -# Example 2: Consider a portfolio of stocks. Dollar neutral, beta -# neutral, box constraints, and leverage_exposure constraints. Objective -# to minimize portfolio StdDev. This will demonstrate some of the -# more advanced constraint types. Could also introduce position limit -# constraints here in this example. - -# Example 3: Consider an allocation to hedge funds using the -# EDHEC-Risk Alternative Index as a proxy. This will be an extended -# example starting with an objective to minimize portfolio expected -# shortfall, then risk budget percent contribution limit, then equal -# risk contribution limit. - -# Example 4: Consider an allocation to hedge funds using the -# EDHEC-Risk Alternative Index as a proxy. - -# Option 1 for example 4 -# Objective to maximize a risk adjusted return measure -# (e.g.Calmar Ratio, Sterling Ratio, Sortino Ratio, or Upside Potential -# Ratio) - -# I prefer doing this option -# Option 2 for example 4 -# Objective to maximize the -# fourth order expansion of the Constant Relative Risk Aversion (CRRA) -# expected utility function. Demonstrate a custom moment function and -# a custom objective function. - -# Set the directory to save the optimization results -results.dir <- "optimization_results" - -# Load the packages -library(PortfolioAnalytics) -library(foreach) -library(ROI) -library(ROI.plugin.quadprog) - -# for running via Rscript -library(methods) - -# Source in the lwShrink function -source("R/lwShrink.R") - -# Example 1 and Example 2 will use the crsp_weekly data -# Example 3 and Example 4 will use the edhec data -source("data_prep.R") - - -##### Example 1 ##### -stocks <- colnames(equity.data) -# Specify an initial portfolio -portf.init <- portfolio.spec(stocks) -# Add constraints -# weights sum to 1 -portf.minvar <- add.constraint(portf.init, type="full_investment") -# box constraints -portf.minvar <- add.constraint(portf.minvar, type="box", min=0.01, max=0.45) - -# Add objective -# objective to minimize portfolio variance -portf.minvar <- add.objective(portf.minvar, type="risk", name="var") - -# Backtesting parameters -# Set rebalancing frequency -rebal.freq <- "quarters" -# Training Period -training <- 400 -# Trailing Period -trailing <- 250 - -# Run optimization -# Sample Covariance Matrix Estimate - -# By default, momentFUN uses set.portfolio.moments which computes the sample -# moment estimates - -cat("Example 1: running minimum variance with sample covariance matrix - estimate backtest\n") -if(file.exists(paste(results.dir, "opt.minVarSample.rda", sep="/"))){ - cat("file already exists\n") -} else { - opt.minVarSample <- optimize.portfolio.rebalancing(equity.data, portf.minvar, - optimize_method="ROI", - rebalance_on=rebal.freq, - training_period=training, - trailing_periods=trailing) - cat("opt.minVarSample complete. Saving results to ", results.dir, "\n") - save(opt.minVarSample, file=paste(results.dir, "opt.minVarSample.rda", sep="/")) -} - -# Custom moment function to use Ledoit-Wolf shinkage covariance matrix estimate -lw.sigma <- function(R, ...){ - out <- list() - # estimate covariance matrix via robust covariance matrix estimate, - # ledoit-wolf shrinkage, GARCH, factor model, etc. - # set.seed(1234) - # out$sigma <- MASS::cov.rob(R, method="mcd", ...)$cov - out$sigma <- lwShrink(R)$cov - #print(index(last(R))) - return(out) -} - -cat("Example 1: running minimum variance with Ledoit-Wolf shrinkage covariance - matrix estimate backtest\n") -if(file.exists(paste(results.dir, "opt.minVarLW.rda", sep="/"))){ - cat("file already exists\n") -} else{ - # Using Ledoit-Wolf Shrinkage Covariance Matrix Estimate - opt.minVarLW <- optimize.portfolio.rebalancing(equity.data, portf.minvar, - optimize_method="ROI", - momentFUN=lw.sigma, - rebalance_on=rebal.freq, - training_period=training, - trailing_periods=trailing) - cat("opt.minVarLW complete. Saving results to ", results.dir, "\n") - save(opt.minVarLW, file=paste(results.dir, "opt.minVarLW.rda", sep="/")) -} - -##### Example 2 ##### -portf.init <- portfolio.spec(stocks) - -# weights sum to 0 -portf.dn <- add.constraint(portf.init, type="weight_sum", - min_sum=-0.01, max_sum=0.01) - -# Add box constraints such that no stock has weight less than -20% or -# greater than 20% -portf.dn <- add.constraint(portf.dn, type="box", - min=-0.2, max=0.2) -# Add position limit constraint such that the portfolio has a maximum -# of 20 non-zero positions -portf.dn <- add.constraint(portf.dn, type="position_limit", max_pos=20) - -# Compute the betas of each stock -betas <- t(CAPM.beta(equity.data, market, Rf)) - -# Add factor exposure constraint to limit portfolio beta -portf.dn <- add.constraint(portf.dn, type="factor_exposure", B=betas, - lower=-0.25, upper=0.25) -# portf.dn <- add.constraint(portf.dn, type="leverage_exposure", leverage=2) - -# generate random portfolios -if(file.exists(paste(results.dir, "rp.rda", sep="/"))){ - cat("random portfolios already generated\n") -} else { - cat("generating random portfolios\n") - rp <- random_portfolios(portf.dn, 10000, eliminate=TRUE) - cat("random portfolios generated. Saving rp to ", results.dir, "\n") - save(rp, file=paste(results.dir, "rp.rda", sep="/")) -} - -# Add objective to maximize return -portf.dn.StdDev <- add.objective(portf.dn, type="return", name="mean", - target=0.0015) -# Add objective to target a portfolio standard deviation of 2% -portf.dn.StdDev <- add.objective(portf.dn.StdDev, type="risk", name="StdDev", - target=0.02) - -cat("Example 2: running dollar neutral optimization\n") -if(file.exists(paste(results.dir, "opt.dn.rda", sep="/"))){ - cat("file already exists\n") -} else { - # Run optimization - opt.dn <- optimize.portfolio(equity.data, portf.dn.StdDev, - optimize_method="random", rp=rp, - trace=TRUE) - cat("opt.dn complete. Saving results to ", results.dir, "\n") - save(opt.dn, file=paste(results.dir, "opt.dn.rda", sep="/")) -} - -##### Example 3 ##### -# Example 3 will consider three portfolios -# - minES -# - minES with component contribution limit -# - minES with equal risk contribution - -funds <- colnames(R) -portf.init <- portfolio.spec(funds) -portf.init <- add.constraint(portf.init, type="weight_sum", - min_sum=0.99, max_sum=1.01) - -portf.init <- add.constraint(portf.init, type="box", - min=0.05, max=0.4) - -# Set multiplier=0 so that it is calculated, but does not affect the optimization -portf.init <- add.objective(portf.init, type="return", - name="mean", multiplier=0) - -# Add objective to minimize expected shortfall -portf.minES <- add.objective(portf.init, type="risk", name="ES") - -# Add risk budget objective with upper limit on percentage contribution -portf.minES.RB <- add.objective(portf.minES, type="risk_budget", - name="ES", max_prisk=0.3) - -# Relax the box constraint -portf.minES.RB$constraints[[2]]$max <- rep(1,ncol(R)) -# print.default(portf.minES.RB$constraints[[2]]) - -# Add risk budget objective to minimize concentration of percentage component -# contribution to risk. Concentration is defined as the Herfindahl-Hirschman -# Index (HHI). $\sum_i x_i^2$ -portf.minES.EqRB <- add.objective(portf.minES, type="risk_budget", - name="ES", min_concentration=TRUE) -# relax the box constraint -portf.minES.EqRB <- add.constraint(portf.minES.EqRB, type="box", - min=0.05, max=1, indexnum=2) -# portf.minES.RB$constraints[[2]]$max <- rep(1,ncol(R)) -# print.default(portf.minES.EqRB$constraints[[2]]) - -# Add risk budget objective to minES portfolio with multiplier=0 so that it -# is calculated, but does not affect optimization -portf.minES <- add.objective(portf.minES, type="risk_budget", - name="ES", multiplier=0) - -# Combine the portfolios so we can make a single call to -# optimize.portfolio -portf <- combine.portfolios(list(minES=portf.minES, - minES.RB=portf.minES.RB, - minES.EqRB=portf.minES.EqRB)) - -cat("Example 3: running minimum ES optimizations\n") -if(file.exists(paste(results.dir, "opt.minES.rda", sep="/"))){ - cat("file already exists\n") -} else { - # Run the optimization - opt.minES <- optimize.portfolio(R, portf, optimize_method="DEoptim", - search_size=5000, trace=TRUE, traceDE=0, - message=TRUE) - cat("opt.minES complete. Saving results to ", results.dir, "\n") - save(opt.minES, file=paste(results.dir, "opt.minES.rda", sep="/")) -} - -# Now we want to evaluate the optimization through time - -# Rebalancing parameters -# Set rebalancing frequency -rebal.freq <- "quarters" -# Training Period -training <- 120 -# Trailing Period -trailing <- 72 - -cat("Example 3: running minimum ES backtests\n") -if(file.exists(paste(results.dir, "bt.opt.minES.rda", sep="/"))){ - cat("file already exists\n") -} else { - # Backtest - bt.opt.minES <- optimize.portfolio.rebalancing(R, portf, - optimize_method="DEoptim", - rebalance_on=rebal.freq, - training_period=training, - trailing_periods=trailing, - search_size=5000, - traceDE=0, message=TRUE) - cat("bt.opt.minES complete. Saving results to ", results.dir, "\n") - save(bt.opt.minES, file=paste(results.dir, "bt.opt.minES.rda", sep="/")) -} - -##### Example 4 ##### - -# Simple function to compute the moments used in CRRA -crra.moments <- function(R, ...){ - out <- list() - out$mu <- colMeans(R) - out$sigma <- cov(R) - out$m3 <- PerformanceAnalytics:::M3.MM(R) - out$m4 <- PerformanceAnalytics:::M4.MM(R) - out -} - - -# Fourth order expansion of CRRA expected utility -CRRA <- function(R, weights, lambda, sigma, m3, m4){ - weights <- matrix(weights, ncol=1) - M2.w <- t(weights) %*% sigma %*% weights - M3.w <- t(weights) %*% m3 %*% (weights %x% weights) - M4.w <- t(weights) %*% m4 %*% (weights %x% weights %x% weights) - term1 <- 0.5 * lambda * M2.w - term2 <- (1 / 6) * lambda * (lambda + 1) * M3.w - term3 <- (1 / 24) * lambda * (lambda + 1) * (lambda + 2) * M4.w - out <- -term1 + term2 - term3 - out -} - -# test the CRRA function -portf.crra <- portfolio.spec(funds) -portf.crra <- add.constraint(portf.crra, type="weight_sum", - min_sum=0.99, max_sum=1.01) - -portf.crra <- add.constraint(portf.crra, type="box", - min=0.05, max=0.4) - -portf.crra <- add.objective(portf.crra, type="return", - name="CRRA", arguments=list(lambda=10)) - -# I just want these for plotting -# Set multiplier=0 so that it is calculated, but does not affect the optimization -portf.crra <- add.objective(portf.crra, type="return", name="mean", multiplier=0) -portf.crra <- add.objective(portf.crra, type="risk", name="ES", multiplier=0) -portf.crra <- add.objective(portf.crra, type="risk", name="StdDev", multiplier=0) - -cat("Example 4: running maximum CRRA optimization\n") -if(file.exists(paste(results.dir, "opt.crra.rda", sep="/"))){ - cat("file already exists\n") -} else { - # Run the optimization - opt.crra <- optimize.portfolio(R, portf.crra, optimize_method="DEoptim", - search_size=5000, trace=TRUE, traceDE=0, - momentFUN="crra.moments") - cat("opt.crra complete. Saving results to ", results.dir, "\n") - save(opt.crra, file=paste(results.dir, "opt.crra.rda", sep="/")) -} - -cat("Example 4: running maximum CRRA backtest\n") -if(file.exists(paste(results.dir, "bt.opt.crra.rda", sep="/"))){ - cat("file already exists\n") -} else { - # Run the optimization with rebalancing - bt.opt.crra <- optimize.portfolio.rebalancing(R, portf.crra, - optimize_method="DEoptim", - search_size=5000, trace=TRUE, - traceDE=0, - momentFUN="crra.moments", - rebalance_on=rebal.freq, - training_period=training, - trailing_periods=trailing) - cat("bt.opt.crra complete. Saving results to ", results.dir, "\n") - save(bt.opt.crra, file=paste(results.dir, "bt.opt.crra.rda", sep="/")) -} - -##### RP Demo ##### -cat("Random portfolio method comparison\n") -if(file.exists("optimization_figures/rp_plot.png")){ - cat("file already exists\n") -} else { - portf.lo <- portfolio.spec(colnames(R)) - portf.lo <- add.constraint(portf.lo, type="weight_sum", - min_sum=0.99, max_sum=1.01) - - portf.lo <- add.constraint(portf.lo, type="long_only") - - # Use the long only portfolio previously created - # Generate random portfolios using the 3 methods - rp1 <- random_portfolios(portf.lo, permutations=5000, - rp_method='sample') - rp2 <- random_portfolios(portf.lo, permutations=5000, - rp_method='simplex') - rp3 <- random_portfolios(portf.lo, permutations=5000, - rp_method='grid') - - # Calculate the portfolio mean return and standard deviation - rp1_mean <- apply(rp1, 1, function(x) mean(R %*% x)) - rp1_StdDev <- apply(rp1, 1, function(x) StdDev(R, weights=x)) - rp2_mean <- apply(rp2, 1, function(x) mean(R %*% x)) - rp2_StdDev <- apply(rp2, 1, function(x) StdDev(R, weights=x)) - rp3_mean <- apply(rp3, 1, function(x) mean(R %*% x)) - rp3_StdDev <- apply(rp3, 1, function(x) StdDev(R, weights=x)) - - x.assets <- StdDev(R) - y.assets <- colMeans(R) - ### - # create an interactive plot using rCharts and nvd3 scatterChart - # tmp1 <- data.frame(name="sample", mean=rp1_mean, sd=rp1_StdDev) - # tmp2 <- data.frame(name="simplex", mean=rp2_mean, sd=rp2_StdDev) - # tmp3 <- data.frame(name="grid", mean=rp3_mean, sd=rp3_StdDev) - # tmp <- rbind(tmp1, tmp2, tmp3) - # n1 <- nPlot(mean ~ sd, group="name", data=tmp, type="scatterChart") - # n1 - ### - x.lower <- min(x.assets) * 0.9 - x.upper <- max(x.assets) * 1.1 - y.lower <- min(y.assets) * 0.9 - y.upper <- max(y.assets) * 1.1 - - png("optimization_figures/rp_plot.png") - # plot feasible portfolios - plot(x=rp1_StdDev, y=rp1_mean, col="gray", main="Random Portfolio Methods", - ylab="mean", xlab="StdDev", xlim=c(x.lower, x.upper), - ylim=c(y.lower, y.upper)) - points(x=rp2_StdDev, y=rp2_mean, col="red", pch=2) - points(x=rp3_StdDev, y=rp3_mean, col="green", pch=5) - points(x=x.assets, y=y.assets) - text(x=x.assets, y=y.assets, labels=colnames(R), pos=4, cex=0.8) - legend("bottomright", legend=c("sample", "simplex", "grid"), - col=c("gray", "red", "green"), - pch=c(1, 2, 5), bty="n") - dev.off() -} - -cat("Random portfolio simplex method fev biasing\n") -if(file.exists("optimization_figures/fev_plot.png")){ - cat("file already exists\n") -} else { - png("optimization_figures/fev_plot.png") - fev <- 0:5 - x.assets <- StdDev(R) - y.assets <- colMeans(R) - par(mfrow=c(2, 3)) - for(i in 1:length(fev)){ - rp <- rp_simplex(portfolio=portf.lo, permutations=2000, fev=fev[i]) - tmp.mean <- apply(rp, 1, function(x) mean(R %*% x)) - tmp.StdDev <- apply(rp, 1, function(x) StdDev(R=R, weights=x)) - x.lower <- min(c(tmp.StdDev, x.assets)) * 0.85 - x.upper <- max(c(tmp.StdDev, x.assets)) * 1.15 - y.lower <- min(c(tmp.mean, y.assets)) * 0.85 - y.upper <- max(c(tmp.mean, y.assets)) * 1.15 - plot(x=tmp.StdDev, y=tmp.mean, main=paste("FEV =", fev[i]), - ylab="mean", xlab="StdDev", col=rgb(0, 0, 100, 50, maxColorValue=255), - xlim=c(x.lower, x.upper), - ylim=c(y.lower, y.upper)) - points(x=x.assets, y=y.assets) - text(x=x.assets, y=y.assets, labels=colnames(R), pos=4, cex=0.8) - } - par(mfrow=c(1,1)) - dev.off() -} - -# # Calculate the turnover per period -# turnover.rebalancing <- function(object){ -# weights <- extractWeights(object) -# n <- nrow(weights) -# out <- vector("numeric", n) -# out[1] <- NA -# for(i in 2:n){ [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3379 From noreply at r-forge.r-project.org Thu May 1 08:00:59 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 1 May 2014 08:00:59 +0200 (CEST) Subject: [Returnanalytics-commits] r3380 - in pkg/PortfolioAnalytics/sandbox/RFinance2014: . R data figures optimization_results Message-ID: <20140501060059.C7B881851BF@r-forge.r-project.org> Author: rossbennett34 Date: 2014-05-01 08:00:59 +0200 (Thu, 01 May 2014) New Revision: 3380 Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/ pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md pkg/PortfolioAnalytics/sandbox/RFinance2014/data/ pkg/PortfolioAnalytics/sandbox/RFinance2014/data/crsp_weekly.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.csv pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/data/parse_edhec.R pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/ pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/bt_rb3.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/bt_w3.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/crra_RR_ES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/crra_RR_StdDev.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/directional_barvar.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/edhec_box.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/eqrb_minES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/equity_box.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/fev_plot.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/opt_dn.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/opt_minES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/rb_minES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/relative_barvar.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/ret_crra.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/ret_minES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/ret_minVar.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/risk_minES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/risk_minESEqRB.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/risk_minESRB.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/rp_plot.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/rp_viz.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/w1.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/w2.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/weights_crra.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/weights_minES.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/weights_minESEqRB.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/weights_minESRB.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/weights_minVarLW.png pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/weights_minVarSample.png pkg/PortfolioAnalytics/sandbox/RFinance2014/index.html pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.crra.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/bt.opt.minES.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.crra.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.dn.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minES.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarLW.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/opt.minVarSample.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/rp.rda pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd pkg/PortfolioAnalytics/sandbox/RFinance2014/slidy_presentation.html Log: Checking in files for presentation after reorganization Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/R/charting.R 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,99 @@ +nvd3WeightsPlot <- function(object, + type=c("stackedAreaChart", "multiBarChart") + ){ + type <- match.arg(type) + + # extract the weights and turn into a data.frame + weights <- extractWeights(object) + weights.df <- reshape2::melt( + data.frame(date=format(index(weights)), weights), + id.vars = 1, + variable.name = "stock", + value.name = "weight" + ) + weights.df$date <- as.Date(weights.df$date) + + # plot + n1 <- rCharts::nPlot( + weight ~ date, + group = "stock", + data = weights.df, + type = type + ) + n1$xAxis( + tickFormat = "#!function(d){ + return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000)) + }!#" + ) + n1$yAxis( + tickFormat = "#!function(d){ + return d3.format('0.2%')(d) + }!#" + ) + return(n1) +} + +nvd3RiskPlot <- function(object, + type=c("stackedAreaChart", "multiBarChart") + ){ + type <- match.arg(type) + + # extract the risk budget pct_contrib and turn into a data.frame + tmp <- extractObjectiveMeasures(object) + rb <- tmp[,grep("pct_contrib", colnames(tmp))] + colnames(rb) <- gsub("^.*\\.", "", colnames(rb)) + rb.df <- reshape2::melt( + data.frame(date=as.Date(format(index(rb))), rb), + id.vars = 1, + variable.name = "fund", + value.name = "risk" + ) + + # plot + n1 <- rCharts::nPlot( + risk ~ date, + group = "fund", + data = rb.df, + type = type + ) + n1$xAxis( + tickFormat = "#!function(d){ + return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000)) + }!#" + ) + n1$yAxis( + tickFormat = "#!function(d){ + return d3.format('0.2%')(d) + }!#" + ) + return(n1) +} + +# require(rCharts) +# weights <- extractWeights(opt.minVarSample) +# weights.df <- reshape2::melt( +# data.frame( +# date=format(index(weights)), +# weights +# ), +# id.vars = 1, +# variable.name = "stock", +# value.name = "weight" +# ) +# +# d1 <- dPlot( +# weight ~ date, +# groups = "stock", +# data = weights.df, +# type = "bubble" #area, bar, or bubble +# ) +# d1$xAxis( +# type = "addTimeAxis", +# inputFormat = "%Y-%m-%d", +# outputFormat = "%b %Y" +# ) +# d1$yAxis( +# outputFormat = "0.2%", +# orderBy = "weight" +# ) +# d1 \ No newline at end of file Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/R/lwShrink.R 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,54 @@ +lwShrink <- function(x, shrink=NULL){ + # port of matlab code from http://www.econ.uzh.ch/faculty/wolf/publications.html#9 + # Ledoit, O. and Wolf, M. (2004). + # Honey, I shrunk the sample covariance matrix. + # Journal of Portfolio Management 30, Volume 4, 110-119. + + # De-mean returns + n <- nrow(x) + p <- ncol(x) + meanx <- colMeans(x) + x <- x - matrix(rep(meanx, n), ncol=p, byrow=TRUE) + + # Compute sample covariance matrix using the de-meaned returns + sample <- (1 / n) * (t(x) %*% x) + + # Compute prior + var <- matrix(diag(sample), ncol=1) + sqrtvar <- sqrt(var) + tmpMat <- matrix(rep(sqrtvar, p), nrow=p) + rBar <- (sum(sum(sample / (tmpMat * t(tmpMat)))) - p) / (p * (p - 1)) + prior <- rBar * tmpMat * t(tmpMat) + diag(prior) <- var + + if(is.null(shrink)){ + # What is called pi-hat + y <- x^2 + phiMat <- t(y) %*% y / n - 2 * (t(x) %*% x) * sample / n + sample^2 + phi <- sum(phiMat) + + # What is called rho-hat + term1 <- (t(x^3) %*% x) / n + help <- t(x) %*% x / n + helpDiag <- matrix(diag(help), ncol=1) + term2 <- matrix(rep(helpDiag, p), ncol=p, byrow=FALSE) * sample + term3 <- help * matrix(rep(var, p), ncol=p, byrow=FALSE) + term4 <- matrix(rep(var, p), ncol=p, byrow=FALSE) * sample + thetaMat <- term1 - term2 - term3 + term4 + diag(thetaMat) <- 0 + rho <- sum(diag(phiMat)) + rBar * sum(sum(((1 / sqrtvar) %*% t(sqrtvar)) * thetaMat)) + + # What is called gamma-hat + gamma <- norm(sample - prior, "F")^2 + + # Compute shrinkage constant + kappa <- (phi - rho) / gamma + shrinkage <- max(0, min(1, kappa / n)) + } else { + shrinkage <- shrink + } + # Compute the estimator + sigma <- shrinkage * prior + (1 - shrinkage) * sample + out <- list(cov=sigma, prior=prior, shrinkage=shrinkage) + return(out) +} Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,17 @@ +PortfolioAnalyticsPresentation +============================== + +Repository for exploring ways to develop html presentation for the PortfolioAnalytics package, primarily for RFinance 2014. + +This repo has two branches +* master +* gh-pages + +Only work on the master branch. The gh-pages branch is used to view the generated presentation as index.html. + +http://oli.jp/2011/github-pages-workflow/ +you can push your local master branch to the gh-pages branch on GitHub + +``` +git push -f origin master:gh-pages +``` Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/crsp_weekly.rda =================================================================== (Binary files differ) Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/crsp_weekly.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.csv =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.csv (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.csv 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,206 @@ +date;Convertible Arbitrage;CTA Global;Distressed Securities;Emerging Markets;Equity Market Neutral;Event Driven;Fixed Income Arbitrage;Global Macro;Long/Short Equity;Merger Arbitrage;Relative Value;Short Selling;Funds Of Funds +31/01/1997;1.19%;3.93%;1.78%;7.91%;1.89%;2.13%;1.91%;5.73%;2.81%;1.50%;1.80%;-1.66%;3.17% +28/02/1997;1.23%;2.98%;1.22%;5.25%;1.01%;0.84%;1.22%;1.75%;-0.06%;0.34%;1.18%;4.26%;1.06% +31/03/1997;0.78%;-0.21%;-0.12%;-1.20%;0.16%;-0.23%;1.09%;-1.19%;-0.84%;0.60%;0.10%;7.78%;-0.77% +30/04/1997;0.86%;-1.70%;0.30%;1.19%;1.19%;-0.05%;1.30%;1.72%;0.84%;-0.01%;1.22%;-1.29%;0.09% +31/05/1997;1.56%;-0.15%;2.33%;3.15%;1.89%;3.46%;1.18%;1.08%;3.94%;1.97%;1.73%;-7.37%;2.75% +30/06/1997;2.12%;0.85%;2.17%;5.81%;1.65%;2.58%;1.08%;2.18%;2.23%;2.31%;1.98%;-0.65%;2.25% +31/07/1997;1.93%;5.91%;2.34%;5.60%;2.47%;3.07%;0.95%;7.38%;4.54%;2.00%;1.81%;-4.29%;4.35% +31/08/1997;1.34%;-4.73%;1.47%;-0.66%;0.17%;0.71%;0.87%;-1.80%;1.07%;0.79%;1.03%;-0.72%;0.51% +30/09/1997;1.22%;1.98%;3.50%;2.29%;2.02%;3.29%;1.19%;2.90%;4.29%;1.97%;1.83%;-1.55%;3.34% +31/10/1997;1.00%;-0.98%;-0.64%;-5.72%;0.95%;0.61%;-0.32%;-1.42%;0.10%;0.94%;0.79%;5.72%;-0.99% +30/11/1997;0.00%;1.33%;0.54%;-3.78%;0.41%;1.34%;0.53%;1.06%;-0.26%;2.23%;1.11%;2.17%;-0.34% +31/12/1997;0.68%;2.86%;0.73%;1.60%;0.66%;1.54%;0.79%;2.64%;1.04%;1.58%;0.82%;1.61%;0.89% +31/01/1998;1.45%;1.04%;0.95%;-4.29%;0.60%;0.55%;-0.26%;-0.50%;0.13%;0.55%;1.32%;0.14%;-0.36% +28/02/1998;1.46%;-0.65%;2.27%;3.39%;1.35%;2.94%;0.98%;1.28%;3.42%;2.12%;1.30%;1.55%;2.56% +31/03/1998;1.44%;1.22%;2.52%;3.18%;1.79%;2.63%;1.28%;5.70%;3.36%;1.64%;1.45%;6.37%;3.73% +30/04/1998;1.26%;-2.96%;1.65%;0.41%;0.67%;1.04%;0.75%;0.34%;1.20%;1.39%;1.45%;6.57%;1.25% +31/05/1998;0.56%;1.93%;0.06%;-8.25%;0.80%;-0.83%;0.40%;0.95%;-0.87%;-0.09%;0.53%;14.37%;-0.72% +30/06/1998;-0.06%;0.51%;-0.47%;-4.22%;1.08%;0.02%;-0.80%;1.20%;1.67%;0.72%;0.26%;-0.53%;0.21% +31/07/1998;0.60%;-0.10%;-0.69%;0.19%;0.12%;-0.37%;1.06%;0.58%;-0.06%;0.07%;0.11%;3.43%;-0.07% +31/08/1998;-3.19%;6.91%;-8.36%;-19.22%;-1.07%;-8.86%;-1.43%;-2.63%;-5.52%;-5.44%;-3.41%;24.63%;-6.16% +30/09/1998;-1.96%;4.54%;-2.15%;-3.95%;0.61%;-1.10%;-3.62%;-0.59%;2.06%;0.76%;0.05%;-3.76%;-0.37% +31/10/1998;-2.14%;0.04%;-0.29%;1.40%;0.52%;0.91%;-8.01%;-2.23%;1.69%;1.59%;-1.40%;-10.77%;-0.02% +30/11/1998;2.69%;-0.89%;1.64%;4.30%;1.58%;2.44%;0.52%;1.94%;2.91%;2.20%;1.98%;-7.56%;2.20% +31/12/1998;1.13%;2.21%;1.08%;-0.98%;2.09%;2.19%;1.20%;2.33%;4.08%;2.24%;1.64%;-5.31%;2.22% +31/01/1999;2.19%;-1.67%;1.81%;-1.20%;1.01%;2.01%;1.58%;0.86%;2.58%;1.12%;1.95%;-6.65%;2.02% +28/02/1999;0.82%;1.97%;-0.21%;1.02%;0.23%;-0.42%;2.08%;-1.11%;-1.69%;0.36%;0.85%;8.33%;-0.63% +31/03/1999;1.36%;-0.65%;1.59%;5.85%;0.33%;1.93%;1.60%;0.24%;2.29%;1.33%;1.16%;-1.54%;2.13% +30/04/1999;2.43%;2.10%;4.18%;6.30%;1.07%;4.29%;1.06%;3.29%;3.12%;2.18%;2.38%;-3.75%;4.00% +31/05/1999;1.66%;-1.50%;2.07%;0.61%;0.89%;2.15%;0.72%;-0.55%;0.95%;2.10%;1.46%;0.09%;1.19% +30/06/1999;1.02%;2.34%;2.73%;6.54%;1.68%;2.97%;0.88%;2.14%;3.15%;2.22%;1.48%;-4.12%;2.82% +31/07/1999;1.01%;-0.51%;0.84%;-0.61%;1.35%;0.96%;0.51%;-0.18%;1.77%;1.47%;1.10%;0.92%;0.88% +31/08/1999;0.48%;-0.27%;0.20%;-1.47%;0.95%;-0.27%;-0.28%;-0.61%;0.22%;0.50%;0.62%;4.68%;0.28% +30/09/1999;0.96%;0.64%;-0.41%;-0.69%;0.95%;0.90%;0.92%;-0.02%;1.13%;1.16%;1.05%;4.01%;0.52% +31/10/1999;0.45%;-3.54%;0.27%;2.88%;0.66%;0.54%;0.87%;0.73%;2.12%;0.96%;0.70%;-1.30%;1.30% +30/11/1999;1.24%;1.66%;2.20%;6.92%;1.33%;2.84%;1.06%;4.05%;4.81%;2.37%;1.37%;-12.39%;4.83% +31/12/1999;1.40%;1.42%;3.00%;12.30%;1.98%;2.86%;0.97%;6.12%;7.45%;0.90%;1.83%;-11.37%;6.22% +31/01/2000;2.27%;1.28%;0.88%;0.77%;0.75%;0.88%;0.41%;0.21%;0.75%;1.43%;1.73%;4.27%;1.69% +29/02/2000;2.67%;-0.22%;4.21%;5.28%;2.53%;3.46%;0.97%;4.08%;6.99%;2.39%;1.85%;-13.40%;6.66% +31/03/2000;2.43%;-1.38%;1.03%;3.18%;1.34%;0.69%;-0.61%;-1.04%;0.06%;1.31%;1.63%;-2.30%;0.39% +30/04/2000;2.23%;-2.41%;-1.01%;-5.41%;1.68%;-0.59%;-0.06%;-3.04%;-2.01%;1.88%;0.92%;10.28%;-2.69% +31/05/2000;1.49%;1.14%;-1.32%;-4.33%;0.62%;-0.34%;1.07%;-0.70%;-0.97%;1.46%;0.80%;7.04%;-1.22% +30/06/2000;1.79%;-1.24%;2.03%;3.34%;1.71%;2.68%;0.58%;1.54%;3.49%;1.67%;1.76%;-11.07%;3.11% +31/07/2000;0.93%;-1.31%;0.64%;0.25%;0.63%;0.57%;0.18%;0.37%;0.06%;1.16%;0.84%;5.53%;-0.22% +31/08/2000;1.62%;1.89%;1.40%;3.68%;2.10%;1.73%;1.07%;2.48%;3.45%;1.57%;1.57%;-11.35%;2.67% +30/09/2000;1.41%;-2.08%;-0.19%;-4.62%;0.58%;0.48%;0.76%;-1.49%;-0.16%;1.37%;0.75%;12.04%;-0.69% +31/10/2000;0.52%;0.75%;-0.73%;-2.56%;0.40%;-0.68%;0.06%;-0.24%;-0.84%;0.26%;-0.04%;7.84%;-1.04% +30/11/2000;-0.81%;4.25%;-2.09%;-3.85%;0.45%;-1.36%;0.66%;1.25%;-1.53%;1.02%;0.06%;16.57%;-2.05% +31/12/2000;-0.02%;6.82%;0.01%;1.16%;1.60%;1.27%;0.48%;4.72%;2.48%;1.25%;0.75%;0.63%;1.33% +31/01/2001;3.44%;0.25%;3.08%;5.86%;0.75%;2.98%;1.63%;2.14%;1.65%;1.11%;3.33%;-2.71%;2.23% +28/02/2001;1.82%;-0.16%;1.00%;-2.21%;1.20%;0.45%;0.54%;-0.72%;-2.64%;0.54%;0.30%;10.21%;-0.89% +31/03/2001;1.62%;4.38%;-0.37%;-1.75%;1.08%;-0.42%;0.51%;0.38%;-1.99%;-0.61%;-0.11%;6.20%;-0.68% +30/04/2001;1.57%;-3.62%;0.48%;1.14%;0.75%;1.10%;0.94%;0.49%;2.46%;0.58%;1.74%;-9.91%;1.04% +31/05/2001;0.33%;0.81%;2.35%;2.78%;0.77%;1.85%;0.68%;0.32%;0.43%;1.61%;1.41%;-1.30%;0.80% +30/06/2001;0.12%;-0.77%;3.60%;1.60%;0.17%;0.63%;0.17%;0.17%;0.19%;-0.87%;0.19%;1.10%;0.13% +31/07/2001;0.91%;-0.40%;0.73%;-2.86%;0.31%;0.49%;0.54%;-0.40%;-1.44%;0.79%;0.10%;3.53%;-0.40% +31/08/2001;1.42%;1.53%;1.06%;0.30%;0.94%;0.90%;1.05%;0.06%;-0.96%;0.99%;-0.31%;7.52%;0.19% +30/09/2001;0.78%;2.46%;-0.14%;-4.25%;0.23%;-2.54%;-0.13%;-0.70%;-3.48%;-2.67%;-2.21%;9.41%;-1.42% +31/10/2001;1.17%;3.36%;1.03%;2.78%;0.58%;1.48%;1.34%;2.08%;0.99%;0.85%;1.64%;-2.98%;0.95% +30/11/2001;0.80%;-5.43%;0.86%;4.83%;0.55%;1.05%;-0.24%;0.21%;2.00%;0.14%;1.36%;-6.55%;0.58% +31/12/2001;-0.94%;1.48%;0.15%;4.21%;0.56%;1.07%;0.53%;1.38%;1.80%;0.45%;0.97%;-2.51%;0.99% +31/01/2002;1.48%;-0.72%;1.86%;2.73%;0.65%;0.78%;0.86%;0.69%;-0.37%;0.77%;0.97%;3.43%;0.30% +28/02/2002;-0.49%;-2.02%;-0.33%;1.81%;-0.07%;-0.71%;0.56%;-0.35%;-1.23%;-0.44%;-0.11%;3.90%;-0.15% +31/03/2002;0.53%;0.09%;0.52%;3.31%;0.47%;1.53%;0.45%;0.64%;1.55%;0.73%;1.45%;-4.46%;0.90% +30/04/2002;0.96%;-1.04%;1.39%;1.44%;0.76%;0.46%;1.13%;0.98%;-0.42%;-0.13%;0.70%;4.83%;0.52% +31/05/2002;0.33%;2.70%;0.91%;0.01%;0.53%;0.01%;0.99%;1.23%;-0.34%;0.00%;0.31%;3.46%;0.50% +30/06/2002;0.04%;6.55%;-1.17%;-2.92%;0.22%;-2.83%;0.69%;-0.22%;-2.49%;-1.70%;-1.07%;5.48%;-0.95% +31/07/2002;-1.59%;4.13%;-1.33%;-3.09%;-0.13%;-3.00%;0.57%;-0.78%;-3.89%;-1.74%;-1.85%;6.44%;-1.40% +31/08/2002;0.50%;2.20%;0.09%;1.19%;0.69%;0.60%;0.97%;0.63%;0.41%;0.61%;0.58%;0.15%;0.37% +30/09/2002;1.46%;2.84%;-0.44%;-2.52%;0.15%;-0.70%;-0.33%;0.54%;-1.60%;-0.28%;-1.10%;7.31%;-0.33% +31/10/2002;1.04%;-3.76%;-0.31%;1.54%;0.16%;0.31%;-0.63%;-0.86%;1.23%;0.32%;0.84%;-4.05%;-0.31% +30/11/2002;2.51%;-1.64%;2.39%;1.90%;0.25%;2.16%;0.54%;0.47%;2.24%;0.54%;1.85%;-5.47%;1.06% +31/12/2002;1.57%;4.89%;2.22%;0.48%;0.94%;0.44%;1.53%;1.92%;-1.49%;0.46%;0.23%;4.43%;0.77% +31/01/2003;2.83%;4.41%;2.43%;0.12%;0.83%;1.54%;1.06%;1.82%;0.05%;0.40%;0.67%;1.62%;0.72% +28/02/2003;1.33%;4.02%;0.92%;0.84%;0.24%;0.26%;0.79%;1.66%;-0.37%;0.18%;-0.04%;1.30%;0.31% +31/03/2003;0.89%;-4.45%;1.13%;0.19%;0.15%;0.83%;0.19%;-1.22%;0.20%;-0.07%;0.49%;-0.75%;-0.04% +30/04/2003;1.50%;0.65%;3.45%;4.50%;0.31%;2.72%;0.91%;1.17%;2.98%;0.99%;1.86%;-6.56%;1.34% +31/05/2003;1.36%;4.90%;2.70%;4.33%;1.07%;3.01%;2.07%;3.97%;3.62%;1.54%;2.12%;-4.99%;2.05% +30/06/2003;-0.58%;-1.92%;2.67%;2.68%;0.34%;1.81%;0.44%;0.56%;1.28%;0.48%;0.71%;-1.62%;0.68% +31/07/2003;-0.72%;-1.71%;1.17%;1.04%;-0.06%;1.19%;-0.92%;-0.35%;1.18%;0.53%;0.41%;-3.61%;0.25% +31/08/2003;-0.87%;0.78%;1.37%;3.74%;0.31%;1.33%;0.43%;2.02%;1.79%;0.70%;0.58%;-3.54%;0.78% +30/09/2003;1.71%;-0.19%;2.42%;2.64%;0.78%;1.33%;1.05%;2.15%;0.94%;0.77%;0.86%;1.36%;1.21% +31/10/2003;1.46%;1.04%;2.67%;2.59%;1.15%;1.91%;0.35%;1.11%;2.99%;1.11%;1.59%;-6.56%;1.52% +30/11/2003;0.92%;0.18%;1.54%;0.96%;0.46%;1.16%;0.69%;0.31%;1.30%;0.44%;1.02%;-1.36%;0.70% +31/12/2003;0.54%;3.81%;1.98%;4.03%;0.54%;1.72%;1.01%;2.93%;1.91%;0.98%;1.27%;-1.78%;1.39% +31/01/2004;1.19%;1.99%;3.01%;2.51%;1.09%;2.34%;0.92%;1.17%;1.92%;0.97%;1.46%;-0.90%;1.56% +29/02/2004;0.17%;5.29%;0.75%;2.53%;0.63%;1.13%;0.84%;1.50%;1.23%;0.51%;0.57%;0.18%;1.11% +31/03/2004;0.61%;-0.51%;0.46%;1.72%;0.32%;0.16%;0.03%;0.64%;0.41%;0.17%;0.38%;-1.48%;0.43% +30/04/2004;0.20%;-5.32%;0.93%;-2.52%;-0.82%;0.02%;0.62%;-1.78%;-1.65%;-0.39%;-0.45%;3.84%;-0.68% +31/05/2004;-1.28%;-1.18%;-0.10%;-1.81%;0.24%;-0.23%;0.40%;-0.81%;-0.35%;0.00%;-0.37%;-0.24%;-0.82% +30/06/2004;-1.06%;-3.16%;2.02%;0.20%;0.42%;1.13%;0.55%;-0.19%;0.91%;0.17%;0.22%;-0.51%;0.34% +31/07/2004;0.13%;-1.19%;0.19%;-0.27%;0.06%;-0.82%;0.62%;-0.14%;-1.54%;-0.92%;0.07%;6.38%;-0.49% +31/08/2004;0.40%;-0.84%;0.88%;1.33%;-0.09%;0.35%;0.36%;-0.39%;-0.22%;0.11%;0.31%;1.26%;-0.10% +30/09/2004;-0.17%;2.20%;1.04%;2.80%;0.85%;1.03%;0.12%;0.08%;2.10%;0.42%;0.52%;-2.16%;0.99% +31/10/2004;-0.44%;3.58%;1.43%;1.85%;-0.05%;1.24%;0.28%;1.38%;0.74%;0.74%;0.40%;-0.92%;0.68% +30/11/2004;0.81%;4.75%;3.37%;3.28%;1.40%;3.06%;0.75%;2.80%;3.08%;1.64%;1.49%;-5.74%;2.44% +31/12/2004;0.56%;0.00%;2.66%;2.01%;0.58%;2.44%;0.60%;0.33%;1.78%;1.33%;0.99%;-3.91%;1.45% +31/01/2005;-0.96%;-4.38%;0.37%;1.43%;0.81%;0.04%;0.44%;-0.47%;-0.17%;0.00%;0.12%;3.87%;0.06% +28/02/2005;-0.58%;0.05%;1.34%;3.46%;0.80%;1.44%;0.85%;1.71%;2.10%;0.65%;0.81%;1.18%;1.36% +31/03/2005;-1.40%;-0.06%;0.32%;-1.97%;0.19%;-0.04%;0.24%;-0.27%;-0.96%;0.32%;-0.42%;2.44%;-0.44% +30/04/2005;-3.16%;-3.54%;-0.52%;-0.49%;-0.30%;-1.28%;-0.03%;-0.80%;-1.84%;-1.05%;-1.08%;3.93%;-1.41% +31/05/2005;-1.33%;2.32%;0.06%;0.72%;0.47%;0.65%;-0.10%;0.88%;1.15%;0.95%;-0.02%;-4.75%;0.18% +30/06/2005;1.07%;2.60%;1.33%;1.60%;0.81%;1.33%;0.10%;1.16%;1.95%;0.85%;0.95%;-0.32%;1.31% +31/07/2005;1.64%;-0.13%;1.73%;2.57%;0.78%;2.15%;0.81%;1.19%;2.65%;1.15%;1.49%;-2.42%;1.34% +31/08/2005;0.66%;1.00%;1.24%;1.52%;0.62%;0.92%;0.36%;0.83%;0.97%;0.61%;0.53%;2.59%;0.79% +30/09/2005;1.42%;0.79%;1.12%;4.02%;0.87%;1.00%;0.62%;2.69%;2.22%;0.35%;1.22%;1.98%;1.47% +31/10/2005;-0.15%;-0.92%;-0.32%;-2.30%;0.01%;-1.73%;0.57%;-0.74%;-1.74%;-1.45%;-0.38%;2.33%;-1.49% +30/11/2005;0.04%;3.79%;1.00%;2.79%;0.61%;1.25%;0.15%;1.64%;2.11%;1.12%;0.67%;-3.00%;1.60% +31/12/2005;0.92%;-1.53%;1.22%;2.84%;0.68%;1.42%;0.54%;1.35%;2.49%;1.38%;1.26%;-0.35%;1.91% +31/01/2006;2.50%;1.74%;2.53%;5.26%;1.15%;3.41%;0.93%;2.58%;3.81%;2.72%;2.38%;-2.88%;2.86% +28/02/2006;1.16%;-1.86%;0.65%;1.61%;0.46%;0.51%;0.41%;0.02%;0.16%;1.04%;0.73%;0.64%;0.37% +31/03/2006;1.07%;2.84%;1.72%;1.22%;0.98%;1.85%;0.55%;0.94%;2.38%;1.44%;1.57%;-1.39%;1.64% +30/04/2006;0.64%;3.87%;1.93%;3.65%;1.02%;1.64%;1.21%;2.38%;1.72%;1.19%;1.26%;-0.12%;1.71% +31/05/2006;0.91%;-1.46%;0.86%;-3.89%;0.02%;0.08%;0.59%;-1.55%;-2.48%;0.09%;-0.25%;2.46%;-1.33% +30/06/2006;0.12%;-1.42%;-0.15%;-0.97%;0.63%;0.12%;0.36%;-0.15%;-0.62%;0.87%;0.21%;1.18%;-0.28% +31/07/2006;0.66%;-2.16%;0.09%;0.67%;0.51%;-0.11%;0.64%;0.06%;-0.31%;0.58%;0.17%;1.73%;-0.05% +31/08/2006;0.98%;0.20%;0.99%;1.33%;-0.09%;1.12%;0.37%;-0.39%;1.14%;0.53%;0.92%;-1.56%;0.66% +30/09/2006;0.93%;-0.55%;0.33%;0.11%;0.09%;0.35%;0.14%;-0.67%;0.05%;0.41%;0.40%;-2.36%;-0.03% +31/10/2006;0.54%;1.02%;1.94%;2.57%;0.65%;2.06%;0.67%;0.97%;1.94%;1.32%;1.32%;-3.80%;1.63% +30/11/2006;0.92%;2.26%;1.79%;3.23%;0.75%;1.82%;0.60%;1.99%;2.00%;1.42%;1.29%;-2.68%;1.85% +31/12/2006;1.27%;1.46%;1.65%;2.91%;1.07%;1.68%;0.72%;1.16%;1.53%;1.33%;1.28%;0.39%;1.75% +31/01/2007;1.30%;1.13%;1.50%;0.79%;0.83%;2.01%;0.69%;0.61%;1.21%;1.91%;1.35%;-1.07%;1.21% +28/02/2007;1.17%;-1.44%;1.45%;1.00%;0.51%;2.07%;1.06%;0.18%;0.82%;2.55%;1.14%;0.28%;0.96% +31/03/2007;0.60%;-1.41%;1.08%;1.85%;1.01%;1.46%;0.60%;0.27%;1.15%;0.63%;0.81%;-0.51%;0.96% +30/04/2007;0.26%;2.41%;1.64%;2.55%;0.89%;1.97%;0.71%;1.52%;1.98%;1.60%;1.34%;-2.65%;1.63% +31/05/2007;1.10%;2.30%;1.80%;2.70%;1.21%;2.13%;0.55%;1.92%;2.24%;1.71%;1.56%;-1.99%;2.04% +30/06/2007;0.11%;2.29%;0.27%;2.36%;0.77%;-0.07%;0.48%;1.07%;0.77%;-0.53%;1.00%;2.36%;0.82% +31/07/2007;-0.53%;-1.22%;-0.56%;2.75%;0.51%;-0.32%;0.07%;1.16%;0.09%;-0.54%;0.04%;4.86%;0.41% +31/08/2007;-1.45%;-2.80%;-1.18%;-2.74%;-0.94%;-1.44%;-0.48%;-1.16%;-1.60%;0.01%;-0.77%;0.92%;-2.22% +30/09/2007;1.61%;4.69%;0.95%;4.28%;1.23%;1.34%;1.64%;3.30%;2.56%;1.31%;1.53%;-2.07%;1.99% +31/10/2007;1.77%;2.80%;1.75%;4.85%;1.68%;2.14%;1.14%;3.04%;2.81%;1.91%;2.00%;-0.26%;3.03% +30/11/2007;-1.31%;-0.16%;-1.69%;-2.37%;-0.18%;-2.02%;-0.94%;-0.63%;-2.25%;-1.49%;-1.12%;7.19%;-1.48% +31/12/2007;-0.77%;1.17%;0.02%;1.30%;0.54%;0.07%;0.36%;1.04%;0.43%;-0.25%;0.22%;0.56%;0.40% +31/01/2008;-0.09%;2.55%;-2.33%;-5.03%;-1.12%;-2.71%;-0.12%;-0.10%;-4.00%;-1.26%;-1.18%;5.56%;-2.72% +29/02/2008;-0.83%;6.20%;0.14%;2.80%;1.20%;0.84%;-0.49%;3.12%;1.40%;0.60%;0.64%;3.00%;1.42% +31/03/2008;-3.17%;-0.56%;-1.26%;-3.79%;-0.49%;-1.68%;-3.06%;-1.69%;-2.36%;-0.45%;-1.62%;1.92%;-2.62% +30/04/2008;0.76%;-0.78%;0.88%;1.90%;0.59%;1.18%;1.87%;0.78%;2.23%;1.49%;1.30%;-4.61%;0.97% +31/05/2008;1.07%;1.62%;1.37%;1.63%;1.26%;1.76%;1.03%;1.14%;2.27%;1.36%;1.59%;-1.42%;1.72% +30/06/2008;-0.81%;3.30%;-0.31%;-2.74%;1.56%;-1.13%;-0.27%;0.30%;-1.64%;-1.09%;-0.84%;7.51%;-0.68% +31/07/2008;-1.88%;-3.33%;-1.82%;-3.30%;-1.00%;-1.66%;-0.23%;-2.13%;-2.61%;0.11%;-1.25%;0.72%;-2.64% +31/08/2008;-0.66%;-1.14%;-0.72%;-3.36%;-1.35%;-0.25%;-0.03%;-1.33%;-1.46%;0.51%;-0.23%;-2.15%;-1.56% +30/09/2008;-10.27%;0.10%;-5.18%;-9.82%;-2.85%;-6.27%;-5.06%;-3.13%;-6.75%;-2.76%;-5.38%;3.78%;-6.18% +31/10/2008;-12.37%;3.45%;-7.75%;-13.31%;-0.44%;-6.25%;-8.67%;-1.57%;-6.29%;-2.45%;-6.92%;11.70%;-6.00% +30/11/2008;-2.76%;2.14%;-4.35%;-3.91%;-5.87%;-3.01%;-3.08%;0.33%;-1.88%;0.06%;-2.09%;4.28%;-1.92% +31/12/2008;1.77%;1.40%;-1.97%;-0.10%;0.05%;-0.71%;-0.35%;1.18%;0.81%;1.62%;0.31%;-1.46%;-1.19% +31/01/2009;4.91%;-0.16%;0.82%;-1.12%;0.79%;1.32%;1.12%;0.29%;-0.17%;0.56%;1.00%;2.82%;0.60% +28/02/2009;1.64%;-0.31%;-1.22%;-1.33%;-0.46%;-0.91%;0.65%;-0.55%;-1.61%;0.06%;-0.16%;3.28%;-0.37% +31/03/2009;2.35%;-1.80%;0.22%;3.50%;0.21%;1.17%;0.57%;0.48%;1.88%;1.25%;1.00%;-4.62%;0.08% +30/04/2009;5.00%;-1.40%;3.87%;6.63%;-0.12%;3.37%;2.21%;1.27%;3.75%;0.81%;3.42%;-8.20%;0.92% +31/05/2009;5.78%;2.13%;5.04%;8.84%;1.46%;4.42%;3.65%;3.48%;5.16%;1.07%;3.92%;0.08%;3.12% +30/06/2009;2.41%;-1.47%;1.98%;0.13%;0.36%;1.23%;1.26%;-0.76%;0.09%;1.04%;1.01%;-0.94%;0.24% +31/07/2009;6.11%;-0.12%;3.11%;4.51%;0.42%;2.91%;3.22%;1.66%;2.77%;0.68%;2.60%;-5.96%;1.53% +31/08/2009;3.15%;0.54%;2.44%;1.66%;0.70%;2.07%;2.02%;0.50%;1.57%;1.02%;1.62%;-1.65%;1.13% +30/09/2009;3.68%;1.51%;4.10%;5.36%;0.85%;3.36%;3.25%;2.31%;2.85%;1.10%;2.20%;-3.94%;1.71% +31/10/2009;1.19%;-1.47%;1.39%;1.08%;-0.05%;0.43%;1.85%;-0.04%;-0.86%;0.26%;0.32%;3.14%;-0.21% +30/11/2009;0.80%;3.32%;2.02%;1.51%;0.09%;1.52%;0.96%;1.65%;1.30%;0.68%;0.89%;-2.27%;0.82% +31/12/2009;2.15%;-2.53%;3.24%;2.29%;0.72%;2.35%;1.41%;-0.28%;1.86%;1.02%;1.61%;-3.73%;0.66% +31/01/2010;0.53%;-2.78%;1.87%;-0.78%;0.28%;0.77%;1.72%;-0.84%;-0.95%;0.48%;0.60%;1.83%;-0.36% +28/02/2010;0.36%;0.90%;0.31%;-0.19%;0.50%;0.76%;0.23%;0.47%;0.84%;0.57%;0.57%;-2.61%;0.13% +31/03/2010;2.29%;2.75%;3.36%;4.21%;0.77%;2.73%;1.36%;1.71%;2.87%;1.09%;1.79%;-4.96%;1.71% +30/04/2010;1.99%;1.00%;2.51%;1.33%;0.18%;1.64%;1.13%;0.76%;1.00%;0.38%;1.22%;-2.87%;0.85% +31/05/2010;-2.44%;-2.48%;-2.50%;-4.80%;-0.50%;-2.57%;-1.02%;-1.28%;-3.71%;-1.15%;-1.86%;4.45%;-2.72% +30/06/2010;0.17%;0.11%;-1.05%;-0.39%;-0.45%;-1.06%;0.78%;-0.23%;-1.61%;0.23%;-0.34%;4.19%;-0.79% +31/07/2010;2.27%;-0.80%;1.43%;2.96%;0.90%;1.70%;1.00%;0.33%;1.91%;1.27%;1.74%;-4.26%;0.69% +31/08/2010;1.21%;3.10%;-0.49%;0.28%;-0.44%;-0.32%;0.88%;1.08%;-0.96%;0.70%;0.31%;3.89%;0.06% +30/09/2010;1.89%;2.67%;2.17%;4.29%;1.60%;2.72%;1.32%;2.63%;4.08%;1.34%;2.15%;-8.26%;2.19% +31/10/2010;2.14%;3.11%;2.06%;2.32%;1.05%;1.87%;1.07%;1.59%;2.08%;0.47%;1.49%;-1.79%;1.48% +30/11/2010;-0.12%;-2.24%;0.65%;-0.49%;0.44%;0.28%;0.56%;-0.47%;0.66%;-0.25%;0.37%;-1.62%;-0.09% +31/12/2010;1.45%;4.36%;3.11%;2.26%;0.94%;2.60%;0.55%;2.50%;3.42%;1.16%;1.57%;-5.07%;2.05% +31/01/2011;1.81%;-0.63%;1.73%;-0.65%;0.56%;1.41%;1.81%;-0.55%;0.52%;0.93%;0.97%;-0.76%;0.13% +28/02/2011;1.62%;1.77%;1.44%;0.11%;0.59%;1.29%;1.03%;0.95%;1.39%;0.62%;1.12%;-3.14%;0.83% +31/03/2011;0.38%;-1.64%;0.43%;1.54%;0.80%;0.20%;0.22%;-0.28%;0.21%;0.31%;0.34%;-1.70%;-0.18% +30/04/2011;0.20%;3.67%;1.29%;1.40%;1.05%;1.14%;0.97%;2.11%;1.39%;0.89%;0.72%;-1.97%;1.14% +31/05/2011;-0.17%;-3.39%;-0.14%;-1.91%;-0.37%;-0.52%;0.33%;-1.50%;-1.08%;-0.11%;-0.05%;1.34%;-1.16% +30/06/2011;-0.91%;-2.39%;-0.68%;-1.00%;-0.14%;-1.38%;-0.10%;-1.30%;-1.17%;-0.14%;-0.56%;2.70%;-1.38% +31/07/2011;-0.33%;2.58%;-0.15%;0.77%;-0.03%;-0.30%;0.18%;1.29%;-0.30%;-0.49%;-0.06%;1.99%;0.34% +31/08/2011;-1.95%;0.07%;-4.02%;-3.90%;-1.61%;-4.01%;-0.85%;-0.63%;-4.21%;-1.19%;-2.00%;6.69%;-2.52% +30/09/2011;-1.90%;-0.57%;-3.70%;-6.95%;-1.59%;-3.41%;-0.48%;-1.42%;-4.61%;-1.02%;-1.97%;7.77%;-2.62% +31/10/2011;1.29%;-3.17%;2.37%;3.65%;1.61%;2.98%;0.63%;0.53%;3.90%;1.72%;1.47%;-7.21%;0.94% +30/11/2011;-0.94%;0.14%;-1.08%;-2.72%;0.02%;-0.58%;-0.34%;-0.66%;-1.31%;0.17%;-0.24%;1.31%;-0.93% +31/12/2011;0.29%;0.34%;0.50%;-1.81%;0.06%;-0.34%;0.45%;-0.22%;-0.56%;0.56%;0.12%;0.41%;-0.54% +31/01/2012;2.36%;0.46%;3.24%;3.95%;0.95%;2.88%;1.16%;1.90%;3.27%;0.95%;2.02%;-6.79%;1.47% +29/02/2012;2.18%;0.91%;2.02%;3.41%;0.71%;1.70%;1.19%;1.34%;2.48%;1.11%;1.72%;-5.22%;1.40% +31/03/2012;0.65%;-2.04%;0.91%;-1.33%;0.23%;0.58%;0.61%;-0.61%;0.33%;0.24%;0.55%;-1.23%;0.01% +30/04/2012;-0.17%;-0.03%;-0.12%;-0.27%;-0.13%;-0.18%;0.34%;-0.59%;-0.68%;-0.11%;-0.20%;0.57%;-0.33% +31/05/2012;-0.77%;2.59%;-1.86%;-5.31%;-1.15%;-1.91%;-0.03%;-0.67%;-3.75%;-0.48%;-1.00%;6.77%;-1.40% +30/06/2012;0.72%;-2.72%;-0.09%;0.26%;0.06%;0.07%;0.46%;-0.63%;0.60%;0.23%;0.70%;-2.58%;-0.37% +31/07/2012;0.92%;3.12%;0.89%;0.81%;0.41%;0.48%;1.25%;1.44%;0.39%;0.06%;1.17%;0.87%;0.76% +31/08/2012;0.76%;-0.82%;1.61%;0.75%;0.49%;1.29%;0.82%;0.37%;1.08%;0.44%;0.95%;-3.67%;0.68% +30/09/2012;0.57%;-1.04%;1.69%;2.73%;0.43%;1.20%;0.76%;0.51%;1.57%;0.06%;1.02%;-3.85%;0.73% +31/10/2012;0.17%;-3.10%;1.18%;0.28%;0.28%;0.48%;0.58%;-0.83%;0.09%;-0.79%;0.30%;0.05%;-0.25% +30/11/2012;0.41%;-0.04%;0.82%;1.31%;0.37%;0.80%;0.54%;0.27%;0.52%;1.00%;0.56%;-1.50%;0.46% +31/12/2012;0.98%;0.57%;2.59%;3.30%;0.37%;1.93%;0.73%;1.11%;1.45%;1.45%;1.17%;-3.87%;1.08% +31/01/2013;1.58%;1.86%;2.19%;3.03%;1.35%;2.14%;1.16%;1.65%;3.08%;-0.16%;2.04%;-4.52%;2.06% +28/02/2013;0.09%;-0.99%;0.52%;-0.12%;0.33%;0.41%;0.56%;-0.12%;0.37%;0.39%;0.47%;-0.35%;0.32% +31/03/2013;0.77%;0.89%;1.49%;0.68%;0.35%;1.43%;1.13%;0.64%;1.44%;0.69%;1.30%;-1.89%;0.93% +30/04/2013;0.52%;1.92%;1.75%;0.63%;0.08%;0.78%;0.50%;1.14%;0.64%;0.61%;0.55%;-2.86%;0.76% +31/05/2013;1.34%;-2.61%;2.23%;0.33%;0.24%;1.87%;0.50%;-0.23%;1.35%;0.59%;1.01%;-2.45%;0.67% +30/06/2013;-0.81%;-2.73%;-1.05%;-3.21%;0.28%;-1.13%;-1.22%;-1.76%;-0.94%;-0.22%;-1.02%;0.56%;-1.33% +31/07/2013;0.60%;-0.76%;1.40%;0.75%;1.00%;1.49%;0.67%;0.16%;2.15%;1.03%;1.17%;-3.69%;0.91% +31/08/2013;0.46%;-1.39%;-0.34%;-1.22%;-0.59%;-0.11%;0.14%;-0.91%;-0.76%;-0.01%;-0.46%;1.07%;-0.68% +30/09/2013;0.43%;-0.57%;1.64%;2.35%;0.63%;1.60%;0.47%;0.69%;2.33%;0.84%;1.40%;-4.52%;1.27% +31/10/2013;0.95%;1.45%;1.61%;2.38%;1.42%;1.45%;0.85%;0.94%;2.04%;0.45%;1.45%;-2.07%;1.25% +30/11/2013;0.07%;1.14%;1.22%;0.30%;1.05%;1.19%;0.67%;0.69%;1.54%;0.30%;0.87%;-1.65%;1.09% +31/12/2013;0.48%;0.52%;1.20%;1.01%;0.76%;1.22%;0.40%;0.65%;1.57%;0.61%;1.02%;-1.55%;1.09% +31/01/2014;1.37%;-1.75%;0.47%;-1.95%;0.42%;0.30%;0.75%;-0.88%;-0.32%;0.46%;0.02%;0.94%;-0.33% \ No newline at end of file Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.rda =================================================================== (Binary files differ) Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/edhec.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data/parse_edhec.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data/parse_edhec.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data/parse_edhec.R 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,11 @@ +library(xts) + +df <- read.table("data/edhec.csv", header=TRUE, as.is=TRUE, sep=";") +head(df) + +edhec <- xts(apply(df[,-1], 2, function(x) as.numeric(gsub("%", "", x))) / 100, as.Date(df[,1], format="%d/%m/%Y")) +save(edhec, file="edhec.rda") +# load("edhec.rda") +# head(edhec) +# library(PerformanceAnalytics) +# data(edhec) Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,127 @@ +library(PerformanceAnalytics) + +source("data_prep.R") + +figures.dir <- "figures" + +##### Equity Data for Example 1 and Example 2 ##### +colors <- c(rep("blue", 15), rep("green", 15), rep("red", 5)) +sd.order <- order(StdDev(equity.data)) + +# boxplot to compare return distributions +# mar(bottom, left, top, right) +# default: par(mar=c(5, 4, 4, 2) + 0.1) +png(paste(figures.dir, "equity_box.png", sep="/"), height = 500, width = 1000) +boxplot(coredata(equity.data[,sd.order]), + cex.axis=0.8, las=3, ylab="Returns", pch=18, + col=colors[sd.order], + main="Return Distribution\n(sorted by StdDev)") +legend("topleft", legend=c("Large Cap", "Mid Cap", "Small Cap"), + fill=c("blue", "green", "red"), bty="n", cex=0.8) +dev.off() + +##### edhec Data for Example 3 and Example 4 ##### +p <- 0.95 + +png(paste(figures.dir, "relative_barvar.png", sep="/")) +charts.BarVaR(R[,1:3], width=60, methods=c("ModifiedES", "ModifiedVaR"), + main="Relative Value") +dev.off() + +png(paste(figures.dir, "directional_barvar.png", sep="/")) +charts.BarVaR(R[,4:6], width=60, methods=c("ModifiedES", "ModifiedVaR"), + main="Directional") +dev.off() + + +colors <- c(rep("lightblue", 3), rep("red", 3)) +ES.order <- order(ES(R, p=p, invert=FALSE)) + +png(paste(figures.dir, "edhec_box.png", sep="/"), height = 500, width = 1000) +boxplot(coredata(R[,ES.order]), + cex.axis=0.8, las=3, ylab="Returns", pch=18, + col=colors[ES.order], + main="Return Distribution\n(sorted by Modified ES (95%))") +legend("topleft", legend=c("Relative Value", "Directional"), + fill=c("lightblue", "red"), bty="n", cex=0.8) +dev.off() + +# script for data analysis + +# library(PerformanceAnalytics) +# library(lattice) +# library(corrplot) + +# load("data/edhec.rda") +# +# head(edhec) +# R <- edhec[,1:4] +# p <- 0.95 +# +# first(R) +# last(R) + +# plot the timeseries of returns +# plot(as.zoo(edhec)) +# xyplot(R, scales=list(y="same")) +# charts.BarVaR(R, width=36, methods=c("ModifiedES", "ModifiedVaR")) +# dev.off() + +# boxplot to compare return distributions +# mar(bottom, left, top, right) +# default: par(mar=c(5, 4, 4, 2) + 0.1) +# par(mar=c(10, 4, 4, 2) + 0.1) +# boxplot(coredata(R[,order(ES(R, p=p, invert=FALSE))]), +# cex.axis=0.8, las=3, ylab="Returns", pch=18, +# main="Return Distribution\n(sorted by Modified ES (95%))") +# par(mar=c(5, 4, 4, 2) + 0.1) +# dev.off() + +# head(R[,order(ES(R, invert=FALSE))]) +# head(R[,order(StdDev(R))]) +# chart.Boxplot(R[,order(ES(R, invert=FALSE))]) +# chart.Boxplot(R[,order(StdDev(R))]) +# boxplot(coredata(R), col=c(2:5), cex.names=0.8, las=3) + +# chart the distribution of returns +# for(i in 1:ncol(R)){ +# chart.Histogram(R[,i], methods=c("add.density", "add.normal"), +# colorset=c("lightgray", "black", "blue")) +# legend("topleft", legend=c("kernel density estimate", "normal"), +# lty=c(1,1), col=c("black", "blue"), bty="n") +# Sys.sleep(1) +# } + + +# chart the correlation and covariance +# from http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html +# cor.mtest <- function(mat, conf.level = 0.95) { +# mat <- as.matrix(mat) +# n <- ncol(mat) +# p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n) +# diag(p.mat) <- 0 +# diag(lowCI.mat) <- diag(uppCI.mat) <- 1 +# for (i in 1:(n - 1)) { +# for (j in (i + 1):n) { +# tmp <- cor.test(mat[, i], mat[, j], conf.level = conf.level) +# p.mat[i, j] <- p.mat[j, i] <- tmp$p.value +# lowCI.mat[i, j] <- lowCI.mat[j, i] <- tmp$conf.int[1] +# uppCI.mat[i, j] <- uppCI.mat[j, i] <- tmp$conf.int[2] +# } +# } +# return(list(p.mat, lowCI.mat, uppCI.mat)) +# } +# res <- cor.mtest(R) +# +# corrplot(cor(R), p.mat=res[[1]], main="Correlation", +# sig.level=0.05, tl.cex=0.8) + +# corrplot(M, method="number", bg="gray", tl.cex=0.8) +# corrplot.mixed(M, bg="gray", tl.cex=0.8) + +# If I compare sample min variance portfolio to a ledoit-shrinkage or robust, +# I should use plotcov to compare covaiance matrices + + + + Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R (rev 0) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R 2014-05-01 06:00:59 UTC (rev 3380) @@ -0,0 +1,25 @@ + +##### Equity Data for Example 1 and Example 2 ##### +load("data/crsp_weekly.rda") + +equity.data <- cbind(largecap_weekly[,1:15], + midcap_weekly[,1:15], + smallcap_weekly[,1:5]) +market <- largecap_weekly[,21] +Rf <- largecap_weekly[,22] + +##### edhec Data for Example 3 and Example 4 ##### +# Load the updated edhec dataset +load("data/edhec.rda") + +# Prep data for Examples 3 and 4 +R <- edhec[,c("Convertible.Arbitrage", "Equity.Market.Neutral", + "Fixed.Income.Arbitrage", + "CTA.Global", "Emerging.Markets", "Global.Macro")] +# Abreviate column names for convenience and plotting +colnames(R) <- c("CA", "EMN", "FIA", "CTAG", "EM", "GM") + + +# clean up and remove the data we don't need +rm(largecap_weekly, midcap_weekly, smallcap_weekly, microcap_weekly) +rm(edhec) Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/bt_rb3.rda =================================================================== (Binary files differ) Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/bt_rb3.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream Added: pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/bt_w3.rda =================================================================== (Binary files differ) Property changes on: pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/bt_w3.rda ___________________________________________________________________ Added: svn:mime-type + application/octet-stream [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/returnanalytics -r 3380 From noreply at r-forge.r-project.org Mon May 5 21:55:24 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 5 May 2014 21:55:24 +0200 (CEST) Subject: [Returnanalytics-commits] r3381 - pkg/PortfolioAnalytics/R Message-ID: <20140505195524.992661873F4@r-forge.r-project.org> Author: rossbennett34 Date: 2014-05-05 21:55:24 +0200 (Mon, 05 May 2014) New Revision: 3381 Modified: pkg/PortfolioAnalytics/R/charts.efficient.frontier.R Log: Revising efficient frontier chart to not calculate metrics on assets unless specified in arguments Modified: pkg/PortfolioAnalytics/R/charts.efficient.frontier.R =================================================================== --- pkg/PortfolioAnalytics/R/charts.efficient.frontier.R 2014-05-01 06:00:59 UTC (rev 3380) +++ pkg/PortfolioAnalytics/R/charts.efficient.frontier.R 2014-05-05 19:55:24 UTC (rev 3381) @@ -461,10 +461,15 @@ } if(is.na(mtc)) stop("could not match match.col with column name of efficient frontier") - # get the data to plot scatter of asset returns - asset_ret <- scatterFUN(R=R, FUN="mean") - asset_risk <- scatterFUN(R=R, FUN=match.col) - rnames <- colnames(R) + if(chart.assets){ + # get the data to plot scatter of asset returns + asset_ret <- scatterFUN(R=R, FUN="mean") + asset_risk <- scatterFUN(R=R, FUN=match.col) + rnames <- colnames(R) + } else { + asset_ret <- NULL + asset_risk <- NULL + } # set the x and y limits if(is.null(xlim)){ From noreply at r-forge.r-project.org Mon May 5 21:58:12 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 5 May 2014 21:58:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3382 - in pkg/PortfolioAnalytics: R man Message-ID: <20140505195812.654C5187455@r-forge.r-project.org> Author: rossbennett34 Date: 2014-05-05 21:58:12 +0200 (Mon, 05 May 2014) New Revision: 3382 Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R pkg/PortfolioAnalytics/man/optimize.portfolio.Rd pkg/PortfolioAnalytics/man/optimize.portfolio.rebalancing.Rd Log: Updating documentation for optimize.portfolio.rebalancing. Revision to optimize.portfolio to omit unnecessary calculation of ES when using ROI Modified: pkg/PortfolioAnalytics/R/optimize.portfolio.R =================================================================== --- pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-05-05 19:55:24 UTC (rev 3381) +++ pkg/PortfolioAnalytics/R/optimize.portfolio.R 2014-05-05 19:58:12 UTC (rev 3382) @@ -814,7 +814,13 @@ } else { moments[["var"]] <- try(var(x=Return.clean(R=R, method=clean), na.rm=TRUE), silent=TRUE) } + } else if(objective$name %in% c("CVaR", "ES", "ETL")){ + # do nothing (no point in computing ES here) + moments[[objective$name]] <- "" } else { + # I'm not sure this is serving any purpose since we control the types + # of problems solved with ROI. The min ES problem only uses + # moments$mu if a target return is specified. moments[[objective$name]] <- try(eval(as.symbol(objective$name))(Return.clean(R=R, method=clean)), silent=TRUE) } target <- ifelse(!is.null(objective$target), objective$target, target) @@ -1119,7 +1125,7 @@ #' #' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns #' @param portfolio an object of type "portfolio" specifying the constraints and objectives for the optimization -#' @param constraints default=NULL, a list of constraint objects. An object of class v1_constraint' can be passed in here. +#' @param constraints default=NULL, a list of constraint objects. An object of class 'v1_constraint' can be passed in here. #' @param objectives default=NULL, a list of objective objects. #' @param optimize_method one of "DEoptim", "random", "ROI", "pso", "GenSA". A solver #' for ROI can also be specified and will be solved using ROI. See Details. @@ -1249,30 +1255,80 @@ return(out_list) } -#' portfolio optimization with support for rebalancing or rolling periods +#' Portfolio Optimization with Rebalancing Periods #' -#' This function may eventually be wrapped into optimize.portfolio +#' Portfolio optimization with support for rebalancing periods for +#' out-of-sample testing (i.e. backtesting) #' -#' For now, we'll set the rebalancing periods here, though I think they should eventually be part of the constraints object +#' @details +#' Run portfolio optimization with periodic rebalancing at specified time periods. +#' Running the portfolio optimization with periodic rebalancing can help +#' refine the constraints and objectives by evaluating the out of sample +#' performance of the portfolio based on historical data #' -#' This function is massively parallel, and will require 'foreach' and we suggest that you register a parallel backend. +#' This function is a essentially a wrapper around \code{optimize.portfolio} +#' and thus the discussion in the Details section of the +#' \code{optimize.portfolio} help file is valid here as well. #' +#' This function is massively parallel and requires the 'foreach' package. It +#' is suggested to register a parallel backend. +#' #' @param R an xts, vector, matrix, data frame, timeSeries or zoo object of asset returns -#' @param portfolio an object of type "portfolio" specifying the constraints and objectives for the optimization -#' @param constraints default=NULL, a list of constraint objects -#' @param objectives default=NULL, a list of objective objects +#' @param portfolio an object of type "portfolio" specifying the constraints +#' and objectives for the optimization +#' @param constraints default NULL, a list of constraint objects +#' @param objectives default NULL, a list of objective objects #' @param optimize_method one of "DEoptim", "random", "pso", "GenSA", or "ROI" #' @param search_size integer, how many portfolios to test, default 20,000 -#' @param trace TRUE/FALSE if TRUE will attempt to return additional information on the path or portfolios searched -#' @param \dots any other passthru parameters -#' @param rp a set of random portfolios passed into the function, to prevent recalculation -#' @param rebalance_on a periodicity as returned by xts function periodicity and usable by endpoints -#' @param training_period period to use as training in the front of the data -#' @param trailing_periods if set, an integer with the number of periods to roll over, default NULL will run from inception -#' @return a list containing the optimal weights, some summary statistics, the function call, and optionally trace information +#' @param trace TRUE/FALSE if TRUE will attempt to return additional +#' information on the path or portfolios searched +#' @param \dots any other passthru parameters to \code{\link{optimize.portfolio}} +#' @param rp a set of random portfolios passed into the function to prevent recalculation +#' @param rebalance_on character string of period to rebalance on. See +#' \code{\link[xts]{endpoints}} for valid names. +#' @param training_period an integer of the number of periods to use as +#' a training data in the front of the returns data +#' @param trailing_periods an integer with the number of periods to roll over +#' (i.e. width of the moving or rolling window), the default is NULL will +#' run using the returns data from inception +#' @return a list containing the following elements +#' \itemize{ +#' \item{\code{portfolio}:}{ The portfolio object.} +#' \item{\code{R}:}{ The asset returns.} +#' \item{\code{call}:}{ The function call.} +#' \item{\code{elapsed_time:}}{ The amount of time that elapses while the +#' optimization is run.} +#' \item{\code{opt_rebalancing:}}{ A list of \code{optimize.portfolio} +#' objects computed at each rebalancing period.} +#' } #' @author Kris Boudt, Peter Carl, Brian G. Peterson #' @name optimize.portfolio.rebalancing #' @aliases optimize.portfolio.rebalancing optimize.portfolio.rebalancing_v1 +#' @seealso \code{\link{portfolio.spec}} \code{\link{optimize.portfolio}} +#' @examples +#' \dontrun{ +#' data(edhec) +#' R <- edhec[,1:4] +#' funds <- colnames(R) +#' +#' portf <- portfolio.spec(funds) +#' portf <- add.constraint(portf, type="full_investment") +#' portf <- add.constraint(portf, type="long_only") +#' portf <- add.objective(portf, type="risk", name="StdDev") +#' +#' # Quarterly rebalancing with 5 year training period +#' bt.opt1 <- optimize.portfolio.rebalancing(R, portf, +#' optimize_method="ROI", +#' rebalance_on="quarters", +#' training_period=60) +#' +#' # Monthly rebalancing with 5 year training period and 4 year trailing (moving window) +#' bt.opt2 <- optimize.portfolio.rebalancing(R, portf, +#' optimize_method="ROI", +#' rebalance_on="months", +#' training_period=60, +#' trailing_period=48) +#' } #' @export optimize.portfolio.rebalancing <- function(R, portfolio=NULL, constraints=NULL, objectives=NULL, optimize_method=c("DEoptim","random","ROI"), search_size=20000, trace=FALSE, ..., rp=NULL, rebalance_on=NULL, training_period=NULL, trailing_periods=NULL) { Modified: pkg/PortfolioAnalytics/man/optimize.portfolio.Rd =================================================================== --- pkg/PortfolioAnalytics/man/optimize.portfolio.Rd 2014-05-05 19:55:24 UTC (rev 3381) +++ pkg/PortfolioAnalytics/man/optimize.portfolio.Rd 2014-05-05 19:58:12 UTC (rev 3382) @@ -29,7 +29,7 @@ the constraints and objectives for the optimization} \item{constraints}{default=NULL, a list of constraint - objects. An object of class v1_constraint' can be passed + objects. An object of class 'v1_constraint' can be passed in here.} \item{objectives}{default=NULL, a list of objective Modified: pkg/PortfolioAnalytics/man/optimize.portfolio.rebalancing.Rd =================================================================== --- pkg/PortfolioAnalytics/man/optimize.portfolio.rebalancing.Rd 2014-05-05 19:55:24 UTC (rev 3381) +++ pkg/PortfolioAnalytics/man/optimize.portfolio.rebalancing.Rd 2014-05-05 19:58:12 UTC (rev 3382) @@ -1,7 +1,7 @@ \name{optimize.portfolio.rebalancing} \alias{optimize.portfolio.rebalancing} \alias{optimize.portfolio.rebalancing_v1} -\title{portfolio optimization with support for rebalancing or rolling periods} +\title{Portfolio Optimization with Rebalancing Periods} \usage{ optimize.portfolio.rebalancing_v1(R, constraints, optimize_method = c("DEoptim", "random", "ROI"), @@ -23,10 +23,10 @@ \item{portfolio}{an object of type "portfolio" specifying the constraints and objectives for the optimization} - \item{constraints}{default=NULL, a list of constraint + \item{constraints}{default NULL, a list of constraint objects} - \item{objectives}{default=NULL, a list of objective + \item{objectives}{default NULL, a list of objective objects} \item{optimize_method}{one of "DEoptim", "random", "pso", @@ -39,40 +39,87 @@ additional information on the path or portfolios searched} - \item{\dots}{any other passthru parameters} + \item{\dots}{any other passthru parameters to + \code{\link{optimize.portfolio}}} \item{rp}{a set of random portfolios passed into the - function, to prevent recalculation} + function to prevent recalculation} - \item{rebalance_on}{a periodicity as returned by xts - function periodicity and usable by endpoints} + \item{rebalance_on}{character string of period to + rebalance on. See \code{\link[xts]{endpoints}} for valid + names.} - \item{training_period}{period to use as training in the - front of the data} + \item{training_period}{an integer of the number of + periods to use as a training data in the front of the + returns data} - \item{trailing_periods}{if set, an integer with the - number of periods to roll over, default NULL will run - from inception} + \item{trailing_periods}{an integer with the number of + periods to roll over (i.e. width of the moving or rolling + window), the default is NULL will run using the returns + data from inception} } \value{ - a list containing the optimal weights, some summary - statistics, the function call, and optionally trace - information + a list containing the following elements \itemize{ + \item{\code{portfolio}:}{ The portfolio object.} + \item{\code{R}:}{ The asset returns.} + \item{\code{call}:}{ The function call.} + \item{\code{elapsed_time:}}{ The amount of time that + elapses while the optimization is run.} + \item{\code{opt_rebalancing:}}{ A list of + \code{optimize.portfolio} objects computed at each + rebalancing period.} } } \description{ - This function may eventually be wrapped into - optimize.portfolio + Portfolio optimization with support for rebalancing + periods for out-of-sample testing (i.e. backtesting) } \details{ - For now, we'll set the rebalancing periods here, though I - think they should eventually be part of the constraints - object + Run portfolio optimization with periodic rebalancing at + specified time periods. Running the portfolio + optimization with periodic rebalancing can help refine + the constraints and objectives by evaluating the out of + sample performance of the portfolio based on historical + data - This function is massively parallel, and will require - 'foreach' and we suggest that you register a parallel + This function is a essentially a wrapper around + \code{optimize.portfolio} and thus the discussion in the + Details section of the \code{optimize.portfolio} help + file is valid here as well. + + This function is massively parallel and requires the + 'foreach' package. It is suggested to register a parallel backend. } +\examples{ +\dontrun{ +data(edhec) +R <- edhec[,1:4] +funds <- colnames(R) + +portf <- portfolio.spec(funds) +portf <- add.constraint(portf, type="full_investment") +portf <- add.constraint(portf, type="long_only") +portf <- add.objective(portf, type="risk", name="StdDev") + +# Quarterly rebalancing with 5 year training period +bt.opt1 <- optimize.portfolio.rebalancing(R, portf, +optimize_method="ROI", +rebalance_on="quarters", +training_period=60) + +# Monthly rebalancing with 5 year training period and 4 year trailing (moving window) +bt.opt2 <- optimize.portfolio.rebalancing(R, portf, +optimize_method="ROI", +rebalance_on="months", +training_period=60, +trailing_period=48) +} +} \author{ Kris Boudt, Peter Carl, Brian G. Peterson } +\seealso{ + \code{\link{portfolio.spec}} + \code{\link{optimize.portfolio}} +} From noreply at r-forge.r-project.org Sat May 10 19:35:10 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 10 May 2014 19:35:10 +0200 (CEST) Subject: [Returnanalytics-commits] r3383 - pkg/FactorAnalytics Message-ID: <20140510173510.E6BEE187833@r-forge.r-project.org> Author: chenyian Date: 2014-05-10 19:35:10 +0200 (Sat, 10 May 2014) New Revision: 3383 Modified: pkg/FactorAnalytics/DESCRIPTION Log: Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2014-05-05 19:58:12 UTC (rev 3382) +++ pkg/FactorAnalytics/DESCRIPTION 2014-05-10 17:35:10 UTC (rev 3383) @@ -2,7 +2,7 @@ Type: Package Title: factor analysis Version: 1.0 -Date: 2013-06-17 +Date: 2014-05-10 Author: Eric Zivot and Yi-An Chen Maintainer: Yi-An Chen 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. From noreply at r-forge.r-project.org Sat May 10 19:35:32 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 10 May 2014 19:35:32 +0200 (CEST) Subject: [Returnanalytics-commits] r3384 - pkg/FactorAnalytics Message-ID: <20140510173533.02F95183BB0@r-forge.r-project.org> Author: chenyian Date: 2014-05-10 19:35:32 +0200 (Sat, 10 May 2014) New Revision: 3384 Modified: pkg/FactorAnalytics/.Rbuildignore Log: Modified: pkg/FactorAnalytics/.Rbuildignore =================================================================== --- pkg/FactorAnalytics/.Rbuildignore 2014-05-10 17:35:10 UTC (rev 3383) +++ pkg/FactorAnalytics/.Rbuildignore 2014-05-10 17:35:32 UTC (rev 3384) @@ -1,7 +1,2 @@ -^\.svn$ -^sandbox/*$ -^R/\.svn$ -^data/\.svn$ -^inst/\.svn$ -^man/\.svn$ -^vignettes/\.svn$ +^.*\.Rproj$ +^\.Rproj\.user$ From noreply at r-forge.r-project.org Sat May 10 20:25:10 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 10 May 2014 20:25:10 +0200 (CEST) Subject: [Returnanalytics-commits] r3385 - in pkg/FactorAnalytics: . R Message-ID: <20140510182510.ACFF1186EB4@r-forge.r-project.org> Author: chenyian Date: 2014-05-10 20:25:10 +0200 (Sat, 10 May 2014) New Revision: 3385 Modified: pkg/FactorAnalytics/.Rbuildignore pkg/FactorAnalytics/R/factorModelMonteCarlo.R Log: fix rst() in factorModelMonteCarlo.R Modified: pkg/FactorAnalytics/.Rbuildignore =================================================================== --- pkg/FactorAnalytics/.Rbuildignore 2014-05-10 17:35:32 UTC (rev 3384) +++ pkg/FactorAnalytics/.Rbuildignore 2014-05-10 18:25:10 UTC (rev 3385) @@ -1,2 +1,9 @@ +^\.svn$ +^sandbox/*$ +^R/\.svn$ +^data/\.svn$ +^inst/\.svn$ +^man/\.svn$ +^vignettes/\.svn$ ^.*\.Rproj$ ^\.Rproj\.user$ Modified: pkg/FactorAnalytics/R/factorModelMonteCarlo.R =================================================================== --- pkg/FactorAnalytics/R/factorModelMonteCarlo.R 2014-05-10 17:35:32 UTC (rev 3384) +++ pkg/FactorAnalytics/R/factorModelMonteCarlo.R 2014-05-10 18:25:10 UTC (rev 3385) @@ -85,83 +85,73 @@ #' "TRUE") #' factorModelMonteCarlo <- -function(n.boot=1000, factorData, Beta.mat, Alpha.mat=NULL, - residualData, residual.dist = c("normal", "Cornish-Fisher", "skew-t"), - boot.method = c("random", "block"), - seed=123, return.factors= FALSE , return.residuals= FALSE ) { - - - require(tseries) # for function tsbootstrap() - require(sn) # for function rst() - require(PerformanceAnalytics) - - boot.method = boot.method[1] - residual.dist = residual.dist[1] - set.seed(seed) - if (nrow(Beta.mat) != nrow(residualData)) { - stop("Beta.mat and residualData have different number of rows") - } - factorData = as.matrix(factorData) - n.funds = nrow(Beta.mat) - fund.names = rownames(Beta.mat) - if (is.null(Alpha.mat)) { - Alpha.mat = matrix(0, nrow(Beta.mat)) - rownames(Alpha.mat) = fund.names - } -## -## reseample from empirical distribution of factors -## - if (boot.method == "random") { - bootIdx = sample(nrow(factorData), n.boot, replace=TRUE) - } else { - n.samples = round(n.boot/nrow(factorData)) - n.adj = n.boot - n.samples*nrow(factorData) - bootIdx = as.vector(tsbootstrap(1:nrow(factorData), nb=n.samples)) - if (n.adj > 0) { -## need to make sure that length(bootIdx) = n.boot - bootIdx = c(bootIdx, bootIdx[1:n.adj]) - } - } - factorDataBoot = factorData[bootIdx, ] -## -## run factor model Monte Carlo loop over funds -## - fundReturnsBoot = matrix(0, n.boot, n.funds) - residualsSim = matrix(0, n.boot, n.funds) - colnames(fundReturnsBoot) = colnames(residualsSim) = fund.names - for (i in fund.names) { - ## set random number seed for fund specific residual simulations - set.seed(which(fund.names == i)) - ## simulate from residual distributions - if (residual.dist == "normal") { - residualsSim[, i] = rnorm(n.boot, sd=sqrt(residualData[i,])) - } else if (residual.dist == "Cornish-Fisher") { - ## residual distribution is CornishFisher - residualsSim[, i] = rCornishFisher(n.boot, - sigma=sqrt(residualData[i,"var"]), - skew=residualData[i,"skew"], - ekurt=residualData[i,"ekurt"]) - } else if (residual.dist == "skew-t") { - ## residual distribution is CornishFisher - residualsSim[, i] = rst(n.boot, - xi=residualData[i, "location"], - omega=residualData[i,"scale"], - alpha=residualData[i,"shape"], - nu=residualData[i,"df"]) - } else { - stop("Invalid residual distribution") + function (n.boot = 1000, factorData, Beta.mat, Alpha.mat = NULL, + residualData, residual.dist = c("normal", "Cornish-Fisher", + "skew-t"), boot.method = c("random", "block"), seed = 123, + return.factors = FALSE, return.residuals = FALSE) + { + require(tseries) + require(sn) + require(PerformanceAnalytics) + boot.method = boot.method[1] + residual.dist = residual.dist[1] + set.seed(seed) + if (nrow(Beta.mat) != nrow(residualData)) { + stop("Beta.mat and residualData have different number of rows") } - ## simulated fund returns - fundReturnsBoot[, i] = Alpha.mat[i,1] + factorDataBoot[, colnames(Beta.mat)] %*% t(Beta.mat[i, ,drop=FALSE]) + residualsSim[, i] - } # end loop over funds - - ans = list(returns=fundReturnsBoot) - if (return.factors) { - ans$factors=factorDataBoot + factorData = as.matrix(factorData) + n.funds = nrow(Beta.mat) + fund.names = rownames(Beta.mat) + if (is.null(Alpha.mat)) { + Alpha.mat = matrix(0, nrow(Beta.mat)) + rownames(Alpha.mat) = fund.names + } + if (boot.method == "random") { + bootIdx = sample(nrow(factorData), n.boot, replace = TRUE) + } + else { + n.samples = round(n.boot/nrow(factorData)) + n.adj = n.boot - n.samples * nrow(factorData) + bootIdx = as.vector(tsbootstrap(1:nrow(factorData), nb = n.samples)) + if (n.adj > 0) { + bootIdx = c(bootIdx, bootIdx[1:n.adj]) + } + } + factorDataBoot = factorData[bootIdx, ] + fundReturnsBoot = matrix(0, n.boot, n.funds) + residualsSim = matrix(0, n.boot, n.funds) + colnames(fundReturnsBoot) = colnames(residualsSim) = fund.names + for (i in fund.names) { + set.seed(which(fund.names == i)) + if (residual.dist == "normal") { + residualsSim[, i] = rnorm(n.boot, sd = sqrt(residualData[i, + ])) + } + else if (residual.dist == "Cornish-Fisher") { + residualsSim[, i] = rCornishFisher(n.boot, sigma = sqrt(residualData[i, + "var"]), skew = residualData[i, "skew"], ekurt = residualData[i, + "ekurt"]) + } + else if (residual.dist == "skew-t") { + residualsSim[, i] = rst(n.boot, location = residualData[i, + "location"], scale = residualData[i, "scale"], + shape = residualData[i, "shape"], df = residualData[i, + "df"]) + } + else { + stop("Invalid residual distribution") + } + fundReturnsBoot[, i] = Alpha.mat[i, 1] + factorDataBoot[, + colnames(Beta.mat)] %*% t(Beta.mat[i, , drop = FALSE]) + + residualsSim[, i] + } + ans = list(returns = fundReturnsBoot) + if (return.factors) { + ans$factors = factorDataBoot + } + if (return.residuals) { + ans$residuals = residualsSim + } + return(ans) } - if (return.residuals) { - ans$residuals=residualsSim - } - return(ans) -} From noreply at r-forge.r-project.org Sun May 18 22:51:46 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 18 May 2014 22:51:46 +0200 (CEST) Subject: [Returnanalytics-commits] r3386 - in pkg/FactorAnalytics: . vignettes Message-ID: <20140518205146.9C16C186D47@r-forge.r-project.org> Author: chenyian Date: 2014-05-18 22:51:46 +0200 (Sun, 18 May 2014) New Revision: 3386 Modified: pkg/FactorAnalytics/DESCRIPTION pkg/FactorAnalytics/vignettes/fundamentalFM.Rnw Log: 1. delete ff package dependency. 2. edit vignettes/fundamentalFM.Rnw Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2014-05-10 18:25:10 UTC (rev 3385) +++ pkg/FactorAnalytics/DESCRIPTION 2014-05-18 20:51:46 UTC (rev 3386) @@ -7,5 +7,5 @@ Maintainer: Yi-An Chen 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,ff, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo +Depends: robust, robustbase, leaps, lars, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo LazyLoad: yes Modified: pkg/FactorAnalytics/vignettes/fundamentalFM.Rnw =================================================================== --- pkg/FactorAnalytics/vignettes/fundamentalFM.Rnw 2014-05-10 18:25:10 UTC (rev 3385) +++ pkg/FactorAnalytics/vignettes/fundamentalFM.Rnw 2014-05-18 20:51:46 UTC (rev 3386) @@ -13,39 +13,39 @@ \maketitle \section{Introduction} -This vignette aims to help users to learn how to use fit factor model with \verb at factorAnalytics@ package. We will walk through users a few examples from data input to risk analysis and performance attribution. +This vignette aims to help users learn how to use \verb at factorAnalytics@ package. It provides a few examples covering data input, factor model estimation, risk decomposition and performance attribution. \section{Factor Model} -A factor model is defined as \\ +A factor model is defined as following:\\ \begin{equation} r_t = bf_t + \epsilon_t\;,t=1 \cdots T \label{fm} \end{equation} -Where $r_t$ is N x 1 exress returns, b is N x K and f is K x 1. N is number of variables and K is number of factors. b is usually called factor exposures or factor loadings, and b can be time-varying $b_t$ in fundamental factor model setting. f is factor returns. $\epsilon_t$ is serial uncorrelated but may be cross-correlated. The model is useful to fit asset pricing model. The famous CAPM (Capital Assets Pricing Model) is a one factor model with f equal to market returns. +Where $r_t$ is N x 1 vector of exress returns, b is N x K matrix of factor loadings and f is K x 1 vector of common risk factor. N is numbers of assets and K is numbers of factors. b stands for factor exposures or factor loadings. factor loading b can be time-varying $b_t$ in fundamental factor model. $\epsilon_t$ is assumed serial uncorrelated but maybe cross-correlated in some models. Factor model is useful to fit asset pricing model, for example, the famous CAPM (Capital Assets Pricing Model) is a factor model which contains only one factor and that factor is excess market returns. -\verb at factorAnalytics@ package provides 3 different kinds of factor models. That is fundamental factor model, statistical factor model and time series factor model. We will walk through them one by one. +\verb at factorAnalytics@ package provides 3 different kinds of factor models. They are fundamental factor model, statistical factor model and time series factor model. \subsection{Fundamental Factor Model} -In the case of fundamental factor model, we assume we know factor exposures b which are assets characteristics, like market capitalization or book-to-market ratio. Therefore, $b_t$ is known and $f_t$ is unknown. We run cross-section OLS or WLS regression to estimate $f_t$ for each time period. In specific, +In the case of fundamental factor model, factor exposures are time-varying and stand for assets characteristics or fundamentals, such as market capitalization, book-to-market ratio, industry indicator and so on . That is to say, $b_t$ is known and $f_t$ is unknown. Estimation of factor returns $f_t$ can be done by running cross-section OLS or WLS regression in each time period t. In specific: \begin{equation}\label{ffm} -r_t = f_M + b\hat{f_t} + \hat{\epsilon_t}\;,t=1 \cdots T +r_t = f_M + b_t\hat{f_t} + \hat{\epsilon_t}\;,t=1 \cdots T \end{equation} -$f_M$ is normally called market factor or world factor depending on the context on the country level or global level. Econometrically, it is an intercept term of fundamental factor model. $f_t$ is estimated with cross-sectional in each period t. +$f_M$ is the market factor or world factor depending on the asset space. The former is of the country level and the later is of the global level. Econometrically, it is an intercept term of each cross-sectional regression. -This approach is also called BARRA type approach since it is initially developed by BARRA and later on been merged by MSCI. The famous Barra global equity model (GEM3) contains more than 50 factors. +This approach is also known as BARRA type approach. The famous Barra global equity model (GEM3) contains more than 50 factors. \subsection{Example 1} -We will walk through the first examples in this section where use style factors like size are used. +The first example in this section will use firm fundamental such as market cap and book-to-market ratio. \subsubsection{Loading Data} -Let's look at the arguments of \verb at fitFundamentalFactorModel()@ which will deal with fundamental factor model in \verb at factorAnalytics@. +Let's look at the arguments of \verb at fitFundamentalFactorModel()@. It is the function which will estimate fundamental factor model in \verb at factorAnalytics@. <>= library(factorAnalytics) args(fitFundamentalFactorModel) @ -\verb at data@ is in class of \verb at data.frame@ and is required to have \emph{assetvar},\emph{returnvar} and \emph{datevar}. One can image \emph{data} is like panel data setup and need firm variable and time variable. Data has dimension (N x T) and at least 3 consumes to specify information needed. +\verb at data@ is in class of \verb at data.frame@ and is required to specify \emph{assetvar}, \emph{returnvar} and \emph{datevar}. The \emph{data} is a panel data so the firm variables and the time variable are required for \verb at fitFundamentalFactorModel()@. -We download data from CRSP/Compustat quarterly fundamental and name it \verb at equity@. It contains 67 stocks and 106 time period from January 2000 to December 2013. +In this example, the data is downlaoded from CRSP/Compustat quarterly fundamental and named \verb at equity@. It contains 67 stocks and 106 time period from January 2000 to December 2013. <>= #equity <- data(equity) @@ -54,21 +54,20 @@ length(unique(equity$datadate)) # number of period t length(unique(equity$tic)) # number of assets @ -We need asset returns to run our model. We can utilize \verb at Delt()@ to calculate price percentage change which is exactly asset returns in \verb at quantmod@ package. +To calculate asset returns, I use \verb at Delt()@ in \verb at quantmod@ package to calculate price percentage change. <>= library(quantmod) # for Delt. See Delt for detail equity <- cbind(equity,do.call(rbind,lapply(split(equity,equity$tic), function(x) Delt(x$PRCCQ)))) names(equity)[22] <- "RET" @ -We want market value and book-to-market ratio to be our style factors. Market vale can be achieved by common stocks outstanding multiply price and book value is common/ordinary equity value. We take log for market value. +The next step is to construct market capitalization and book-to-market ratio. They will be the factor loadings for \verb at fitFundamentalFactorModel()@ in our example. Market cap can be calculated by multiplying shares of common stocks outstanding with price and book value is the common/ordinary equity value. Nnatrual log is treated for market cap. <>== equity$MV <- log(equity$PRCCQ*equity$CSHOQ) equity$BM <- equity$CEQQ/equity$MV @ -now we will fit Equation \ref{ffm} with b = [MV BM]. -We will get an error message if \verb at datevar@ is not \verb at as.Date@ format compatible. In our example, our date variable is \emph{DATACQTR} and looks like "2000Q1". We have to convert it to \verb at as.Date@ compatible. We can utilize \verb at as.yearqtr@ in \verb at xts@ package to do it. Also, we will use character string for asset variable instead of factor.\footnote{The best data input is to convert all your data into xts class since we use xts to compute everything in this package, although it is not restricted to it.} +We will get an error message if \verb at datevar@ is not \verb at as.Date@ format compatible. In our example, our date variable is \emph{DATACQTR}. It reads as "2000Q1". We have to convert it to \verb at as.Date@ compatible. We can utilize \verb at as.yearqtr@ in \verb at xts@ package to do it. Also, we will use character string for asset variable instead of factor class.\footnote{The best data input is to convert all your data into xts class since we use xts to compute everything in this package.} <>= a <- unlist( lapply(strsplit(as.character(equity$DATACQTR),"Q"), function(x) paste(x[[1]],"-",x[[2]],sep="") ) ) @@ -78,7 +77,7 @@ @ \subsubsection{Fit the Model} -fit the function: +The following codes will fit the fundamental factor model: <>= fit.fund <- fitFundamentalFactorModel(exposure.names=c("BM","MV"),datevar="yearqtr", returnsvar ="RET",assetvar="tic",wls=TRUE, @@ -86,29 +85,29 @@ names(fit.fund) @ -A few notice for fitting fundamental factor model. So far this function can only deal with balanced panel because we want to extract return covariance and residuals and so on. Second, \verb at datevar@ has to be \verb at as.Date@ compatible, otherwise the function can not read time index. It is somehow inconvenient but make sure we will not mess up with any time issue. +A few notice for fitting fundamental factor model: So far this function can only deal with balanced panel because we want to extract return covariance and residuals and so on. Second, \verb at datevar@ has to be \verb at as.Date@ compatible, otherwise the function can not read time index. It is somehow inconvenient but it makes sure time index is not messed up. -Default fit method for \verb at fitFundamentalFactorModel()@ is classic OLS and covariance matrix is also classic covariance matrix defined by \verb at covClassic()@ in \verb at robust@ package. One can change to robust estimation and robust covariance matrix estimation. +Default fitting method for \verb at fitFundamentalFactorModel()@ is classic OLS. The covariance matrix is also fit with classic covariance matrix defined by \verb at covClassic()@ in \verb at robust@ package. One can also use robust estimation by using argument \verb at regression = "robust"@ and robust covariance matrix estimation by using \verb at covariance = "robust"@ -\verb at returns.cov@ contains information about returns covariance. return covariance is +\verb at returns.cov@ contains information about returns covariance. That is : \[ \Sigma_x = B \Sigma_f B' + D \] -If \verb at full.resid.cov@ is \emph{FALSE}, D is diagonal matrix with variance of residuals in diagonal terms. If \emph{TRUE}, D is covariance matrix of residuals. +If \verb at full.resid.cov@ is \emph{FALSE}, D is a diagonal matrix with variance of residuals in diagonal terms. If \emph{TRUE}, D is a covariance matrix of residuals. <>= names(fit.fund$returns.cov) @ -Please check out \verb at fit.fund$factor.cov@, \verb at fit.fund$resids.cov@ and \verb at fit.fund$resid.variance@ yourself for detail. +For more information about covariance, please check out \verb at fit.fund$factor.cov@, \verb at fit.fund$resids.cov@ and \verb at fit.fund$resid.variance@ for detail. -factor returns, residuals,t-stats are xts class. +factor returns, residuals,t-stats are of \verb at xts@ class. <>= fit.fund$factor.returns fit.fund$residuals fit.fund$tstats @ -Output of \verb at fitFundamentalFactorModel()@ is of class \emph{FundamentalFactorModel}. There are generic function \verb at predict@, \verb at summary@, \verb at print@ and \verb at plot@ can be applied. +Output of \verb at fitFundamentalFactorModel()@ is of class \emph{FundamentalFactorModel}. Generic function \verb at predict@, \verb at summary@, \verb at print@ and \verb at plot@ can be applied to the output. <>= summary(fit.fund) predict(fit.fund) @@ -136,7 +135,7 @@ Enter an item from the menu, or 0 to exit \end{verbatim} -For example, choose 1 will give factor returns and it looks like in Figure \ref{fig1} +For example, choose 1 will give users factor returns as shown in the Figure \ref{fig1} <>= plot(fit.fund,which.plot=1,max.show=3) @ @@ -152,14 +151,14 @@ \end{figure} \subsection{Example 2: Barra type industry/country model} -In a global equity model or specific country equity model, modelers can use industry/country dummies. In our example, we have 63 stocks in different industry. In specific, +This example shows how to estimate BARRA tyipe industry/country model. Modelers use industry/country dummies in a specific country equity model or a global equity model. In this example, I have 63 stocks in the US equity market, so it is a BARRA industry model. In specific: \begin{equation} x_{it} = \Sigma_{j=1}^{J}b_{i,j}f_{i,t} + \epsilon_{i,t},\;for\,each\,i\,,t \end{equation} -where $b_{i,j} = 1$ if stock i in industry j and $b_{i,j}=0$ otherwise. +where $b_{i,j} = 1$ if stock i in industry j and $b_{i,j}=0$, otherwise. In matrix form:\[ x_t = Bf_t + \epsilon_t \] and B is the N X J matrix of industry dummies. -\emph{SPCINDCD} in our \verb at equity@ contains $S\&P$ industry codes, we add this variable name into \verb at exposure.names@ and we can fit Barra type industry model. Be sure this variable is of class\emph{character} not \emph{numeric}. Otherwise the function will not create dummies. +\emph{SPCINDCD} in our \verb at equity@ dataset contains $S\&P$ industry codes. \verb at fitFundamentalFactorModel()@ will fit Barra type industry model if \verb at exposure.names@ is equal to \emph{SPCINDCD}. Be sure this variable is of class \emph{character} but not \emph{numeric}. Otherwise the function will not create dummies. <>= equity$SPCINDCD <- as.character(equity$SPCINDCD) @@ -168,7 +167,7 @@ data=equity) @ -\verb at fitFundamentalFactorModel()@ supports mixed model like fit industry/country dummy factor exposures and style factor exposures together. For example, +\verb at fitFundamentalFactorModel()@ also supports mixed model which uses industry/country dummy factor exposures and style factor exposures together. For example : <>= fit.mix <- fitFundamentalFactorModel(exposure.names=c("BM","MV","SPCINDCD"), datevar="yearqtr",returnsvar ="RET", @@ -177,9 +176,9 @@ \subsubsection{Standardizing Factor Exposure} -It is common to standardize factor exposure to have weight mean 0 and standard deviation equal to 1. The weight are often taken as proportional to square root of market capitalization, although other weighting schemes are possible. +It is common to standardize factor exposures by assigning appropriate weights so that factor loadings are mean 0 and standard deviation equal to 1. The weight are often proportional to square root of market capitalization, although other weighting schemes are possible. -We will try example 1 but with standardized factor exposure with square root of market capitalization. First we create a weighting variable. +Let's redo the example 1 with standardized factor exposures with square root of market capitalization. In order to do that, we create a weighting variable first. <>= equity$weight <- sqrt(exp(equity$MV)) # we took log for MV before. @@ -193,21 +192,21 @@ weight.var = "weight" ) @ -The advantage of weight facotr exposures is better interpretation of factor returns. $f_t$ can be interpreted as long-short zero investment portfolio. In our case, $f_{MVt}$ will long big size stocks and short small size stocks. +The advantage of standardizing facotr exposures is the better interpretation of factor returns. $f_t$ can be interpreted as long-short zero investment portfolio. In our case, $f_{MV,t}$ is the long short portfolio returns which long big size stocks and short small size stocks. \subsection{Statistical Factor Model} -In statistical factor model, neither factor exposure b (normally called factor loadings in statistical factor model) nor factor returns $f_t$ are observed in equation \ref{fm}. So we can rewrite the model as: +In statistical factor model, neither factor loading b nor factor returns $f_t$ are observed in equation \ref{fm}. So we can rewrite the model as: \begin{equation} r_t = bf_t + \epsilon_t\;,t=1 \cdots T \label{fm2} \end{equation} Factor returns $f_t$ can be calculated as principle components of covariance matrix of assets returns if number of asset N is less than the number of time period T, and factor loadings can be calculated using conventional least square technique. -By default, the first principle component or factor will explain the most variation of returns covariance matrix and so on. +The first principle component or factor will explain the most variation of returns covariance matrix. The second priciple component will explain the most variation controlling for the first one and so on. -In some cases, when number of assets N is larger than number of time period T. Connor and Korajczyk (1986) develop an alternative method called asymptotic principal components, building on the approximate factor model theory of Chamberlain and Rothschild (1983). Connor and Korajczyk analyze the eigenvector of the T X T cross product of matrix returns rather then N X N covariance matrix of returns. They show the first k eigenvectors of this cross product matrix provide consistent estimates of the k X T matrix of factor returns. +In some cases, when number of assets N is larger than number of time period T. Connor and Korajczyk (1986) develop an alternative method called asymptotic principal components analysis, related to the approximate factor model theory of Chamberlain and Rothschild (1983). Connor and Korajczyk analyze the eigenvector of the T X T cross product of matrix returns rather then N X N covariance matrix of returns. They show the first k eigenvectors of this cross product matrix provide consistent estimates of the k X T matrix of factor returns. -We can use function \verb at fitStatisticalFactorModel@ to fit statistical factor model. First, we need asset returns in time series or xts class. We choose xts to work with because time index is easy to handle but this is not restricted to the function. +We can use function \verb at fitStatisticalFactorModel@ to fit statistical factor model. Asset returns have to be in time series or xts class. We choose xts to work with in this example because time index is easy to handle. <>= library(xts) @@ -222,7 +221,7 @@ ret <- ret[,-1] dim(ret) @ -The data \verb at ret@ contians 63 assets and 52 time periods. We will exploit asymptotic principal components analysis to fit statistical model. There are two ways to find numbers of factors, Connor and Korajczyk(1995) and Bai and Ng (2002). Both are provided in our function. We will use Bai and Ng (2002) to choose the numbers of factors. +The data \verb at ret@ contians 63 assets and 52 time periods. We will exploit asymptotic principal components analysis to fit statistical model. There are two tests to determine numbers of factors, Connor and Korajczyk(1995) and Bai and Ng (2002). Both are provided in our function. We will use Bai and Ng (2002) to choose the numbers of factors. <>= fit.stat <- fitStatisticalFactorModel(data=ret, @@ -230,7 +229,7 @@ names(fit.stat) @ -5 factors is chosen by Bai and Ng (2002). Factor returns can be found \verb at fit.stat$factors at . +5 factors is chosen by Bai and Ng (2002). Factor returns can be found in \verb at fit.stat$factors at . <>= fit.stat$k @ @@ -249,7 +248,7 @@ \label{fig2} \end{figure} -Finally, screen plot of eigenvalues shows how much variance can be explained by factors. We can see the first factor explain more than 70 percent of variation of cross-product matrix. +Finally, screen plot of eigenvalues shows how much variation can be explained by factors. We can see the first factor explain more than 70 percent of variation of asset returns. <>= plot(fit.stat,which.plot=1) @ @@ -267,21 +266,21 @@ Similar to \verb at fitFundamentalFactorModel@, generic functions like \verb at summary@, \verb at print@, \verb at plot@ and \verb at predict@ can be used for statistical factor model. \subsection{Time Series Factor Model} -In Time Series factor model, factor returns $f_t$ is observed and taken as macroeconomic time series like GDP or other time series like market returns or credit spread. In our package, we provid some common used times series in data set \verb at CommonFactors@. \verb at factors@ is monthly time series and \verb at factors.Q@ is quarterly time series. +In Time Series factor model, factor returns $f_t$ is observed and is taken as macroeconomic time series like GDP growth rate or other finanical time series such as market returns or credit spread. In our package, we provid some common used times series in data set \verb at CommonFactors@. \verb at factors@ is monthly time series and \verb at factors.Q@ is quarterly time series. <>= data(CommonFactors) names(factors.Q) @ -We can combine with our data \verb at ret@ and get rid of NA values. +Let's combine these factors with our data \verb at ret@ and delete NA values. <>= ts.factors <- xts(factors.Q,as.yearqtr(index(factors.Q),format="%Y-%m-%d")) ts.data <- na.omit(merge(ret,ts.factors)) @ -We will use SP500, 10 years and 3 months term spread and difference of VIX as our common factors. +In this example, we will use SP500, 10 years and 3 months term spread and difference of VIX as our common factors. <>= fit.time <- fitTimeSeriesFactorModel(assets.names=tic, @@ -295,7 +294,7 @@ @ -\verb at fitTimeSeriesFactorModel@ also have various variable selection algorithm to choose. One can include every factor and let the function to decide which one is the best model. For example, we include every common factors and use method \verb at stepwise@ which utilizes \verb at step@ function in \verb at stat@ package +\verb at fitTimeSeriesFactorModel@ also have various variable selection algorithm to choose. One can include all possible factors and let the function to decide which one is the best model. For example, we include every common factors and use method \verb at stepwise@ which utilizes \verb at step@ function in \verb at stat@ package <>= fit.time2 <- fitTimeSeriesFactorModel(assets.names=tic, @@ -313,10 +312,10 @@ \section{Risk Analysis} \subsection{Factor Model Risk Budgeting} -One can do risk analysis with factor model. According to Meucci (2007), factor model can be represented as +One can perform risk analysis with factor model. Meucci (2007) shows factor model can be represented as: \begin{align} -r_{it} &= \alpha_i + \beta_{i1}f_{1t} + \beta_{i2}f_{2t} + \cdots + \beta_{ik}f_{kt} + \sigma{i}z_{it},\;i=1 \cdots N,\;t=1 \cdots T \\ +r_{it} &= \alpha_i + \beta_{i1}f_{1t} + \beta_{i2}f_{2t} + \cdots + \beta_{ik}f_{kt} + \sigma_{i}z_{it},\;i=1 \cdots N,\;t=1 \cdots T \\ &= \alpha_i + \tilde{\beta_i}'\tilde{F_t} \end{align} @@ -328,11 +327,9 @@ \end{align} where\\ -$\frac{\partial RM_i}{\partial \beta_{ki}}$ is called marginal contribution of factor k to $RM_i$ \\ -$\beta_{ki}\frac{\partial RM_i}{\partial \beta_{ki}}$ is called component contribution of factor k to $RM_i$ \\ -$\beta_{ki}\frac{\partial RM_i}{\partial \beta_{ki}}/RM_i$ is called percentage contribution of factor k to $RM_i$ +$\frac{\partial RM_i}{\partial \beta_{ki}}$ is marginal contribution of factor k to $RM_i$. $\beta_{ki}\frac{\partial RM_i}{\partial \beta_{ki}}$ is component contribution of factor k to $RM_i$ and $\beta_{ki}\frac{\partial RM_i}{\partial \beta_{ki}}/RM_i$ is percentage contribution of factor k to $RM_i$ -\verb at factorAnalytics@ package provide 3 different risk metrics decomposition, Standard deviation (Std), Value-at-Risk (VaR) and Expected Shortfall (ES). Each one with different distribution such as historical distribution, Normal distribution and Cornish-Fisher distribution. +\verb at factorAnalytics@ package provide 3 different risk metrics decomposition, Standard deviation (Std), Value-at-Risk (VaR) and Expected Shortfall (ES). Each risk metric supports different estimation methods under different distribution such as empirical distribution, Normal distribution and Cornish-Fisher distribution. This example shows factor model VaR decomposition with Normal distribution of asset AA for a statistical factor model. <>= @@ -344,14 +341,14 @@ names(var.decp) @ -VaR, number of exceed, id of exceed, marginal contribution to VaR, component contribution to VaR and percentage contribution to VaR are computed. Let see VaR and component contribution to VaR +VaR, number of exceed, index of observations that exceed VaR, marginal contribution to VaR, component contribution to VaR and percentage contribution to VaR are computed. Let's see VaR and component contribution to VaR; <>= var.decp$VaR.fm var.decp$cVaR.fm @ It looks like the second factor contributes the largest risk to asset AA. -One can use \verb at plot()@ method to see barplot of risk budgeting. Default is to show 6 assets. Figure \ref{fig4} shows componenet contribution to VaR for several different assets. +One can use \verb at plot()@ method to see barplot of risk budgeting. The default is to show 6 assets. Figure \ref{fig4} shows componenet contribution to VaR for several different assets. <>= plot(fit.stat,which.plot=8,legend.text=TRUE, args.legend=list(x="topright"), @@ -377,11 +374,9 @@ \end{align} where\\ -$\frac{\partial RM}{\partial w_{i}}$ is called marginal contribution of asset i to RM \\ -$w_{i}\frac{\partial RM}{\partial w_{i}}$ is called component contribution of asset i to RM \\ -$w_{i}\frac{\partial RM}{\partial w_{i}}/RM$ is called percentage contribution of asset i to RM +$\frac{\partial RM}{\partial w_{i}}$ is marginal contribution of asset i to RM. $w_{i}\frac{\partial RM}{\partial w_{i}}$ is component contribution of asset i to RM. $w_{i}\frac{\partial RM}{\partial w_{i}}/RM$ is percentage contribution of asset i to RM. -we can use function \verb at VaR()@ in \verb at PerformanceAnalytics@. Suppose we have an eqaully weighted portfolio of 63 assets in data set \verb at ret@. The following code can compute portfolio VaR, component contribution to VaR and percentage contribution to VaR +we can use function \verb at VaR()@ in \verb at PerformanceAnalytics@ to perform portfolio risk budgeting. Suppose we have an eqaully weighted portfolio of 63 assets in data set \verb at ret@. The following code can compute portfolio VaR, component contribution to VaR and percentage contribution to VaR <>= VaR(R=ret,method="gaussian",portfolio_method="component") @@ -390,23 +385,22 @@ \section{Performance Attribution} -User can do factor-based performance attribution with \verb at factorAnalytics@ package. factor model: +Users can perform factor-based performance attribution with \verb at factorAnalytics@ package. factor model: \begin{equation} r_t = \alpha + Bf_t + e_t,\;t=1 \cdots T \end{equation} -can break down asset returns into two pieces. The first term is \emph{returns atttributed to factors} $Bf_t$ and the second term is called \emph{specific returns} which is simply $\alpha + e_t$. +Factor model breaks asset returns into two pieces. The first term is \emph{returns atttributed to factors} $Bf_t$ and the second term is called \emph{specific returns} which is simply $\alpha + e_t$. -For example, we can breakdown time series factor model.\\ -Function \verb at factorModelPerformanceAttribution()@ can help us to calculate performance attribution. +For the example of time series factor model, function \verb at factorModelPerformanceAttribution()@ calculates performance attribution. <>= ts.attr <- factorModelPerformanceAttribution(fit.time) names(ts.attr) @ -There are 3 items generated by the function. \verb at cum.ret.attr.f@ will return a N x K matrix with cummulative returns attributed to factors. \verb at cum.spec.ret@ will return a N x 1 matrix with cummulative specific returns. \verb at attr.list@ will return a list which contains returns atttribution to each factors and specific returns asset by asset. In addition, a \emph{FM.attribution} class will be generated and generic function \verb at print()@, \verb at summary()@ and \verb at plot()@ can be applied to it. +There are 3 outputs generated by this function. \verb at cum.ret.attr.f@ will return a N x K matrix of cummulative returns attributed to factors. \verb at cum.spec.ret@ will return a N x 1 matrix of cummulative specific returns. \verb at attr.list@ will return a list which contains returns atttribution to each factors and specific returns asset by asset. In addition, a \emph{FM.attribution} class will be generated and generic function \verb at print()@, \verb at summary()@ and \verb at plot()@ can be applied to it. \subsection{Benchmark and Active Returns} Portfolio performance is usually compared to similar type of benchmark. US equity portfolio will compare its performance with S$\&$P 500 index for example. Therefore, \emph{active returns} under active management is interested. We define active returns = assets returns - benchmark. -We can also calculate active return attribution just simply fit active return with fundamental factor model, statistical factor model or time series factor model and calculate by \verb at factorModelPerformanceAttribution()@. +We can also calculate active return attribution by fitting active return with fundamental factor model, statistical factor model or time series factor model first, and then using \verb at factorModelPerformanceAttribution()@. \end{document} \ No newline at end of file From noreply at r-forge.r-project.org Mon May 19 18:27:08 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 19 May 2014 18:27:08 +0200 (CEST) Subject: [Returnanalytics-commits] r3387 - pkg/FactorAnalytics Message-ID: <20140519162709.05CAA1873AA@r-forge.r-project.org> Author: chenyian Date: 2014-05-19 18:27:08 +0200 (Mon, 19 May 2014) New Revision: 3387 Modified: pkg/FactorAnalytics/DESCRIPTION Log: put ff package back in DESCRIPTION Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2014-05-18 20:51:46 UTC (rev 3386) +++ pkg/FactorAnalytics/DESCRIPTION 2014-05-19 16:27:08 UTC (rev 3387) @@ -7,5 +7,5 @@ Maintainer: Yi-An Chen 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, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo +Depends: robust, robustbase, leaps, lars, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo,ff LazyLoad: yes From noreply at r-forge.r-project.org Mon May 19 22:48:26 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 19 May 2014 22:48:26 +0200 (CEST) Subject: [Returnanalytics-commits] r3388 - pkg/FactorAnalytics Message-ID: <20140519204826.91D48186972@r-forge.r-project.org> Author: chenyian Date: 2014-05-19 22:48:26 +0200 (Mon, 19 May 2014) New Revision: 3388 Modified: pkg/FactorAnalytics/DESCRIPTION Log: delete ff package dependency. Modified: pkg/FactorAnalytics/DESCRIPTION =================================================================== --- pkg/FactorAnalytics/DESCRIPTION 2014-05-19 16:27:08 UTC (rev 3387) +++ pkg/FactorAnalytics/DESCRIPTION 2014-05-19 20:48:26 UTC (rev 3388) @@ -7,5 +7,5 @@ Maintainer: Yi-An Chen 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, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo,ff +Depends: robust, robustbase, leaps, lars, MASS, PerformanceAnalytics, sn, tseries, strucchange,xts,ellipse, zoo LazyLoad: yes From noreply at r-forge.r-project.org Thu May 22 16:02:34 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 22 May 2014 16:02:34 +0200 (CEST) Subject: [Returnanalytics-commits] r3389 - pkg/PortfolioAnalytics Message-ID: <20140522140234.ACCA2186F1B@r-forge.r-project.org> Author: rossbennett34 Date: 2014-05-22 16:02:34 +0200 (Thu, 22 May 2014) New Revision: 3389 Modified: pkg/PortfolioAnalytics/README Log: Triggering rebuild on R-Forge Modified: pkg/PortfolioAnalytics/README =================================================================== --- pkg/PortfolioAnalytics/README 2014-05-19 20:48:26 UTC (rev 3388) +++ pkg/PortfolioAnalytics/README 2014-05-22 14:02:34 UTC (rev 3389) @@ -11,4 +11,5 @@ Running the following command from the /PortfolioAnalytics directory is a temporary fix. -svn revert man/chart.Weights.Rd man/chart.RiskReward.Rd man/plot.Rd man/print.optimize.portfolio.Rd man/chart.EfficientFrontier.Rd man/chart.RiskBudget.Rd man/print.summary.optimize.portfolio.rebalancing.Rd \ No newline at end of file +svn revert man/chart.Weights.Rd man/chart.RiskReward.Rd man/plot.Rd man/print.optimize.portfolio.Rd man/chart.EfficientFrontier.Rd man/chart.RiskBudget.Rd man/print.summary.optimize.portfolio.rebalancing.Rd + From noreply at r-forge.r-project.org Fri May 23 16:27:12 2014 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 23 May 2014 16:27:12 +0200 (CEST) Subject: [Returnanalytics-commits] r3390 - pkg/PortfolioAnalytics/sandbox/RFinance2014 Message-ID: <20140523142712.748A4186D43@r-forge.r-project.org> Author: rossbennett34 Date: 2014-05-23 16:27:11 +0200 (Fri, 23 May 2014) New Revision: 3390 Removed: pkg/PortfolioAnalytics/sandbox/RFinance2014/R/ pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md pkg/PortfolioAnalytics/sandbox/RFinance2014/data/ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R pkg/PortfolioAnalytics/sandbox/RFinance2014/figures/ pkg/PortfolioAnalytics/sandbox/RFinance2014/index.html pkg/PortfolioAnalytics/sandbox/RFinance2014/makefile pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_analysis.R pkg/PortfolioAnalytics/sandbox/RFinance2014/optimization_results/ pkg/PortfolioAnalytics/sandbox/RFinance2014/optimize.R pkg/PortfolioAnalytics/sandbox/RFinance2014/presentation.Rmd pkg/PortfolioAnalytics/sandbox/RFinance2014/slidy_presentation.html Log: removing files from RFinance2014 directory to clean and prep for copying updated presentation files Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md 2014-05-22 14:02:34 UTC (rev 3389) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/README.md 2014-05-23 14:27:11 UTC (rev 3390) @@ -1,17 +0,0 @@ -PortfolioAnalyticsPresentation -============================== - -Repository for exploring ways to develop html presentation for the PortfolioAnalytics package, primarily for RFinance 2014. - -This repo has two branches -* master -* gh-pages - -Only work on the master branch. The gh-pages branch is used to view the generated presentation as index.html. - -http://oli.jp/2011/github-pages-workflow/ -you can push your local master branch to the gh-pages branch on GitHub - -``` -git push -f origin master:gh-pages -``` Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R 2014-05-22 14:02:34 UTC (rev 3389) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_analysis.R 2014-05-23 14:27:11 UTC (rev 3390) @@ -1,127 +0,0 @@ -library(PerformanceAnalytics) - -source("data_prep.R") - -figures.dir <- "figures" - -##### Equity Data for Example 1 and Example 2 ##### -colors <- c(rep("blue", 15), rep("green", 15), rep("red", 5)) -sd.order <- order(StdDev(equity.data)) - -# boxplot to compare return distributions -# mar(bottom, left, top, right) -# default: par(mar=c(5, 4, 4, 2) + 0.1) -png(paste(figures.dir, "equity_box.png", sep="/"), height = 500, width = 1000) -boxplot(coredata(equity.data[,sd.order]), - cex.axis=0.8, las=3, ylab="Returns", pch=18, - col=colors[sd.order], - main="Return Distribution\n(sorted by StdDev)") -legend("topleft", legend=c("Large Cap", "Mid Cap", "Small Cap"), - fill=c("blue", "green", "red"), bty="n", cex=0.8) -dev.off() - -##### edhec Data for Example 3 and Example 4 ##### -p <- 0.95 - -png(paste(figures.dir, "relative_barvar.png", sep="/")) -charts.BarVaR(R[,1:3], width=60, methods=c("ModifiedES", "ModifiedVaR"), - main="Relative Value") -dev.off() - -png(paste(figures.dir, "directional_barvar.png", sep="/")) -charts.BarVaR(R[,4:6], width=60, methods=c("ModifiedES", "ModifiedVaR"), - main="Directional") -dev.off() - - -colors <- c(rep("lightblue", 3), rep("red", 3)) -ES.order <- order(ES(R, p=p, invert=FALSE)) - -png(paste(figures.dir, "edhec_box.png", sep="/"), height = 500, width = 1000) -boxplot(coredata(R[,ES.order]), - cex.axis=0.8, las=3, ylab="Returns", pch=18, - col=colors[ES.order], - main="Return Distribution\n(sorted by Modified ES (95%))") -legend("topleft", legend=c("Relative Value", "Directional"), - fill=c("lightblue", "red"), bty="n", cex=0.8) -dev.off() - -# script for data analysis - -# library(PerformanceAnalytics) -# library(lattice) -# library(corrplot) - -# load("data/edhec.rda") -# -# head(edhec) -# R <- edhec[,1:4] -# p <- 0.95 -# -# first(R) -# last(R) - -# plot the timeseries of returns -# plot(as.zoo(edhec)) -# xyplot(R, scales=list(y="same")) -# charts.BarVaR(R, width=36, methods=c("ModifiedES", "ModifiedVaR")) -# dev.off() - -# boxplot to compare return distributions -# mar(bottom, left, top, right) -# default: par(mar=c(5, 4, 4, 2) + 0.1) -# par(mar=c(10, 4, 4, 2) + 0.1) -# boxplot(coredata(R[,order(ES(R, p=p, invert=FALSE))]), -# cex.axis=0.8, las=3, ylab="Returns", pch=18, -# main="Return Distribution\n(sorted by Modified ES (95%))") -# par(mar=c(5, 4, 4, 2) + 0.1) -# dev.off() - -# head(R[,order(ES(R, invert=FALSE))]) -# head(R[,order(StdDev(R))]) -# chart.Boxplot(R[,order(ES(R, invert=FALSE))]) -# chart.Boxplot(R[,order(StdDev(R))]) -# boxplot(coredata(R), col=c(2:5), cex.names=0.8, las=3) - -# chart the distribution of returns -# for(i in 1:ncol(R)){ -# chart.Histogram(R[,i], methods=c("add.density", "add.normal"), -# colorset=c("lightgray", "black", "blue")) -# legend("topleft", legend=c("kernel density estimate", "normal"), -# lty=c(1,1), col=c("black", "blue"), bty="n") -# Sys.sleep(1) -# } - - -# chart the correlation and covariance -# from http://cran.r-project.org/web/packages/corrplot/vignettes/corrplot-intro.html -# cor.mtest <- function(mat, conf.level = 0.95) { -# mat <- as.matrix(mat) -# n <- ncol(mat) -# p.mat <- lowCI.mat <- uppCI.mat <- matrix(NA, n, n) -# diag(p.mat) <- 0 -# diag(lowCI.mat) <- diag(uppCI.mat) <- 1 -# for (i in 1:(n - 1)) { -# for (j in (i + 1):n) { -# tmp <- cor.test(mat[, i], mat[, j], conf.level = conf.level) -# p.mat[i, j] <- p.mat[j, i] <- tmp$p.value -# lowCI.mat[i, j] <- lowCI.mat[j, i] <- tmp$conf.int[1] -# uppCI.mat[i, j] <- uppCI.mat[j, i] <- tmp$conf.int[2] -# } -# } -# return(list(p.mat, lowCI.mat, uppCI.mat)) -# } -# res <- cor.mtest(R) -# -# corrplot(cor(R), p.mat=res[[1]], main="Correlation", -# sig.level=0.05, tl.cex=0.8) - -# corrplot(M, method="number", bg="gray", tl.cex=0.8) -# corrplot.mixed(M, bg="gray", tl.cex=0.8) - -# If I compare sample min variance portfolio to a ledoit-shrinkage or robust, -# I should use plotcov to compare covaiance matrices - - - - Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R 2014-05-22 14:02:34 UTC (rev 3389) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/data_prep.R 2014-05-23 14:27:11 UTC (rev 3390) @@ -1,25 +0,0 @@ - -##### Equity Data for Example 1 and Example 2 ##### -load("data/crsp_weekly.rda") - -equity.data <- cbind(largecap_weekly[,1:15], - midcap_weekly[,1:15], - smallcap_weekly[,1:5]) -market <- largecap_weekly[,21] -Rf <- largecap_weekly[,22] - -##### edhec Data for Example 3 and Example 4 ##### -# Load the updated edhec dataset -load("data/edhec.rda") - -# Prep data for Examples 3 and 4 -R <- edhec[,c("Convertible.Arbitrage", "Equity.Market.Neutral", - "Fixed.Income.Arbitrage", - "CTA.Global", "Emerging.Markets", "Global.Macro")] -# Abreviate column names for convenience and plotting -colnames(R) <- c("CA", "EMN", "FIA", "CTAG", "EM", "GM") - - -# clean up and remove the data we don't need -rm(largecap_weekly, midcap_weekly, smallcap_weekly, microcap_weekly) -rm(edhec) Deleted: pkg/PortfolioAnalytics/sandbox/RFinance2014/index.html =================================================================== --- pkg/PortfolioAnalytics/sandbox/RFinance2014/index.html 2014-05-22 14:02:34 UTC (rev 3389) +++ pkg/PortfolioAnalytics/sandbox/RFinance2014/index.html 2014-05-23 14:27:11 UTC (rev 3390) @@ -1,45546 +0,0 @@ - - - - Complex Portfolio Optimization with PortfolioAnalytics - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Complex Portfolio Optimization with PortfolioAnalytics

-

R/Finance 2014

-

Ross Bennett

-
-
-
- - - - -
-

Overview

-
-
-
    -
  • Discuss Portfolio Optimization
  • -
  • Introduce PortfolioAnalytics
  • -
  • Demonstrate PortfolioAnalytics with Examples
  • -
- - - -
- -
- - -
-

Modern Portfolio Theory

-
-
-

"Modern" Portfolio Theory (MPT) was introduced by Harry Markowitz in 1952.

- -

In general, MPT states that an investor's objective is to maximize portfolio expected return for a given amount of risk.

- -

General Objectives

- -
    -
  • Maximize a measure of gain per unit measure of risk
  • -
  • Minimize a measure of risk
  • -
- -

How do we define risk? What about more complex objectives?

- - - -
- -
- - -
-

Portfolio Optimization Objectives

-
-
-
    -
  • Minimize Risk - -
      -
    • Volatility
    • -
    • Tail Loss (VaR, ES)
    • -
    • Other Downside Risk Measure
    • -
  • -
  • Maximize Risk Adjusted Return - -
      -
    • Sharpe Ratio, Modified Sharpe Ratio
    • -
    • Several Others
    • -
  • -
  • Risk Budgets - -
      -
    • Equal Component Contribution to Risk (i.e. Risk Parity)
    • -
    • Limits on Component Contribution
    • -
  • -
  • Maximize a Utility Function - -
      -
    • Quadratic, CRRA, etc.
    • -
  • -
- - - -
- -
- - -
-

PortfolioAnalytics Overview

-
-
-

PortfolioAnalytics is an R package designed to provide numerical solutions and visualizations for portfolio optimization problems with complex constraints and objectives.

- -
    -
  • Support for multiple constraint and objective types
  • -
  • An objective function can be any valid R function
  • -
  • Modular constraints and objectives
  • -
  • Support for user defined moment functions
  • -
  • Visualizations
  • -
  • Solver agnostic
  • -
  • Support for parallel computing
  • -
- - - -
- -
- - -
-

Support Multiple Solvers

-
-
-

Linear and Quadratic Programming Solvers

- -
    -
  • R Optimization Infrastructure (ROI) - -
      -
    • GLPK (Rglpk)
    • -
    • Symphony (Rsymphony)
    • -
    • Quadprog (quadprog)
    • -
  • -
- -

Global (stochastic or continuous solvers)

- -
    -
  • Random Portfolios
  • -
  • Differential Evolution (DEoptim)
  • -
  • Particle Swarm Optimization (pso)
  • -
  • Generalized Simulated Annealing (GenSA)
  • -
- - - -
- -
- - -
-

Random Portfolios

-
-
-

PortfolioAnalytics has three methods to generate random portfolios.

- -
    -
  1. The sample method to generate random portfolios is based on an idea by Pat Burns.
  2. -
  3. The simplex method to generate random portfolios is based on a paper by W. T. Shaw.
  4. -
  5. The grid method to generate random portfolios is based on the gridSearch function in the NMOF package.
  6. -
- - - -
- -
- - -
-

Comparison of Random Portfolio Methods

-
-
-

- - - -
- -
- - -
-

Comparison of Random Portfolio Methods (Interactive!)

-
-
-
- -