1

Currently I have the following xts table.

       AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2013-09-09    505.00    507.92   503.48     506.17    12116200        506.17
2013-09-10    506.20    507.45   489.50     494.64    26490200        494.64
2013-09-11    467.01    473.69   464.81     467.71    32031600        467.71
2013-09-12    468.50    475.40   466.01     472.69    14409400        472.69
2013-09-13    469.34    471.83   464.70     464.90    10649000        464.90
...

I can use the quantmod package to calculate percent change Delt(AA[,"AAPL.Adjusted"],k=1) however I'm new to R and wondering how to do this without the package and not using some sort of for loop. I guess it would be something like lag(k/k-1)-1? Thank you.

Henrik
  • 65,555
  • 14
  • 143
  • 159
Ahdee
  • 4,679
  • 4
  • 34
  • 58

3 Answers3

1

I figured it out from the xts package pdf online,

AA$AAPL.change2<-AA[,"AAPL.Adjusted"]/lag(AA[,"AAPL.Adjusted"], k=1, na.pad = TRUE)-1

What confused me was how to differentiated current vs. lag but it turns out that just calling the object is enough, in other words if the object is x then if you want to divide current with lag of 1 then its just x/lag(x, k=1) - this is probably obvious but for a newbie its really cool ;)

Ahdee
  • 4,679
  • 4
  • 34
  • 58
1

Another option is using ROC

s <- get(getSymbols('AMZN')
s$pct <- ROC(Ad(s),1)
head(s)
           AMZN.Open AMZN.High AMZN.Low AMZN.Close AMZN.Volume AMZN.Adjusted          pct
2007-01-03     38.68     39.06    38.05      38.70    12405100         38.70           NA
2007-01-04     38.59     39.14    38.26      38.90     6318400         38.90  0.005154651
2007-01-05     38.72     38.79    37.60      38.37     6619700         38.37 -0.013718346
2007-01-08     38.22     38.31    37.17      37.50     6783000         37.50 -0.022934971
2007-01-09     37.60     38.06    37.34      37.78     5703000         37.78  0.007438929
2007-01-10     37.49     37.70    37.07      37.15     6527500         37.15 -0.016816091
haki
  • 9,389
  • 15
  • 62
  • 110
0

The xts package has a diff.xts function nowadays.

You are able to specify the lag period as well as the differencing order. For stock returns I'd advise to use lag=1, differences=1 and log=TRUE.

PrinzvonK
  • 93
  • 6