1
votes

I downloaded several timeseries via Yahoo-Finance, Reuters and other sources.

They are all listed as seperate "xts"-objects which contains the respective closing price. These vectors are available for daily and monthly intervals.

I would like to create one chart which shows the price developement of my stocks. This chart should the relative price developement in relation to the first day:

price of 2005-01-04/price of 2005-01-03 
price of 2005-01-05/price of 2005-01-03

and so on.

For this I tried to create a for-loop:

indexfun <- function(x)
  {
  y <- as.matrix(x)
  z <- rep(NULL, nrow(x))
  for(i in nrow(y)){
  z[i] <- y[i,1]/y[1,1]
    print(z)
  }
}

Unfortunately, it returns soley NA-values except for the last one. I tried to save the vector as matrix to ensure I can acces the column containing the closing prices and leaving the dates untouched.

My xts-vector looks like

           BA.close
2005-01-03    50.97
2005-01-04    49.98
2005-01-05    50.81
2005-01-06    50.48
2005-01-07    50.31
2005-01-10    50.98

Can you help me?

Thank you very much.

1
Try for(i in 1:nrow(y)).Lyngbakr
Unfortunately it delivers the same result (NA values).StableSong
Can you share your data with the dput() function (or just a sample)?Mike
@Lyngbakr this doesn't do anythingAndre Elrico

1 Answers

0
votes

Here a solution that works for xts:

library(xts)

x <- xts(c(50.97, 49.98, 50.81, 50.48, 50.31, 50.98),as.Date("2005-01-03")+0:5)

x / drop(coredata(x['2005-01-03']))


                [,1]
2005-01-03 1.0000000
2005-01-04 0.9805768
2005-01-05 0.9968609
2005-01-06 0.9903865
2005-01-07 0.9870512
2005-01-08 1.0001962

If you have more columns where each is a different stock, and you want to divide by the same date:

first convert to matrix your data and remove the date column (you'll put it back later), keep in mind that we use the first row to divide.

mat <- as.matrix(d[,-1]) # remove the dates

sweep(mat,2,mat[1, ],`/`) # divide by mat[1, ]. i.e. first row
#            aaa      bbb
# [1,] 1.0000000 1.000000
# [2,] 0.9805768 2.090909
# [3,] 0.9968609 4.090909
# [4,] 0.9903865 5.090909
# [5,] 0.9870512 7.818182
# [6,] 1.0001962 3.090909
# now we can trasform back to data.frame and cbind() with the dates.

Data used:

tt <- "date     aaa     bbb
2005-01-03    50.97     11
2005-01-04    49.98     23
2005-01-05    50.81     45
2005-01-06    50.48     56
2005-01-07    50.31     86
2005-01-10    50.98     34"

d <- read.table(text=tt, header=T)