Solving Factor Models

"Solving Factor Models in fPortfolio" was the topic in Diethelm Würtz' last econophysics lecture at ETH Zurich (May 2010). Since this may be of general interest we will give in the following some hints how to do it.

Start to read Chapter 15, of Eric's wonderful book "Modeling Financial Time Series with S-Plus" to learn how factor models work. Then load Berndt's Investment data set from the fEcofin package and write a mean covariance estimator function for Sharpe's Single Index Model as described in Eric's book.

# Load Libraries:
library(fEcofin)
library(fPortfolio)

# Load Data:
data(berndtInvest)
berndt <- as.timeSeries(berndtInvest)
names(data)
data <- berndt[, -c(10, 17)]
factors <- berndt[, 10]
attr(data, "factors") <- factors

# Sharpe's Single Index Factor Model:
sharpeFactorEstimator <- 
function(x, spec=NULL, ...)
{
    # Sharpe Single Index Model:
    data <- getDataPart(x)
    factors <- attr(x, "factors")
    nScenarios <- nrow(data)
    X.mat <- cbind(rep(1, times=nScenarios), factors)
    G.hat <- solve(qr(X.mat), data)
    beta.hat <- G.hat[2, ]
    eps.hat <- data - X.mat %*% G.hat
    diagD.hat <- diag(crossprod(eps.hat) / (nScenarios-2))
    mu <- G.hat[1, ] + G.hat[2, ] * colMeans(factors)  
    Sigma <- var(factors)[[1]] * (beta.hat %o% beta.hat) + diag(diagD.hat)
    
    # Return Value:
    list(mu = mu, Sigma = Sigma)
}

# Solve Long Only Markowitz Model:
markowitz <- portfolioFrontier(data)

# Solve Long Only Sharpe Single Index Model:
spec <- portfolioSpec()
setEstimator(spec) <- "sharpeFactorEstimator"
sharpe <- portfolioFrontier(data, spec)

# Plot:
tailoredFrontierPlot(markowitz)
points(frontierPoints(sharpe), col = "steelblue")

The plot shows the result for the long only Markowitz portfolio (full grey and black dots)  in comparison to Sharpe's Single Index Model (steelblue circles).

Isn't it easy? In the same way you can implement estimators for related factor models:

FUNCTION:                     DESCRIPTION:
sharpeFactorEstimator()       Sharpe's single index model
macroFactorEstimator()        General macroeconomic factor model
industryFactorEstimator()     Barra industry factor model
statisticalFactorEstimator()  Statistical factor model
pcaFactorEstimator()          PCA statistical factor model
asympcaFactorEstimator()      Asymptotic PCA statistical factor model

References:
Würtz, Chalabi, Chen, Ellis, Portfolio Optimization with R/Rmetrics, Rmetrics and Finance Online Publishing, Zurich 2009
Zivot and Wang, Modeling Financial Time Series with S-PLUS. Springer Publishing New York, 2nd edition 2006

Any Questions?
Do not hesitate to contact us or come to the Meielisalp 2010 Workshop to meet the authors.