Skip to content

Instantly share code, notes, and snippets.

@bestdan
Last active December 11, 2015 21:58
Show Gist options
  • Save bestdan/4665749 to your computer and use it in GitHub Desktop.
Save bestdan/4665749 to your computer and use it in GitHub Desktop.
efficientFrontier_v1.R
effFrontier = function (data, nports = 20, shorts=T,wmin=0, wmax=1)
{
rcov<-cov(data)
averet<-colMeans(data)
mxret = max((colMeans(data)))
mnret = 0#-mxret Long only...
n.assets = ncol(data)
reshigh = rep(wmax,n.assets)
if( shorts )
{
reslow = rep(-wmax,n.assets)
} else {
reslow = rep(wmin,n.assets)
}
min.rets = seq(mnret, mxret, len = nports)
vol = rep(NA, nports)
ret = rep(NA, nports)
pws = matrix(NA,ncol=n.assets, nrow=nports)
for (k in 1:nports)
{
port.sol = NULL
try(port.sol <- portfolio.optim(data, pm=min.rets[k],
reshigh=reshigh, reslow=reslow,shorts=shorts),silent=T)
if ( !is.null(port.sol) )
{
vol[k] = sqrt(as.vector(port.sol$pw %*% rcov %*% port.sol$pw))
ret[k] = averet %*% port.sol$pw
pws[k,] = port.sol$pw
}
}
return(list(vol = vol, ret = ret,pws=pws))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment