Last active
May 19, 2016 16:30
-
-
Save vladiim/87f15d241987c2f84cabab3c02320205 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # http://www.r-bloggers.com/portfolio-optimization-using-r-and-plotly/ | |
| library(PortfolioAnalytics) | |
| library(quantmod) | |
| library(PerformanceAnalytics) | |
| library(zoo) | |
| library(stringr) | |
| library(memoise) | |
| # library(plotly) | |
| # Vanguard® MSCI Australian Large Companies Index ETF ASX:VLC | |
| # Vanguard® MSCI Australian Small Companies Index ETF ASX:VSO | |
| # Vanguard® US Total Market Shares Index ETF ASX:VTS | |
| # Vanguard® All-World ex-US Shares Index ETF ASX:VEU | |
| # Vanguard® FTSE Emerging Markets Shares ETF ASX:VGE | |
| # iShares Core S&P Mid-Cap ETF ASX:IJH | |
| # iShares Asia 50 ETF ASX:IAA | |
| # Vanguard® Australian Government Bond Index ETF ASX:VGB | |
| # iShares Government Inflation ETF ASX:ILB | |
| SYMBOLS <- c('VTS.AX', 'VLC.AX', 'VEU.AX', 'VSO.AX', 'VGE.AX', 'IJH.AX', 'IAA.AX', 'VGB.AX', 'ILB.AX') | |
| extract.data <- memoise(function(symbols = SYMBOLS) { | |
| do.call(merge, lapply(symbols, function(symbol) { | |
| getSymbols(symbol, from = '2011-05-27', auto.assign = FALSE) | |
| })) | |
| }) | |
| transform.data <- function(symbols = SYMBOLS) { | |
| d <- extract.data(symbols) | |
| d <- d[, seq(from = 6, to = length(symbols) * 6, by = 6)] | |
| d <- na.omit(CalculateReturns(d)) | |
| names(d) <- symbols | |
| d | |
| } | |
| meanReturns <- colMeans(d) | |
| covMat <- cov(d) | |
| corMat <- cor(d) | |
| port <- portfolio.spec(assets = TICKERS) | |
| port <- add.constraint(port, type = "box", min = 0.05, max = 0.8) | |
| port <- add.constraint(portfolio = port, type = "full_investment") | |
| # Generate random portfolios | |
| rportfolios <- random_portfolios(port, permutations = 500000, rp_method = "sample") | |
| # Get minimum variance portfolio | |
| minvar.port <- add.objective(port, type = "risk", name = "var") | |
| # Optimize | |
| minvar.opt <- optimize.portfolio(returns.data, minvar.port, optimize_method = "random", rp = rportfolios) | |
| # Generate maximum return portfolio | |
| maxret.port <- add.objective(port, type = "return", name = "mean") | |
| # Optimize | |
| maxret.opt <- optimize.portfolio(returns.data, maxret.port, optimize_method = "random", rp = rportfolios) | |
| # Generate vector of returns | |
| minret <- 0.06/100 | |
| maxret <- maxret.opt$weights %*% meanReturns |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment