Skip to content

Instantly share code, notes, and snippets.

@mbusigin
Created July 19, 2014 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbusigin/7b01c307916cd5ae7e45 to your computer and use it in GitHub Desktop.
Save mbusigin/7b01c307916cd5ae7e45 to your computer and use it in GitHub Desktop.
Estimate a portfolio's return and risk
create.portfolio <- function( tickers=c('SPY', 'AGG', 'TLT', 'GLD'), weights=NULL, er=NULL, ev=NULL )
{
e = new.env()
getSymbols(tickers, from="1950-01-01", env=e)
a = NULL
for ( i in 1:length(tickers) )
{
a = cbind(a, annualReturn( get(tickers[i], e) ))
}
if ( is.null(weights) )
{
weights = rep(1/length(tickers), length(tickers))
}
a = na.omit(a)
names(a) = tickers
covmat = cov(a)
if ( is.null(er) )
{
er = as.vector(last(a))
}
if ( !is.null(ev) )
{
diag(covmat) = ev^2
}
vol = sqrt(weights %*% covmat %*% weights)
per = weights %*% er
pf = list(
"weights" = weights,
"sd" = vol,
"er" = per
)
pf
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment