I wanted to try out the tawny package (v2.1.6) for its portfolio optimization with shrinkage estimators and ran the following example from the documentation page (R 3.4.1 on Win 7):
require(tawny)
require(tawny.types)
require(PerformanceAnalytics)
# Select a portfolio using 200 total observations
data(sp500.subset)
h <- sp500.subset
p <- TawnyPortfolio(h, 150)
b <- BenchmarkPortfolio('^GSPC', 150, nrow(h), end=end(h))
# Optimize using a window of length 200 (there will be 51 total iterations)
ws <- optimizePortfolio(p, RandomMatrixDenoiser())
rs <- PortfolioReturns(p, ws)
o <- zoo(cbind(portfolio=rs, benchmark=b$returns), index(rs))
charts.PerformanceSummary(o)
At line rs <- PortfolioReturns(p, ws)
I get stuck with error:
Error in UseFunction(type.fn, type.name, ...) :
No valid function for 'PortfolioReturns(TawnyPortfolio,xts)'
The only conclusion I can draw from debugging the UseFunction
in the lambda.r package is, that the PortfolioReturns function expects the second argument as numeric while I am supplying an xts object. I tried supplying a numeric matrix instead of the xts i.e. as.numeric(coredata(ws))
- without success. My R/lambda.r-expertise is not good enough to take it any further.
I have two questions:
1) Am I wasting my time with the tawny package (alpha release)? Are there better alternatives you can recommend?
2) Alternatively, is there a way to fix and use that example?
For now, I went the manual route. I replaced the PortfolioReturns()
function by MyPortfolioReturns()
using the original as blueprint:
MyPortfolioReturns <- function(h, weights) {
w.index <- c(index(weights[2:nrow(weights)]), end(weights) + 1)
index(weights) <- w.index
h.trim <- h[index(h) %in% index(weights)]
ts.rets <- apply(xts(h.trim) * weights, 1, sum)
ts.rets <- xts(ts.rets, order.by=index(h.trim))
if (any(is.na(ts.rets)))
{
cat("WARNING: Filling NA returns with 0\n")
ts.rets[is.na(ts.rets)] <- 0
}
return(ts.rets)
}
Note that tawny shifts the weights by one day, as they are applied the following day.
The rest of the demo code needs some slight adjustments:
rs <- MyPortfolioReturns(p$returns, ws)
o <- xts(cbind(portfolio=rs, benchmark=b$returns[151:200,]), index(rs))
charts.PerformanceSummary(o)
At least now I can chart the results from the portfolio optimization.