rm(list=ls())
# DATA
firm_data <- read.csv("~/Desktop/3firmExample_data1.csv")
str(firm_data)
## 'data.frame':    59 obs. of  4 variables:
##  $ date     : chr  "Mar-95" "Apr-95" "May-95" "Jun-95" ...
##  $ Nordstrom: num  -0.03615 -0.0568 0.07821 -0.00302 -0.02757 ...
##  $ Starbucks: num  0.00521 -0.02105 0.21244 0.2036 0.04797 ...
##  $ Microsoft: num  0.1213 0.13923 0.03529 0.06501 0.00138 ...
library(xts)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## ################################### WARNING ###################################
## # We noticed you have dplyr installed. The dplyr lag() function breaks how    #
## # base R's lag() function is supposed to work, which breaks lag(my_xts).      #
## #                                                                             #
## # If you call library(dplyr) later in this session, then calls to lag(my_xts) #
## # that you enter or source() into this session won't work correctly.          #
## #                                                                             #
## # All package code is unaffected because it is protected by the R namespace   #
## # mechanism.                                                                  #
## #                                                                             #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## # You can use stats::lag() to make sure you're not using dplyr::lag(), or you #
## # can add conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop   #
## # dplyr from breaking base R's lag() function.                                #
## ################################### WARNING ###################################
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
date <- lubridate::my(firm_data[,1])
firm_data.xts <- as.xts(firm_data[, -1], order.by = date)
class(firm_data.xts)
## [1] "xts" "zoo"
library(quantmod)
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr   1.1.0     ✔ readr   2.1.4
## ✔ forcats 1.0.0     ✔ stringr 1.5.0
## ✔ ggplot2 3.4.1     ✔ tibble  3.1.8
## ✔ purrr   1.0.1     ✔ tidyr   1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::first()  masks xts::first()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::last()   masks xts::last()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(tidyquant)
## Loading required package: PerformanceAnalytics
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend
library(fBasics)
## 
## Attaching package: 'fBasics'
## 
## The following objects are masked from 'package:PerformanceAnalytics':
## 
##     kurtosis, skewness
## 
## The following object is masked from 'package:TTR':
## 
##     volatility
#1 Computing optimal weight
Sigma <- cov(firm_data[, 2:4])
ones <- rep(1, 3)
one.vec <- matrix(ones, ncol =1)
a <- inv(Sigma)%*%one.vec
b <- t(one.vec)%*%a
mvp.w <- a / as.numeric(b)
head(mvp.w)
##                [,1]
## Nordstrom 0.3635998
## Starbucks 0.1936537
## Microsoft 0.4427465
#2 Given constraint: Portfolio return is specified as 0.045 annual rate.  
# The optimal weights for the minimum variance portfolio. 
mu <- 0.045/12
return <- firm_data[,2:4]
Ax <- rbind(2*cov(return), colMeans(return), rep(1, ncol(return)))
Ax <- cbind(Ax, rbind(t(tail(Ax, 2)), matrix(0, 2, 2)))
b0 <- c(rep(0, ncol(return)), mu, 1)
out <- solve(Ax, b0)
wgt <- out[1:3]
wgt
##   Nordstrom   Starbucks   Microsoft 
##  0.90766373  0.11201021 -0.01967394
sum(wgt)
## [1] 1
# Verfity the return
ret.out<-sum(wgt*colMeans(return))
ret.out.annual<-ret.out*12
ret.out.annual
## [1] 0.045
# Compute the standard deviation or risk of the portfolio
std.out<-sqrt(t(wgt)%*%cov(return)%*%wgt)
std.out.annual<-std.out*sqrt(12)
std.out.annual
##           [,1]
## [1,] 0.3444032

R Markdown

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

Including Plots

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.