library(quantmod)
library(PortfolioAnalytics)
Define the portfolio symbols
symbols <- c(
“EWJ”, #iShares Japan
“EWG”, #iShares Germany
“EWU”, #iShares UK
“EWC”, #iShares Canada
“EWY”, #iShares South Korea
“EWA”, #iShares Australia
“EWH”, #iShares Hong Kong
“EWS”, #iShares Singapore
“EWT”, #iShares Taiwan
“EWZ”, #iShares Brazil
“EFA”, #iShares EAFE
“ERUS”, #iShares Russia
“EZA”, #iShares South Africa
“EPP”, #iShares Pacific Ex Japan
“FXI” ,#iShare China Large-Cap
“SPY” #US
)
Fetch the closing prices
prices <- data.frame(lapply(symbols, function(sym) Ad(getSymbols(sym, auto.assign = FALSE))))
prices <- data.frame(Date = as.Date(“1970-01-01”))
for (sym in symbols) {
sym_data <- data.frame(Date = index(getSymbols(sym, auto.assign = FALSE)),
Ad(getSymbols(sym, auto.assign = FALSE)))
colnames(sym_data)[-1] <- sym
prices <- merge(prices, sym_data, by = “Date”, all = TRUE)
}
Define the portfolio
portfolio <- portfolio.spec(assets = symbols)
Add constraints
portfolio <- add.constraint(portfolio, type = “weight_sum”, min_sum = 0.95, max_sum = 1.05)
portfolio <- add.constraint(portfolio, type = “box”, min = 0.01, max = 0.5)
Define the optimization objective
portfolio <- add.objective(portfolio, type = “risk”, name = “var”, arguments = list(p = 0.95))
library(xts)
Set the date column as row names
rownames(prices) <- prices$Date
prices$Date <- NULL
Convert to a time series object
prices_xts <- xts(prices, order.by = as.Date(rownames(prices)))
names(prices_xts) <-c(“Japan”,”Germany”,”UK”,”Canada”,”South Korea”,”Australia”,”Hong Kong”,
“Singapore”,”Taiwan”,”Brazil”,”EAFE”,”Russia”,”South Africa”,”Pacific Ex Japan”,
“China”,”U.S.”)
tail(prices_xts)
Run the portfolio optimization
opt_portfolio <- optimize.portfolio(prices_xts, portfolio)
Optimize the portfolio
opt_portfolio <- optimize.portfolio(prices, portfolio)
Display the optimized weights
print(opt_portfolio$weights)
opt_portfolio
Create a vector of values for the pie chart
values <- c(opt_portfolio$weights)
Create a vector of labels for the pie chart
labels <- c(“Japan”, “Germany”, “UK”, “Canada”, “South Korea”, “Australia”, “Hong Kong”, “Singapore”, “Taiwan”, “Brazil”, “EAFE”, “Russia”, “South Africa”, “Pacific Ex Japan”, “China”, “U.S.”)
Create the pie chart
pie(values, labels = labels)
Add a title to the pie chart
title(“Allocation of Investments by Country”)
percent <- paste0(round(values * 100, 1), “%”)
legend(“topleft”, legend = paste(labels, percent, sep = ” – “), cex = 0.8, fill = rainbow(length(values)))