Question 1

knitr::opts_chunk$set(warning = FALSE, message = FALSE)
library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(Metrics)
library(zoo)
library(PerformanceAnalytics)
## 
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
## 
##     legend
library(xts)
library(ggplot2)


start_date = "2016-01-01"
end_date = "2019-12-01"
getSymbols("DECK", from = start_date, to = end_date, periodicity = "monthly")
## [1] "DECK"
getSymbols("NVDA", from = start_date, to = end_date, periodicity = "monthly")
## [1] "NVDA"
getSymbols("AAPL", from = start_date, to = end_date, periodicity = "monthly")
## [1] "AAPL"
getSymbols("COST", from = start_date, to = end_date, periodicity = "monthly")
## [1] "COST"
getSymbols("WST", from = start_date, to = end_date, periodicity = "monthly")
## [1] "WST"
COST_Price <- COST$COST.Adjusted
AAPL_Price <- AAPL$AAPL.Adjusted
WST_Price <- WST$WST.Adjusted
DECK_Price <- DECK$DECK.Adjusted
NVDA_Price <- NVDA$NVDA.Adjusted

returnCOST <- diff(log(COST_Price))
returnAAPL <- diff(log(AAPL_Price))
returnWST <- diff(log(WST_Price))
returnDECK <- diff(log(DECK_Price))
returnNVDA <- diff(log(NVDA_Price))


getSymbols("^GSPC", from=start_date, to=end_date, src ="yahoo",periodicity = "monthly")
## [1] "GSPC"
rGSPC <- diff(log(GSPC$GSPC.Adjusted))
rGSPC <- rGSPC [-1,]
getSymbols("^TNX", from = start_date, to = end_date, periodicity = "monthly", src = "yahoo")
## [1] "TNX"
priceTNX <- TNX$TNX.Adjusted
rTNX <- diff(log(priceTNX))/100

erCOST <- returnCOST - rTNX
erAAPL <- returnAAPL - rTNX
erWST <- returnWST - rTNX
erDECK <- returnDECK - rTNX
erNVDA <- returnNVDA - rTNX
erP <- rGSPC - rTNX

pricTab1 = data.frame(COST_Price, AAPL_Price, WST_Price, DECK_Price, NVDA_Price)
retTab1 = data.frame(returnCOST, returnAAPL, returnWST, returnDECK, returnNVDA)
EretTab1 = data.frame(erCOST, erAAPL, erWST, erDECK, erNVDA)
retTab1 = retTab1[-1,]              
EretTab1 = EretTab1[-1,]          
priceMat1 = matrix(c(COST_Price, AAPL_Price, WST_Price, DECK_Price, NVDA_Price), nrow = length(COST_Price), ncol=5, byrow=TRUE)

asset.names = c("COST", "AAPL", "WST", "DECK", "NVDA")
VCV = matrix(c(cov(retTab1)), nrow = 5, ncol = 5, byrow=TRUE)
dimnames(VCV) = list(asset.names, asset.names)

rm = matrix(colMeans(retTab1, na.rm = TRUE))  
erm = matrix(colMeans(EretTab1, na.rm = TRUE))
tnxy = mean((rTNX)[-1,])

retmat <- matrix(c(rm, erm), ncol=2)
dimnames(retmat) = list(asset.names, c("Return ", "Excess Return"))

VCV
##              COST        AAPL          WST         DECK        NVDA
## COST 0.0025427553 0.001524156 0.0017247503 0.0008156912 0.001770097
## AAPL 0.0015241558 0.006113342 0.0011472022 0.0010478265 0.006276000
## WST  0.0017247503 0.001147202 0.0042870318 0.0006131797 0.003857926
## DECK 0.0008156912 0.001047826 0.0006131797 0.0064240117 0.002493248
## NVDA 0.0017700972 0.006276000 0.0038579260 0.0024932479 0.017412551
retmat
##         Return  Excess Return
## COST 0.01669717    0.01671536
## AAPL 0.02336413    0.02338232
## WST  0.02103684    0.02105503
## DECK 0.02660588    0.02662407
## NVDA 0.04393162    0.04394981
cat("\n")
cat("Monthly Risk Free: ", tnxy)
## Monthly Risk Free:  -1.819007e-05
ZOPT <- solve(VCV,erm)                
WOPT <- ZOPT/sum(ZOPT)                          
dimnames(WOPT) <- list(asset.names, "Weights")  


ROPT <- t(WOPT)%*%rm                     
VOPT <- t(WOPT)%*%VCV%*%WOPT              
SDOPT <- VOPT^0.5                         
SRatio <-(ROPT-tnxy)/(SDOPT)             

PTBL <- matrix(c(ROPT, VOPT, SDOPT, SRatio), nrow = 4)            
optstat.names <- c("Return", "Variance", "Std Dev", "Sharpe")    

WOPT  
##         Weights
## COST 0.25824203
## AAPL 0.13552711
## WST  0.22762602
## DECK 0.29930505
## NVDA 0.07929978

After using Modern Modern Portfolio Theory and multiplying the Covariance Matrix by the Expected Returns of the stocks we get the following Optimal Weights:

COST 0.25824431 AAPL 0.13552562 WST 0.22762499 DECK 0.29930472 NVDA 0.07930036

Question 2

#GMV 
cat ("\n")
dimnames(PTBL) <- list(optstat.names, "Opt. Portfolio")    
PTBL
##          Opt. Portfolio
## Return      0.023713959
## Variance    0.002328892
## Std Dev     0.048258597
## Sharpe      0.491770380
ZGMV <- solve(VCV,matrix(c(1,1,1,1,1), byrow = TRUE)) 
WGMV <- ZGMV/sum(ZGMV)                                
dimnames(WGMV) <- list(asset.names, "Weights")        

#Calculate GMV Portfolio Stats
RGMV <- t(WGMV)%*%rm                                  
VGMV <- t(WGMV)%*%VCV%*%WGMV                          
SDGMV <- VGMV^0.5                                   

#Create GMV Stats Table
GTBL <- matrix(c(RGMV, VGMV, SDGMV), nrow = 3)         
gmvstat.names <- c("Return", "Variance", "Std Dev")   
dimnames(GTBL) <- list(gmvstat.names, "GMV Portfolio") 

#Display Data
WGMV
##         Weights
## COST  0.4118680
## AAPL  0.2162967
## WST   0.2648347
## DECK  0.2111198
## NVDA -0.1041192
j <- 0                                                          
return_p <- rep(0, 50000)
sd_p <- rep(0, 50000)                                              
vect_0 <- rep(0, 50000)                                           
fractions <- matrix(vect_0, 10000,5)                             

for (a in seq(-.2, 1, 0.1)) {                                     
    for (b in seq(-.2, 1, 0.1)) {                               
        for(c in seq(-.2, 1, 0.1)){                              
            for(d in seq(-.2, 1, 0.1)){                           
                for(e in seq(-.2, 1, 0.1)){                     
        if(a+b+c+d+e==1) {                                        
            j=j+1                                                
        fractions[j,] <- c(a,b,c,d,e)                             
         sd_p[j] <-  (t(fractions[j,])%*%VCV%*%fractions[j,])^.5  
        return_p[j] <-  fractions[j,]%*%rm                        
        
            }
            }
            }
            }
            }
            } 

Rport <- return_p[1:j]                                          
StdDev_p <- sd_p[1:j]                                             

f <- seq(0,.24, .24)                                             
CAL <- tnxy+SRatio*f        

plot(StdDev_p, Rport, col="green", xlab="Portfolio Standard Deviation", ylab= "Portfolio expected return", xlim=c(0, .2), ylim= c(0, .1))  
points(SDGMV, RGMV, col="red3", pch=17)                           
points(SDOPT, ROPT, col= "black", pch=16, bg="black")             
points(f, CAL, col= "cadetblue", type="l")                        
legend("bottomright",c("short sale", "GMV", "Tangency Porfolio", "CAL"),cex=.8,col=c("green1","red3", "black","cadetblue"),lty = c(0,0,0,1),pch=c(1,17,16,NA_integer_))

The efficient frontier, as well as the tangency point and the Capital Allocation Line are graphed above, along with tangency portfolio statistics. We can see that the tangency portfolio’s monthly return is 2.37%,the monthly standard deviation is 4.825%. We also have a Sharpe Ratio of 0.4917, which we use to build the CAL line (risk-free rate + sharpe*portfolio risk).

CAL Line Equation = 0.00189 + 0.4917*X, with Y being the portfolio’s expected return and X being the portfolio’s standard deviation

Question 3

start_date23 = "2020-01-01"
end_date23 = "2023-08-01"

DECK23 <- getSymbols("DECK", from = start_date23, to = end_date23, periodicity = "monthly")
NVDA23 <-getSymbols("NVDA", from = start_date23, to = end_date23, periodicity = "monthly")
AAPL23 <- getSymbols("AAPL", from = start_date23, to = end_date23, periodicity = "monthly")
COST23 <- getSymbols("COST", from = start_date23, to = end_date23, periodicity = "monthly")
WST23 <- getSymbols("WST", from = start_date23, to = end_date23, periodicity = "monthly")
getSymbols("^GSPC", from=start_date23, to=end_date23, src ="yahoo",periodicity = "monthly")
## [1] "GSPC"
rGSPC23 <- diff(log(GSPC$GSPC.Adjusted))
rGSPC23 <- rGSPC23 [-1,]
SP500 <- GSPC[,6]

getSymbols("^TNX", from = start_date23, to = end_date23, periodicity = "monthly", src = "yahoo")
## [1] "TNX"
priceTNX <- TNX$TNX.Adjusted
rTNX23 <- diff(log(priceTNX))/100

initial_priceWST <- WST[1,6]
initial_priceDECK <- DECK[1,6]
initial_priceAAPL <- AAPL[1,6]
initial_priceCOST <- COST[1,6]
initial_priceNVDA <- NVDA[1,6]

initialmatrix <- matrix(c(initial_priceCOST,initial_priceAAPL,initial_priceWST,initial_priceDECK,initial_priceNVDA),nrow = 5)
  
NumberofShares <- (WOPT*100/initialmatrix)


close_priceWST <- WST[,6]
close_priceDECK <- DECK[,6]
close_priceAAPL <- AAPL[,6]
close_priceCOST <- COST[,6]
close_priceNVDA <- NVDA[,6]

closematrix <- data.frame(close_priceCOST,close_priceAAPL,close_priceWST,close_priceDECK,close_priceNVDA)


portfolio_value <- as.matrix(closematrix) %*% NumberofShares
index <- 100/portfolio_value[1] * portfolio_value

SP500 <- as.matrix(SP500)
SP500_index <- 100/SP500[1]*SP500

dates <- seq(as.Date ("2020-01-01"), as.Date("2023-07-30"), by = "1 month")
Monthly_Index <- data.frame(Date =dates, Index = index)
SP500_index <- data.frame (Date = dates, Index = SP500_index)
colnames (SP500_index) [2] <- 'Index'

ggplot (data = Monthly_Index, aes (x = Date, y = index)) +
  geom_line (color ="cyan3") +
  geom_point (color = "cyan4",size = 1) +
  geom_hline (yintercept = 100, linetype = "dashed", color ="grey")+
  labs(title = "Tangency Portfolio Index (2020-2023)", X = "Date", у ="Index") +
  theme_minimal()

When allocating 100 USD we have to look at the initial stock prices in 2020M1 and buying the shares according to the weights we got in quesstion 2. This results in us purchasing the following number of shares: COST 0.08940569, AAPL 0.17978181, WST 0.14741012, DECK 0.15677795, NVDA 0.13467474

Holding these shares from 2020M1 to 2023M6 we see the index rise from 100 USD to 287 USD, meaning a 187% return in 3 years. The value of the portfolio throughout the period is presented in the “Tangency Portfolio Index (2020-2023)” graph above.

Question 4

portfolio_returns <- diff(log(portfolio_value))
portfolio_returns <- na.omit(portfolio_returns)
market_returns <- na.omit(rGSPC23)
portfolio_returns <- as.numeric(portfolio_returns)
market_returns <- as.numeric(market_returns)

rTNX23 <- rTNX23[-1]
risk_free_rate <- mean(rTNX23)


dates <- dates [-1]

portfolio_xts <- xts(portfolio_returns, order.by = dates)
market_xts <- xts(market_returns, order.by = dates)
beta <- CAPM.beta(portfolio_xts, market_xts, Rf = risk_free_rate)

average_return <- mean(portfolio_returns)
market_risk_premium <- mean(market_returns) - risk_free_rate
market_return <- mean(market_returns)
sml_x <- seq(0, 2, by = 0.01)
sml_y <- risk_free_rate + sml_x * market_risk_premium

sml_plot <- ggplot(data.frame(sml_x, sml_y), aes(x = sml_x, y = sml_y)) + 
  geom_line(color = "blue") + 
  geom_point(aes(x = beta, y = average_return), color = "red", size = 4) +
  xlab("Beta") + 
  ylab("Expected Return") +
  ggtitle("Security Market Line (SML)") +
  theme_minimal()

print(sml_plot)

market_excess_returns <- market_returns - risk_free_rate
portfolio_excess_returns <- portfolio_returns - risk_free_rate

capm_model <- lm(portfolio_excess_returns ~ market_excess_returns)

summary(capm_model)
## 
## Call:
## lm(formula = portfolio_excess_returns ~ market_excess_returns)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.091054 -0.024224  0.004811  0.030830  0.076942 
## 
## Coefficients:
##                       Estimate Std. Error t value Pr(>|t|)    
## (Intercept)           0.016040   0.006601   2.430   0.0197 *  
## market_excess_returns 1.087169   0.113271   9.598 6.22e-12 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.04236 on 40 degrees of freedom
## Multiple R-squared:  0.6972, Adjusted R-squared:  0.6897 
## F-statistic: 92.12 on 1 and 40 DF,  p-value: 6.222e-12
df <- data.frame(market_excess_returns, portfolio_excess_returns)

ggplot(df, aes(x = market_excess_returns, y = portfolio_excess_returns)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "red") +
  labs(x = "Market Return (RSP)", y = "Portfolio Return (WeightPortRet)") +
  theme(axis.text.x = element_text(face = "bold"),
        axis.text.y = element_text(face = "bold")) +
  geom_hline(yintercept = 0, linetype = "dashed", color = "black") +  
  geom_vline(xintercept = 0, linetype = "dashed", color = "black")

When estimating the CAPM, a regression was run first to see the validity of the results. and the beta calculated was 1.087. Moreover, we also had a statiscally significant Jensen Alpha that has a value of 0.016040, indicating that the portofolio has performed better than predicted by CAPM.

This is also reflected on the Security Market Line (SML) graph, as the portfolio’s point is above the SML, which suggests that it is generating a higher return than what would be expected for its level of risk, as per the CAPM. This is generally a sign of a strong portfolio performance, and a performance better than the S&P 500

Question 5

portfolio_xts <- xts(portfolio_returns, order.by = dates)

shutdown_dummy <- ifelse(index(portfolio_xts) >= as.Date("2020-03-01") & index(portfolio_xts) <= as.Date("2020-08-31"), 1, 0)

shutdown_dummy_xts <- xts(shutdown_dummy, order.by = index(portfolio_xts))

market_xts <- xts(market_returns, order.by = index(portfolio_xts))

excess_market_returns <- market_xts - risk_free_rate

market_interaction <- excess_market_returns * shutdown_dummy
market_interaction_xts <- xts(market_interaction, order.by = index(portfolio_xts))

covid <- lm(portfolio_xts ~ excess_market_returns + shutdown_dummy_xts + market_interaction_xts)

summary(covid)
## 
## Call:
## lm(formula = portfolio_xts ~ excess_market_returns + shutdown_dummy_xts + 
##     market_interaction_xts)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.084901 -0.022472  0.001991  0.031973  0.081757 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             0.011973   0.006921   1.730   0.0918 .  
## excess_market_returns   1.147792   0.130783   8.776 1.13e-10 ***
## shutdown_dummy_xts      0.035405   0.019213   1.843   0.0732 .  
## market_interaction_xts -0.314070   0.251414  -1.249   0.2192    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.04135 on 38 degrees of freedom
## Multiple R-squared:  0.7259, Adjusted R-squared:  0.7042 
## F-statistic: 33.54 on 3 and 38 DF,  p-value: 9.041e-11

In order to see if there was any significant difference, a regression has to be run with the inclusion of dummy variables. In this case looking at dummy variables “shutdown_dummy_xts” and “market_interaction_xts” show that the pandemic did not have an impact on the Jensen alpha and the market risk of the CAPM model with both variables having a p-value greater than 0.05 showing statistical insignificance at a 95% confidence interval.

Question 6

start_date23 = "2020-01-01"
end_date23 = "2023-08-01"

getSymbols("VTI", from=start_date23, to=end_date23, src ="yahoo",periodicity = "monthly")
## [1] "VTI"
rVTI <- diff(log(VTI$VTI.Adjusted))
rVTI <- na.omit(rVTI)

vanguard_xts <- xts(rVTI, order.by = dates)

#Coefficient of Variation (CV)
calculateCV <- function(x) {
  return(sd(x, na.rm = TRUE) / mean(x, na.rm = TRUE))
}

cv <- calculateCV(portfolio_returns)
cvVTI <- calculateCV(rVTI)

# Sharpe Ratio
sharpe_ratio <- SharpeRatio.annualized(portfolio_xts, Rf = risk_free_rate)
vangaurdsharpe_ratio <- SharpeRatio.annualized(vanguard_xts, Rf = risk_free_rate)

# Sortino Ratio
sortino_ratio <- SortinoRatio(portfolio_xts, MAR = risk_free_rate)
vangaurdsortino_ratio <- SortinoRatio(vanguard_xts, MAR = risk_free_rate)

# Treynor Ratio
treynor_ratio <- TreynorRatio(portfolio_xts, market_xts, Rf = risk_free_rate)
vanguardtreynor_ratio <- TreynorRatio(vanguard_xts, market_xts, Rf = risk_free_rate)

print(paste("Coefficient of Variation Portfolio:", cv))
## [1] "Coefficient of Variation Portfolio: 3.02373103287198"
print(paste("Coefficient of Variation Vanguard:", cvVTI))
## [1] "Coefficient of Variation Vanguard: 6.60823964972952"
print(paste("Sharpe Ratio of Portfolio:", sharpe_ratio))
## [1] "Sharpe Ratio of Portfolio: 1.13662374380943"
print(paste("Sharpe Ratio of Vanguard:", vangaurdsharpe_ratio))
## [1] "Sharpe Ratio of Vanguard: 0.422625988981272"
print(paste("Sortino Ratio of Portfolio:", sortino_ratio))
## [1] "Sortino Ratio of Portfolio: 0.540957949946349"
print(paste("Sortino Ratio of Vanguard:", vangaurdsortino_ratio))
## [1] "Sortino Ratio of Vanguard: 0.216624219126473"
print(paste("Treynor Ratio of Portfolio:", treynor_ratio))
## [1] "Treynor Ratio of Portfolio: 0.275374226801952"
print(paste("Treynor Ratio of Vanguard:", vanguardtreynor_ratio))
## [1] "Treynor Ratio of Vanguard: 0.0859603336907237"

When comparing my Portfolio and the Vanaguard Portfolio with the various risk-adjusted performance metrics it is clear that my portfolio outperforms Vanguard VTI.

With a smaller Coefficient of Variation, it tell me my portfolio has less variability. Moreover, the higher Sharpe Ratio suggests that my portfolio provides a better return per unit of risk than Vanguard VTI. The higher Sortino Ratio indicates a better return on bad risk. Finally, the higher Treynor Ratio indicates a higher return per unit of market risk.

Question 7

mean_return_monthlyVTI <- mean(rVTI)   
mean_return_six_monthsVTI <- mean(rVTI) * 6  
mean_return_annualVTI <- mean(rVTI) * 12  

mean_return_monthly <- mean(portfolio_returns)   
mean_return_six_months <- mean(portfolio_returns) * 6  
mean_return_annual <- mean(portfolio_returns) * 12  

VaR_2_percent <- quantile(portfolio_returns, 0.02)
VaR_2_percentVTI <- quantile(rVTI, 0.02)

VaR_monthly <- VaR_2_percent 
VaR_six_months <- VaR_2_percent * sqrt(6)
VaR_annual <- VaR_2_percent * sqrt(12)

VaR_monthlyVTI <- VaR_2_percentVTI 
VaR_six_monthsVTI <- VaR_2_percentVTI * sqrt(6)
VaR_annualVTI <- VaR_2_percentVTI * sqrt(12)


print(paste("Portfolio One Month VaR :", VaR_monthly))
## [1] "Portfolio One Month VaR : -0.139595899405549"
print(paste("Portfolio 6 Month VaR:", VaR_six_months))
## [1] "Portfolio 6 Month VaR: -0.341938723728484"
print(paste("Portfolio 1-year VaR:", VaR_annual))
## [1] "Portfolio 1-year VaR: -0.483574380597369"
print(paste("Vanguard One Month VAR:", VaR_monthlyVTI))
## [1] "Vanguard One Month VAR: -0.11068928267001"
print(paste("Vanguard Six Month VAR:", VaR_six_monthsVTI))
## [1] "Vanguard Six Month VAR: -0.271132262536217"
print(paste("Vanguard 1-year VaR:", VaR_annualVTI))
## [1] "Vanguard 1-year VaR: -0.383438922875621"

When comparing my portfolio to Vangaurd, the Vanguard fund demonstrates lower risk as indicated by its VaR values compared to my portfolio. The less negative the VaR, the lower the expected loss, hence, Vanguard is portrayed as a safer investment in this comparison across all time horizons.

Question 8

portfolio_df <- data.frame(portfolio_xts)
market_df <- data.frame(market_xts)
plot(dates,portfolio_df$portfolio_xts, col = 'black', 
     type = 'l',
     main = 'Return of Portfolio and S&P',
     ylab = 'Period Return',
     xlab = 'Dates'
     )
lines(dates,market_df$market_xts, col = 'red')
legend("bottomleft", legend = c("Portfolio", "S&P"), lty = 1, col = c('black', 'red'))

The graph above compares the returns of my portfolio (blue line) and the S&P (red line) from 2020 to 2023.It seem like my portfolio exhibits more pronounced volatility with sharper peaks and troughs than the S&P, suggesting higher risk and deviation from the market benchmark. No clear trend is evident, and no outliers are present. Finally, structural shifts are noticeable around early 2021 and mid-2022, where the behavior of returns changes noticeably. My portfolio’s returns frequently diverge from the S&P’s, indicating periods of over- or under-performance relative to the market.

Question 9

print(portfolio_returns)
##  [1] -0.061473451 -0.073056327  0.127953752  0.122308903  0.054508709
##  [6]  0.112873933  0.079950454 -0.001765963  0.017131739  0.044053179
## [11]  0.044643160  0.010500514 -0.001088016  0.015272086  0.080298291
## [16]  0.019213989  0.095640374  0.076536832  0.064717157 -0.080358688
## [21]  0.081760245  0.083863495 -0.007671401 -0.133761059 -0.030184096
## [26]  0.054813259 -0.166176837 -0.039852932 -0.050791380  0.157396774
## [31] -0.062862645 -0.115595121  0.061334141  0.082890803 -0.071898192
## [36]  0.119537803  0.043130995  0.090173387  0.034790272  0.045085750
## [41]  0.101256284  0.031033912
library(Metrics)

train_size <- length(portfolio_returns) - 2  
train_set <- data.frame(
  portfolio_excess_returns = portfolio_excess_returns[1:train_size], 
  market_excess_returns = market_excess_returns[1:train_size]
)
test_set <- data.frame(
  portfolio_excess_returns = portfolio_excess_returns[(train_size+1):(train_size+2)], 
  market_excess_returns = market_excess_returns[(train_size+1):(train_size+2)]
)

capm_model <- lm(portfolio_excess_returns ~ market_excess_returns, data = train_set)

pred <- predict(capm_model, newdata = test_set)

mae_post <- mae(test_set$portfolio_excess_returns, pred)
mape_post <- mape(test_set$portfolio_excess_returns, pred)
rmse_post <- rmse(test_set$portfolio_excess_returns, pred)
mase_post <- mase(test_set$portfolio_excess_returns, pred)

Results_post <- data.frame(
  Method = 'EX_POST_F',
  MAE = mae_post,
  MAPE = mape_post,
  RMSE = rmse_post,
  MASE = mase_post
)
print(Results_post)
##      Method        MAE      MAPE       RMSE      MASE
## 1 EX_POST_F 0.01774731 0.3817042 0.01775481 0.2527302
capm_model
## 
## Call:
## lm(formula = portfolio_excess_returns ~ market_excess_returns, 
##     data = train_set)
## 
## Coefficients:
##           (Intercept)  market_excess_returns  
##                0.0161                 1.0834
plot(portfolio_excess_returns, type="l", col="red")
lines(capm_model$fitted.values, col="blue")

pred <- predict(capm_model, newdata = test_set,se.fit=TRUE)
pred
## $fit
##          1          2 
## 0.08379704 0.04906929 
## 
## $se.fit
##           1           2 
## 0.009500468 0.007405127 
## 
## $df
## [1] 38
## 
## $residual.scale
## [1] 0.04326623

Using the estimated CAPM equation of the portfolio, I did two periods of ex-post forecasting of the returns to my portfolio and compared it to the actual portfolio returns. This resulted in a forecasted return of 0.08379704 and 0.007405138 for the months of July and August, with the actual returns being 0.101256227 and 0.031034101.

Talking about accuracy, my forecast had a MAE, MAPE, RMSE, and MASE of 0.0177, 0.3816, 0.01775, and 0.2527, respectively. With a MASE less than 1 and of approximately 0.2527 my forecasting model is at least better than what naive model would be. However, despite being better than the naive forecast,my forecast has a MAPE of 38.17% which would suggest that this is not a good forecast model, because the MAPE is greater than 10%.

Question 10

capm_model <- lm(portfolio_excess_returns ~ market_excess_returns, data = train_set)
library("forecast")
fore <- forecast(capm_model, newdata=data.frame(market_excess_returns=c(-0.02309905,-0.05082038)))
fore
##   Point Forecast       Lo 80      Hi 80       Lo 95      Hi 95
## 1    -0.00892970 -0.06623578 0.04837638 -0.09787879 0.08001939
## 2    -0.03896252 -0.09675509 0.01883006 -0.12866674 0.05074170
plot(fore, type="l")

I used the CAPM equation to make two ex-ante periods that forecast returns for my portfolio for 2023M9 and 2023M10. Given the data, we are expecting a forecast loss of less than 1% in September 2023 with it being around -0.089% and 3.89% loss in October 2023. Additonally, we are 95% confident that in September the returns will be between -9.78% - 8% and in October the returns will be somewhere between -12.86% and 5.07%

Question 11

library(Metrics)
samplestart4<- as.Date('2020-01-01')
sampleend4 <- as.Date('2023-08-01')

start_date1 = "2016-01-01"
end_date1 = "2023-10-01"

DECK23 <- getSymbols("DECK", from = start_date1, to = end_date1, periodicity = "monthly")
NVDA23 <-getSymbols("NVDA", from = start_date1, to = end_date1, periodicity = "monthly")
AAPL23 <- getSymbols("AAPL", from = start_date1, to = end_date1, periodicity = "monthly")
COST23 <- getSymbols("COST", from = start_date1, to = end_date1, periodicity = "monthly")
WST23 <- getSymbols("WST", from = start_date1, to = end_date1, periodicity = "monthly")

start_date1 <- as.Date("2016-01-01")
end_date1  <- as.Date("2023-10-01")

sampleend4 <- as.Date(sampleend4)
start_date <- as.Date(start_date1)
monthindex4 <- as.numeric((sampleend4 - start_date1) / 30) + 1
skipped4<- as.numeric((samplestart4 - start_date1)/30)+1

priceDECK1 <-DECK[skipped4 :monthindex4,6]
priceNVDA1 <- NVDA[skipped4 :monthindex4,6]
priceAAPL1 <- AAPL[skipped4 :monthindex4,6]
priceCOST1 <- COST[skipped4 :monthindex4,6]
priceWST1 <- WST[skipped4 :monthindex4,6]

indexmat1 <- cbind.xts(priceDECK1,priceNVDA1,priceAAPL1,priceCOST1,priceWST1)

Port4 <- ts(indexmat1%*%WOPT,start = 2020, frequency = 12)

Lagged <- rwf(Port4,3)
plot(Lagged, ylab = 'Indexed Portfolio')

MovAvg <- ma(Port4, order = 15)
plot(Port4, ylab = 'Indexed Portfolio')
lines(MovAvg, col = 'blue')

ESfit1 <- ses(Port4, alpha=0.2, initial="simple", h=3)
ESfit2 <- ses(Port4, alpha=0.6, initial="simple", h=3)
ESfit3 <- ses(Port4, h=3)


plot(ESfit1, main="Simple Exponential Smoothing, S&P500", 
     fcol="white", 
     type="o")
lines(fitted(ESfit1), col="purple3", type="o")
lines(fitted(ESfit2), col="black", type="o")
lines(fitted(ESfit3), col="green3", type="o")
lines(ESfit1$mean, col="purple3", type="o")
lines(ESfit2$mean, col="black", type="o")
lines(ESfit3$mean, col="green3", type="o")
legend("topleft",lty=1, col=c(1,"purple3","black","green3"), 
       c("data", expression(alpha == 0.2), expression(alpha == 0.6),
         expression(alpha == 0.99 )),pch=1)

mae <- mae(Port4[8:(length(Port4)-7)], na.omit(MovAvg))
mse <- mse(Port4[8:(length(Port4)-7)], na.omit(MovAvg))
rmse <- sqrt(mse)
mape <- mape(Port4[8:(length(Port4)-7)],na.omit(MovAvg))

accuracy_matrix <- matrix(c(MAE = mae, RMSE = rmse, MAPE = mape, MSE = mse), 
                          nrow = 1, 
                          dimnames = list(c(" "), 
                                          c("MAE", "RMSE", "MAPE", "SE")))


detach("package:Metrics", unload=TRUE)

accuracy(ESfit1)
##                  ME     RMSE      MAE     MPE     MAPE      MASE      ACF1
## Training set 25.176 39.56139 33.41184 7.76125 11.04223 0.4381552 0.7309217
accuracy(ESfit2)
##                    ME    RMSE      MAE      MPE    MAPE     MASE     ACF1
## Training set 10.02139 23.4943 20.61146 3.085296 6.94027 0.270294 0.321585
accuracy(ESfit3)
##                    ME     RMSE      MAE      MPE     MAPE      MASE        ACF1
## Training set 6.117257 21.06077 17.18289 1.893078 5.783329 0.2253325 -0.03122839
ESfit3$model$par
##       alpha           l 
##   0.9998999 173.0746629
accuracy(Lagged)
##                    ME     RMSE      MAE      MPE     MAPE      MASE        ACF1
## Training set 6.257407 21.30413 17.58073 1.936058 5.916846 0.2305496 -0.03798586
print(accuracy_matrix)
##        MAE     RMSE       MAPE       SE
##   17.92031 23.55239 0.05830764 554.7149

The charts above display three different types forecasting: Naive Forecast, Moving Average (15) and Exponential Smoothing. To determine which of the forecats is the most precise we have to look at accuracy statistics. For the Naive Forecast we got MAE: 17.58073, MAPE: 5.916843 and RMSE: 21.3041. On the otherhand, the Moving Average (15) showed worse accuracy statistics having MAE: 17.9203, MAPE: 0.05830753 and RMSE: 23.55238. We know the Moving Average Forecast was worse because of the higher RMSE value.

The last forecast, the Exponential Smoothing Forecast at an alpha of 0.99 ended up being the most accurate as it had a MAE: 17.181, MAPE: 5.7826 and RMSE: 21.0607. Though it was very close with the naive forecast, the Exponential Smoothing Forecast at alpha 0.99 still had a lower RMSE and therefore is the best forecast.