6

I have an xts object called Daily_Quotes that contains stock quotes. I'm using endpoints to get monthly stock quotes that I retrieved using getSymbols (from the quantmod package). I noticed that the endpoints function creates an index of the row that contains the last trading day for the particular month and assigns it to the new object for the specified date range. Is there anyway to get first trading day of the month instead?

# My code    
Monthly_Quotes <- Daily_Quotes[endpoints(Daily_Quotes,'months')]

What I tried doing was:

# This gave me the next day or 1st day of the next month
# or next row for the object.
endpoints(Daily_Quotes,'months') + 1

# So I applied this and it gave me 
# Error in `[.xts`(Daily_Quotes, endpoints(Daily_Quotes, "months") + 1) :
# subscript out of bounds
Monthly_Quotes <- Daily_Quotes[endpoints(Daily_Quotes,'months') + 1]

How do I attempt to solve this ?

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
NewComer
  • 205
  • 6
  • 12
  • http://stackoverflow.com/a/21865333/967840 – GSee Nov 17 '14 at 21:16
  • 1
    it's usually better not to edit the Answer into your Question. We try to keep the Quesion and Answers separate. If someone reads your Question now, it is less clear what you are asking since it says "How do I attempt to solve this?" followed by a solution. – GSee Nov 17 '14 at 23:52
  • @GSee: I rolled those edits back, for that very reason. – Joshua Ulrich Nov 18 '14 at 14:23
  • Thanks Joshua as I was going to Edit it myself. @Gsee will do that going forward. – NewComer Nov 18 '14 at 15:45

1 Answers1

6

You can create a startpoints function like this

startpoints <- function (x, on = "months", k = 1) {
  head(endpoints(x, on, k) + 1, -1)
}
GSee
  • 48,880
  • 13
  • 125
  • 145
  • I need to understand the -1 argument. I understand that "head(endpoints(x, on, k) + 1)" gives me x amount of each index value + 1 on months based on the k element. So far so good? When executing "head(endpoints(Daily_Quotes,'months', 1) + 1, -1)" It gives me each index value + 1 on months based on k and with the addition of -1 returns all the index values. So I see the difference but do not know how this is working? I hope my question makes sense. Am I over analyzing or asking a legit question? – NewComer Nov 18 '14 at 16:09
  • @NewComer `head(x, -1)` is equivalent to `x[-length(x)]` (which is how this same function is implemented if you look at `xts:::startof`). `?head` says that if `n` is negative, "all but the `n` last/first number of elements of `x`." Does that help? – GSee Nov 18 '14 at 17:54
  • That definitely helps. I'm going to look into xts:::startof. Thanks for the explanation. – NewComer Nov 18 '14 at 17:59