On Thu, Mar 14, 2013 at 3:21 AM, Sven D <sduve@> wrote:
Dear All,
I am trying to evaluate a gas storage contract and I am trying to use R do
the work for me. What I am trying to do is to generate a matrix like:
gy <- matrix(0, nrow=13, ncol=13)
gy <- xts(gy, order.by = timeBasedSeq('201304/201404'))
# these numbers are an imaginariy gas forward curve
forwardcurve <-
c(26.5,26.45,26.4,26.25,26.25,26.25,26.21,27.54,27.91,28.14,28.17,27.91)
# populate first row and first col with the forward curve
gy[1,c(2:13)] <- forwardcurve
gy[c(2:13),1] <- forwardcurve
# calculate the monthly spreads
for(i in 2:13) gy[i,c(i:13)] <- (gy[1, c(i:13)] - gy[i,1])
This throws an error (that you didn't mention) because arithmetic
operations on zoo/xts objects merge by index before performing the
operation. In other words, you can't perform arithmetic operations on
different rows without using coredata() to drop the index attribute.
You need something like this instead:
for(i in 2:13) {
gy[i, i:13] <- gy[1, i:13] - drop(coredata(gy[i,1]))
}
# the matrix should look like this
<snip... the output is incorrect anyway>
apologies, yes, I was performing the inital loop before I turned the matrix
into an xts. I kept on trying to find a solution while writing the question.
I now need to xts the columns as well, is that possibel?
No. xts is a specific class of object, it's not something you do to any
object.
I tried
gy <- xts(colnames(gy), order.by = timeBasedSeq('201304/201404'))
but this doesnt give me the required result at all.
What is the required result? You only give a vague description; an
example would help others help you. You could set the column names of
'gy' to the index values, but I have no idea if that's what you
actually want...
colnames(gy) <- index(gy)
thank you, as things brings me closer to what I would like to do:
as.Date(as.yearmon(colnames(gy)[1], format="%B %Y"))
will return a date, and from that date value I will be able to calculate the
time to maturity for each single spreadoption. Like:
as.numeric(as.Date(as.yearmon(colnames(gy)[2], format="%B %Y")) -
as.Date(as.yearmon(colnames(gy)[1], format="%B %Y"))) / 365