[R-SIG-Finance] use rows and cols of a matrix as dates

Joshua Ulrich josh.m.ulrich at gmail.com
Thu Mar 14 12:43:09 CET 2013


On Thu, Mar 14, 2013 at 3:21 AM, Sven D <sduve at hotmail.com> 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
>> gy
<snip... the output is incorrect anyway>
>
> 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)

> Can anyone help?
>
>
> Best
>
> Sven
>

Best,
--
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  www.fosstrading.com

R/Finance 2013: Applied Finance with R  | www.RinFinance.com



More information about the R-SIG-Finance mailing list