Skip to content
Prev 14800 / 15274 Next

how to grow XTS series in R dynamically ? And Quickly!

let's start with what exactly do you want to do? Do you want to collect market data and save it to disk? Or maybe you want to have a real-time strategy? These are two different problems and require distinct solutions.

1) market data storage - why do you want to use R here? Isn't it better to dump the memory using mmap syscall and then import it into the database or R?

2) real-time market strategy in R - in this case your lookback is limited. So if you add new data point, you can also discard/drop the oldest. In this way, your memory usage will remain at the same low level. If this solution suits you, then you can write a fast function in C here that would operate on the xts object.

There is no such thing as matrix in R - this is a multidimensional vector. Let's say we have classic OHLC data for xts object:

O H L C
O H L C
O H L C
O H L C
O H L C


In the memory of the data looks like one long vector.

x: OOOOOHHHHHLLLLLCCCCC

You can be clever here and use memcpy():

memcpy(&xp + 1, &xp, (nrows(x) - 1)) * sizeof(double));  // or int - use: switch((TYPEOF(x))

memcpy(&index_p + 1, &index_p, (nrows(x) - 1)) * sizeof(double)); // or int for Date() type

This will move the memory so that the oldest value will be overwritten:

    1 2 3 4 5   1 2 3 4 5   1 2 3 4 5   1 2 3 4 5
x: OOOOH   HHHHL      LLLLC      CCCC N

Then you can add a new index and value.

You will have preallocated memory at all times and you will use memory copy as little as possible. And the most important: you'll be operating on the xts object all time, so your code in R will be very fast :)

It is advanced solutions - you need to understand not only how R's internals works, but also have a good C skills. If you want to use R for real-time trading, it's worth learn these things.

Daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20190906/c8bcda47/attachment.html>

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: Message signed with OpenPGP
URL: <https://stat.ethz.ch/pipermail/r-sig-finance/attachments/20190906/c8bcda47/attachment.sig>