This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
You can also embed plots, for example:
Note that the echo = FALSE parameter was added to the
code chunk to prevent printing of the R code that generated the
plot.
library(quantmod) library(PerformanceAnalytics) library(tseries) library(ggplot2) library(xts) library(dplyr)
data <- read.csv(“myetf4.csv”) data\(Date <- as.Date(data\)Date, format=“%Y-%m-%d”)
prices <- xts(data[, -1], order.by = data$Date)
daily_returns <- ROC(prices, type=“discrete”)[-1, ]
cov_matrix <- cov(daily_returns, use = “complete.obs”)
inv_cov <- solve(cov_matrix) one_vec <- rep(1, ncol(inv_cov)) w_gmvp <- inv_cov %% one_vec / sum(inv_cov %% one_vec)
gmvp_return <- colMeans(daily_returns, na.rm = TRUE) %% w_gmvp gmvp_sd <- sqrt(t(w_gmvp) %% cov_matrix %*% w_gmvp)
monthly_prices <- to.monthly(prices, indexAt=‘lastof’, OHLC=FALSE) monthly_returns <- ROC(monthly_prices, type=“discrete”)[-1, ]
cov_matrix_monthly <- cov(monthly_returns, use = “complete.obs”)
inv_cov_monthly <- solve(cov_matrix_monthly) w_gmvp_monthly <- inv_cov_monthly %% one_vec / sum(inv_cov_monthly %% one_vec)
gmvp_return_monthly <- colMeans(monthly_returns, na.rm = TRUE) %% w_gmvp_monthly gmvp_sd_monthly <- sqrt(t(w_gmvp_monthly) %% cov_matrix_monthly %*% w_gmvp_monthly)
mu <- colMeans(monthly_returns, na.rm = TRUE) w_tangency <- inv_cov_monthly %% mu / sum(inv_cov_monthly %% mu)
tangency_return <- sum(mu * w_tangency) tangency_sd <- sqrt(t(w_tangency) %% cov_matrix_monthly %% w_tangency)
list( GMVP_Daily = list(weights = w_gmvp, return = gmvp_return, sd = gmvp_sd), GMVP_Monthly = list(weights = w_gmvp_monthly, return = gmvp_return_monthly, sd = gmvp_sd_monthly), Tangency = list(weights = w_tangency, return = tangency_return, sd = tangency_sd) )