Created
July 19, 2014 19:58
-
-
Save mbusigin/7b01c307916cd5ae7e45 to your computer and use it in GitHub Desktop.
Estimate a portfolio's return and risk
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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