knitr::opts_chunk$set(echo = TRUE)
# Load necessary libraries
library(xts)
library(PerformanceAnalytics)

# 1. Load and prepare the data
df <- read.csv("myetf4.csv")
df$Index <- as.Date(df$Index, format="%Y/%m/%d")

# Convert to xts object and filter for the dates 2015-12-14 to 2018-12-28
prices_xts <- xts(df[,-1], order.by=df$Index)
prices_insample <- prices_xts["2015-12-14/2018-12-28"]

# --- Q1: Daily Returns ---
# Calculate daily returns
ret_daily <- na.omit(Return.calculate(prices_insample, method="discrete"))

# Compute Covariance and Mean
cov_d <- cov(ret_daily)
mu_d <- colMeans(ret_daily)
inv_cov_d <- solve(cov_d)
ones_d <- rep(1, ncol(ret_daily))

# GMVP Weights (Daily)
w_gmvp_d <- (inv_cov_d %*% ones_d) / as.numeric(t(ones_d) %*% inv_cov_d %*% ones_d)
ret_gmvp_d <- t(w_gmvp_d) %*% mu_d
std_gmvp_d <- sqrt(t(w_gmvp_d) %*% cov_d %*% w_gmvp_d)

cat("Q1 Daily Weights:\n"); print(w_gmvp_d)
## Q1 Daily Weights:
##                [,1]
## tw0050   -0.2193579
## tw0056    0.7283718
## tw006205  0.1076234
## tw00646   0.3833627
cat("Daily Return:", ret_gmvp_d, "| Daily Std:", std_gmvp_d, "\n\n")
## Daily Return: 0.0002536645 | Daily Std: 0.005904941
# --- Q2: Monthly Returns ---
# Resample to monthly prices and calculate returns
prices_monthly <- prices_insample[endpoints(prices_insample, on="months")]
ret_monthly <- na.omit(Return.calculate(prices_monthly, method="discrete"))

# Compute Covariance and Mean
cov_m <- cov(ret_monthly)
mu_m <- colMeans(ret_monthly)
inv_cov_m <- solve(cov_m)
ones_m <- rep(1, ncol(ret_monthly))

# GMVP Weights (Monthly)
w_gmvp_m <- (inv_cov_m %*% ones_m) / as.numeric(t(ones_m) %*% inv_cov_m %*% ones_m)
ret_gmvp_m <- t(w_gmvp_m) %*% mu_m
std_gmvp_m <- sqrt(t(w_gmvp_m) %*% cov_m %*% w_gmvp_m)

cat("Q2 Monthly Weights:\n"); print(w_gmvp_m)
## Q2 Monthly Weights:
##                 [,1]
## tw0050   0.003183861
## tw0056   0.474049044
## tw006205 0.001203750
## tw00646  0.521563345
cat("Monthly Return:", ret_gmvp_m, "| Monthly Std:", std_gmvp_m, "\n\n")
## Monthly Return: 0.005733667 | Monthly Std: 0.02490441
# --- Q3: Tangency Portfolio (Monthly) ---
rf <- 0 # Risk-free rate

# Tangency Weights
w_tan_m <- (inv_cov_m %*% (mu_m - rf)) / as.numeric(t(ones_m) %*% inv_cov_m %*% (mu_m - rf))
ret_tan_m <- t(w_tan_m) %*% mu_m
std_tan_m <- sqrt(t(w_tan_m) %*% cov_m %*% w_tan_m)

cat("Q3 Tangency Weights:\n"); print(w_tan_m)
## Q3 Tangency Weights:
##                [,1]
## tw0050    1.3050535
## tw0056   -0.1576807
## tw006205 -0.8475320
## tw00646   0.7001591
cat("Tangency Return:", ret_tan_m, "| Tangency Std:", std_tan_m, "\n")
## Tangency Return: 0.01809002 | Tangency Std: 0.04423638