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:
# Load libraries
library(tidyquant)
## Loading required package: lubridate
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(lubridate)
library(timetk)
library(purrr)
library(quantmod)
library(SIT)
library(tibble)
library(reshape2)
library(xts)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:xts':
##
## first, last
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(readr)
library(quadprog)
# 1. Import data
symbols <- c("SPY", "QQQ", "EEM", "IWM", "EFA", "TLT", "IYR", "GLD")
prices <-
getSymbols(symbols, src = 'yahoo', from = "2010-01-01",
auto.assign = TRUE, warnings = FALSE) %>%
map(~Ad(get(.))) %>%
reduce(merge) %>%
`colnames<-`(symbols)
head(prices)
## SPY QQQ EEM IWM EFA TLT IYR
## 2010-01-04 88.11788 41.00546 32.42903 53.08979 37.99448 63.06113 28.77183
## 2010-01-05 88.35117 41.00546 32.66440 52.90724 38.02797 63.46840 28.84092
## 2010-01-06 88.41336 40.75814 32.73273 52.85744 38.18871 62.61879 28.82836
## 2010-01-07 88.78657 40.78464 32.54292 53.24744 38.04137 62.72412 29.08586
## 2010-01-08 89.08207 41.12030 32.80108 53.53787 38.34275 62.69600 28.89116
## 2010-01-11 89.20645 40.95247 32.73273 53.32212 38.65753 62.35194 29.02934
## GLD
## 2010-01-04 109.80
## 2010-01-05 109.70
## 2010-01-06 111.51
## 2010-01-07 110.82
## 2010-01-08 111.37
## 2010-01-11 112.85
## 2. Calculate weekly and monthly returns using log returns
prices_weekly <- to.weekly(prices, indexAt = "last", OHLC = FALSE)
prices_monthly <- to.monthly(prices, indexAt = "last", OHLC = FALSE)
asset_returns_wk <- na.omit(Return.calculate(prices_weekly))
asset_returns_mon <- na.omit(Return.calculate(prices_monthly))
head(asset_returns_wk)
## SPY QQQ EEM IWM EFA
## 2010-01-15 -0.008117820 -0.01503742 -0.02893521 -0.01301901 -0.003493571
## 2010-01-22 -0.038982401 -0.03685950 -0.05578053 -0.03062176 -0.055740467
## 2010-01-29 -0.016665184 -0.03102329 -0.03357774 -0.02624365 -0.025802774
## 2010-02-05 -0.006798071 0.00444052 -0.02821322 -0.01397439 -0.019054993
## 2010-02-12 0.012938790 0.01814795 0.03333357 0.02952617 0.005244799
## 2010-02-19 0.028692708 0.02445119 0.02445359 0.03343132 0.022995166
## TLT IYR GLD
## 2010-01-15 2.004663e-02 -0.006304098 -0.004579349
## 2010-01-22 1.010119e-02 -0.041785631 -0.033285246
## 2010-01-29 3.370339e-03 -0.008447150 -0.011290465
## 2010-02-05 -5.461627e-05 0.003223616 -0.012080019
## 2010-02-12 -1.946064e-02 -0.007574412 0.022544905
## 2010-02-19 -8.205368e-03 0.050185097 0.022701796
head(asset_returns_mon)
## SPY QQQ EEM IWM EFA
## 2010-02-26 0.03119469 0.04603870 0.017763793 0.04475146 0.002667829
## 2010-03-31 0.06087941 0.07710911 0.081108904 0.08230699 0.063853861
## 2010-04-30 0.01546992 0.02242523 -0.001661987 0.05678429 -0.028045707
## 2010-05-28 -0.07945432 -0.07392344 -0.093935384 -0.07536613 -0.111928076
## 2010-06-30 -0.05174107 -0.05975711 -0.013986693 -0.07743408 -0.020619462
## 2010-07-30 0.06830052 0.07258250 0.109324719 0.06730904 0.116104406
## TLT IYR GLD
## 2010-02-26 -0.003424817 0.05457058 0.032748219
## 2010-03-31 -0.020573278 0.09748429 -0.004386396
## 2010-04-30 0.033218241 0.06388105 0.058834363
## 2010-05-28 0.051083275 -0.05683505 0.030513147
## 2010-06-30 0.057977881 -0.04670106 0.023553189
## 2010-07-30 -0.009463134 0.09404791 -0.050871157
# 3. Convert monthly returns into tibble format
monthly_return <- tibble(Date = index(asset_returns_mon), asset_returns_mon)
# 4. Download Fama French 3 factors data and change to digit numbers
download.file("http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip",
"FamaFrench.zip")
unzip("FamaFrench.zip", exdir = "FamaFrench")
ff_data <- read.csv("FamaFrench/F-F_Research_Data_Factors.CSV", skip = 3, header = TRUE)
colnames(ff_data)[colnames(ff_data) == "X"] <- "Date"
colnames(ff_data)[grepl("^X$", colnames(ff_data))] <- "Date"
ff_data$Date <- as.Date(as.yearmon(ff_data$Date, "%Y%m"))
# 5. Merge monthly return data and Fama French 3 factors data
merged_data <- left_join(monthly_return, ff_data, by = "Date")
head(merged_data)
## # A tibble: 6 × 6
## Date asset_re…¹ [,"QQ…² [,"EE…³ [,"IW…⁴ [,"EF…⁵ Mkt.RF SMB HML RF
## <date> <xts[,1]> <xts[,> <xts[,> <xts[,> <xts[,> <chr> <chr> <chr> <chr>
## 1 2010-02-26 0.031194… 0.046… 0.017… 0.044… 0.002… <NA> <NA> <NA> <NA>
## 2 2010-03-31 0.060879… 0.077… 0.081… 0.082… 0.063… <NA> <NA> <NA> <NA>
## 3 2010-04-30 0.015469… 0.022… -0.001… 0.056… -0.028… <NA> <NA> <NA> <NA>
## 4 2010-05-28 -0.079454… -0.073… -0.093… -0.075… -0.111… <NA> <NA> <NA> <NA>
## 5 2010-06-30 -0.051741… -0.059… -0.013… -0.077… -0.020… <NA> <NA> <NA> <NA>
## 6 2010-07-30 0.068300… 0.072… 0.109… 0.067… 0.116… <NA> <NA> <NA> <NA>
## # … with 1 more variable: asset_returns_mon[6:8] <xts[,8]>, and abbreviated
## # variable names ¹asset_returns_mon[,"SPY"], ²[,"QQQ"], ³[,"EEM"], ⁴[,"IWM"],
## # ⁵[,"EFA"]
# 6. Compute covariance matrix for the 8-asset portfolio using CAPM model
# Filter the asset returns for the desired period
start_date <- as.Date("2010-02-26")
end_date <- as.Date("2015-01-30")
filtered_returns <- asset_returns_mon[index(asset_returns_mon) >= start_date & index(asset_returns_mon) <= end_date]
# Calculate the covariance matrix
cov_matrix <- cov(filtered_returns)
# Print the covariance matrix
print(cov_matrix)
## SPY QQQ EEM IWM EFA
## SPY 0.0013963097 0.0014668482 0.0017259312 0.0017871576 0.0015995543
## QQQ 0.0014668482 0.0018151194 0.0018027487 0.0018552209 0.0016782266
## EEM 0.0017259312 0.0018027487 0.0033502312 0.0023216524 0.0024683840
## IWM 0.0017871576 0.0018552209 0.0023216524 0.0026990074 0.0019706398
## EFA 0.0015995543 0.0016782266 0.0024683840 0.0019706398 0.0024130410
## TLT -0.0009945684 -0.0009915754 -0.0012008258 -0.0013412104 -0.0011241266
## IYR 0.0011994651 0.0012334301 0.0017915527 0.0016107198 0.0015501663
## GLD 0.0001987656 0.0003965327 0.0008793462 0.0005371969 0.0004206013
## TLT IYR GLD
## SPY -0.0009945684 0.0011994651 0.0001987656
## QQQ -0.0009915754 0.0012334301 0.0003965327
## EEM -0.0012008258 0.0017915527 0.0008793462
## IWM -0.0013412104 0.0016107198 0.0005371969
## EFA -0.0011241266 0.0015501663 0.0004206013
## TLT 0.0016210153 -0.0003852439 0.0001967874
## IYR -0.0003852439 0.0020244332 0.0005165084
## GLD 0.0001967874 0.0005165084 0.0028996541
# 7. Compute covariance matrix for the 8-asset portfolio using Fama-French three-factor model
# Subset the factor data to match the length of filtered_returns
ff_filtered <- ff_data[index(filtered_returns), ]
# Extract the market excess return, SMB, and HML factors
mkt_excess <- ff_filtered$Mkt.RF
smb <- ff_filtered$SMB
hml <- ff_filtered$HML
# Combine the asset returns and factor data
data <- cbind(filtered_returns, mkt_excess, smb, hml)
# Compute the covariance matrix using the Fama-French 3-factor model
cov_matrix_ff <- cov(data)
# Print the covariance matrix
print(cov_matrix_ff)
## SPY QQQ EEM IWM
## SPY 0.0013963097 0.0014668482 0.0017259312 0.0017871576
## QQQ 0.0014668482 0.0018151194 0.0018027487 0.0018552209
## EEM 0.0017259312 0.0018027487 0.0033502312 0.0023216524
## IWM 0.0017871576 0.0018552209 0.0023216524 0.0026990074
## EFA 0.0015995543 0.0016782266 0.0024683840 0.0019706398
## TLT -0.0009945684 -0.0009915754 -0.0012008258 -0.0013412104
## IYR 0.0011994651 0.0012334301 0.0017915527 0.0016107198
## GLD 0.0001987656 0.0003965327 0.0008793462 0.0005371969
## mkt_excess NA NA NA NA
## smb NA NA NA NA
## hml NA NA NA NA
## EFA TLT IYR GLD mkt_excess
## SPY 0.0015995543 -0.0009945684 0.0011994651 0.0001987656 NA
## QQQ 0.0016782266 -0.0009915754 0.0012334301 0.0003965327 NA
## EEM 0.0024683840 -0.0012008258 0.0017915527 0.0008793462 NA
## IWM 0.0019706398 -0.0013412104 0.0016107198 0.0005371969 NA
## EFA 0.0024130410 -0.0011241266 0.0015501663 0.0004206013 NA
## TLT -0.0011241266 0.0016210153 -0.0003852439 0.0001967874 NA
## IYR 0.0015501663 -0.0003852439 0.0020244332 0.0005165084 NA
## GLD 0.0004206013 0.0001967874 0.0005165084 0.0028996541 NA
## mkt_excess NA NA NA NA NA
## smb NA NA NA NA NA
## hml NA NA NA NA NA
## smb hml
## SPY NA NA
## QQQ NA NA
## EEM NA NA
## IWM NA NA
## EFA NA NA
## TLT NA NA
## IYR NA NA
## GLD NA NA
## mkt_excess NA NA
## smb NA NA
## hml NA NA
# 8. Compute global minimum variance (GMV) portfolio weights based on CAPM and Fama-French models
# Compute the inverse of the covariance matrix for CAPM
inv_cov_matrix <- solve(cov_matrix)
# Compute the inverse of the covariance matrix for Fama-French 3-factor model
inv_cov_matrix_ff <- solve(cov_matrix_ff)
# Set the number of assets
n_assets <- ncol(filtered_returns)
# Set the target return for portfolio optimization
target_return <- 0 # Change this value if you have a specific target return
# Create the matrices for the quadratic programming problem
Dmat <- 2 * inv_cov_matrix
dvec <- rep(0, n_assets)
Amat <- matrix(1, nrow = 1, ncol = n_assets)
bvec <- 1
# Solve the quadratic programming problem for CAPM
weights_capm <- solve.QP(Dmat = Dmat, dvec = dvec, Amat = t(Amat), bvec = bvec)$solution
# Solve the quadratic programming problem for Fama-French 3-factor model
Dmat_ff <- 2 * inv_cov_matrix_ff
dvec_ff <- rep(0, n_assets)
Amat_ff <- cbind(rep(1, n_assets), filtered_returns$Mkt_RF, filtered_returns$SMB, filtered_returns$HML) # Include the factor returns
bvec_ff <- c(1, 0, 0, 0) # Set the factor exposure constraints
weights_ff <- solve.QP(Dmat = Dmat_ff, dvec = dvec_ff, Amat = t(Amat_ff), bvec = bvec_ff)$solution
## Error in solve.QP(Dmat = Dmat_ff, dvec = dvec_ff, Amat = t(Amat_ff), bvec = bvec_ff): Dmat and dvec are incompatible!
# Print the portfolio weights
print(weights_capm)
## [1] 0.12979627 0.14338219 0.20352089 0.17720935 0.17002366 -0.06536308
## [7] 0.14778874 0.09364197
print(weights_ff)
## Error in print(weights_ff): object 'weights_ff' not found
# 9. Backtest the performance of GMV portfolios based on CAPM and Fama-French models
# Set the number of assets and historical returns window
n_assets <- ncol(filtered_returns)
window_size <- 6
# Initialize variables to store portfolio returns
returns_capm <- vector("numeric")
returns_ff <- vector("numeric")
# Loop over the time period to estimate and construct portfolios
for (i in (window_size + 1):nrow(filtered_returns)) {
# Select the historical returns for estimation
returns_window <- filtered_returns[(i - window_size):(i - 1), ]
# Compute the covariance matrix and factor exposures
cov_matrix <- cov(returns_window)
cov_matrix_ff <- cov(returns_window[, c("Mkt_RF", "SMB", "HML")])
# Compute the inverse of the covariance matrix
inv_cov_matrix <- solve(cov_matrix)
inv_cov_matrix_ff <- solve(cov_matrix_ff)
# Compute the weights for CAPM
weights_capm <- solve.QP(Dmat = 2 * inv_cov_matrix, dvec = rep(0, n_assets),
Amat = matrix(1, nrow = 1, ncol = n_assets),
bvec = 1)$solution
# Compute the weights for Fama-French 3-factor model
weights_ff <- solve.QP(Dmat = 2 * inv_cov_matrix_ff, dvec = rep(0, n_assets),
Amat = cbind(rep(1, n_assets), returns_window$Mkt_RF, returns_window$SMB, returns_window$HML),
bvec = c(1, 0, 0, 0))$solution
# Calculate the portfolio returns for the next month
returns_next_month <- filtered_returns[i, ]
# Calculate the returns of the GMV portfolios based on CAPM and Fama-French models
returns_capm <- c(returns_capm, sum(weights_capm * returns_next_month))
returns_ff <- c(returns_ff, sum(weights_ff * returns_next_month))
}
## Error in `[.xts`(returns_window, , c("Mkt_RF", "SMB", "HML")): subscript out of bounds
# Convert the returns to a time series object
returns_capm_ts <- xts(returns_capm, order.by = index(filtered_returns)[-c(1:window_size)])
returns_ff_ts <- xts(returns_ff, order.by = index(filtered_returns)[-c(1:window_size)])
# Perform performance analysis
perf_capm <- Return.cumulative(returns_capm_ts)
perf_ff <- Return.cumulative(returns_ff_ts)
# Print the performance results
print(perf_capm)
##
## Cumulative Return
print(perf_ff)
##
## Cumulative Return