0

I'm supposed to use the downloaded daily prices from March 1, 2015 to March 1, 2017 for EBAY, GOOG, TEVA to compute the sample covariance matrix for the arithmetic returns.

This is what I have:

library(zoo)
library(tseries)
library(fBasics)

for(ticker in c("ebay", "goog", "teva", "ge")){
Prices = get.hist.quote(instrument = ticker, start = "2015-03-01",
                        end = "2017-03-01", quote = "Close", 
                        provider = "yahoo",origin = "1970-01-01", 
                        compression = "d", retclass = "zoo")}


return = diff(Prices)/lag(Prices, k=-1)

covariance = cov(return)

However, when I print covariance, I get a 1 by 1 matrix...I know that my loop is overwriting the tickers in Prices so it is only using prices from the last ticker for the rest of the code. I've tried to use the list function, to correct this, but that didn't change my end result for the covariance. I believe I"m suppose to end up with a 4x4 matrix, but I don't really understand how to get that.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
user6259845
  • 185
  • 8

1 Answers1

0

I suggest to read more about lists and how they work before trying to use lists. Also, I recommend you to not use = for assigning variables, see more on that on this SO thread What are the differences between "=" and "<-" in R?.

An alternative for the lists could be to save separate data.frame for each ticker and then cbind the data.frames.

But based on your code the list version is:

library(zoo)
library(tseries)
Prices <- c()
k <- 1
for(ticker in c("ebay", "goog", "teva", "ge")){

  Prices[[k]] <- get.hist.quote(instrument = ticker, start = "2015-03-01",
                          end = "2017-03-01", quote = "Close", 
                          provider = "yahoo",origin = "1970-01-01", 
                          compression = "d", retclass = "zoo")
  k <- k+1
  }


return_list <- lapply(Prices, function(x) diff(x)/lag(x, k=c(-1)))
return_matrix <- do.call("cbind", return_list)
colnames(return_matrix) <- c("ebay", "goog", "teva", "ge")

covariance <- cov(return_matrix)

             ebay         goog         teva           ge
ebay 3.180376e-04 8.985594e-05 5.332997e-05 7.296451e-05
goog 8.985594e-05 2.385761e-04 6.331062e-05 7.274448e-05
teva 5.332997e-05 6.331062e-05 3.919655e-04 4.754861e-05
ge   7.296451e-05 7.274448e-05 4.754861e-05 1.538201e-04
nadizan
  • 1,323
  • 10
  • 23