1
votes

This is my first time with coding - not in finances, either. Just trying to learn R.

I tried to calculate differences in closing price for historical data on Google. The problem is that to apply a function (and I bet there are many functions for this already prepackaged), I could only make it work by converting the Adjusted price column of the xts file into a vector.

I got what I wanted, but now I'm stuck with a vector that I can't merge back into the xts file to look up specific dates:

getSymbols("GOOG")
head(GOOG)
z = as.vector(GOOG$GOOG.Adjusted)

D2D = function (x) {
                days = length(x)
                delta = numeric(days)
                for(i in 2:days){
                  delta[i] <- (100*((x[i] - x[i - 1])/(x[i - 1])))
                }
                delta
}
DELTA = D2D(z)
summary(DELTA)
GOOG_DELTA = append(0,DELTA)
merge(GOOG,GOOG_DELTA)

Any tips would be appreciated.

2

2 Answers

3
votes

No need to cerate a custom function for this , xts and quantmod have already build-in vectorized function to do this. I thing you are looking for this :

merge(GOOG,Ad((GOOG-lag(GOOG,1))/(lag(GOOG,1))))
0
votes

In the meantime, I think the very specific way of preventing the problem I was having is to convert the xts file as a whole to a data.frame (rather than separating a column vector); doing the operations on the data.frame, and at the tail end merging the results to the original xts.

Here's a possible way that works (NOTE: I gave the mean to the first row, instead of "NA"):

getSymbols("GOOG")
str(GOOG) #We start with an xts
z = as.data.frame(GOOG$GOOG.Adjusted)
head(z)
D2D = function (x) {
                days = nrow(x)
                delta = numeric(days)
                for(i in 2:days){
                  delta[i] <- (100*((x[i,1] - x[i - 1,1])/(x[i - 1,1])))
                }
                delta
}
DELTA = D2D(z)
head(DELTA)
DELTA[1]<-mean(DELTA)
head(DELTA)
summary(DELTA)
GOOG_D2D = merge(GOOG,DELTA)
str(GOOG_D2D) #And we end with an xts file!