Convert a matrix to an xts object - r

I am new to R and need to use the function getnfac from the PANICr package. And it seems that the function only takes an xts object as its first argument. However, after I went through some reading I still don't understand what an xts object is. Could anyone please tell me how I can convert a matrix into an xts object?
Below I use return matrix as the first argument. Therefore I just need to convert return to an xts object.
getnfac(return,143,"BIC3")
Error in getnfac(return, 143, "BIC3") :
x must be an xts object so lags and differences are taken properly

xts is an extensible time series object, essentially a regular ts object (or more correctly a zoo object) with some bits added.
The 'extensible' part of the name refers to how you can add attributes of your own choice.
While a matrix can be converted into a multivariate time series quite easily
m <- matrix(1:16, 4)
m.ts <- ts(m)
index(m.ts)
An xts requires its index (a vector describing at what time each sample was taken) to be in a date or time format
library(xts)
m <- matrix(1:16, 4)
d <- as.Date(1:nrow(m))
m.xts <- xts(m, order.by=d)
index(m.xts)
If your data is sampled at evenly spaced intervals a dummy index like the one above is probably ok. If not, you'll need to supply a vector corresponding to the sampling times.

In my opinion, the first argument to the getnfac() function should be matrix containing the data.
In addition to the above answers,
You can convert matrix format using coredata() about xts object.

Related

How do I access coredata from each object in a matrix of xts zoo objects

I used the getFX function from the Quantmod package in R to generate a vector of rates from Oanda, each in xts zoo format.
currency_pairs <- c("GBP/USD", "USD/SGD")
rates <- getFX(currency_pairs, from="2019/01/01", to="2019/01/01"
This returns a vector of xts zoo objects in the form:
(GBPUSD, USDSGD,...)
However I would like to have just the rates, since I only require the rates for one date and therefore know the timestamp.
I have tried looping over the vector like so:
for (i in 1:length(rates){
rates[i] <- coredata(rates[i])
}
but this just returns the currency pair name.
What you could do in this case, if you only retrieve data for one date, is use to sapply like this:
library(quantmod)
currency_pairs <- c("GBP/USD", "USD/SGD")
# for 1 date this will return a named vector otherwise use lapply
rates <- sapply(currency_pairs, getFX, from="2019/01/01", to="2019/01/01", auto.assign = FALSE)
rates
GBP/USD USD/SGD
1.275455 1.362920
Normally I would suggest using lapply to retrieve all the currencies in a big list and then access the list with lapply / mapply / Map / purrr::map etc.

Fill an object with the results of every loop iteration in R

first time asker here. I have recently strated working with R and I hope I could get some help with an issue. The problem is probably easy to solve but I haven't been able to find an answer by myself and my research hasn't been succesful either.
Basically I need to create a single object based on the input of a loop. I have 7 simulated asset returns, these objects contain the results from a simulation I ran. I want to match the columns from every object and form a combined one (i.e. every column 1 forms an object), which will be used for some calculations.
Finally, the result from each iteration should be stored on a single object that has to be available outside the loop for further analysis.
I have created the following loop, the problem is that only the result from the last iteration is being written in the final object.
# Initial xts object definition
iteration_returns_combined <- iteration_returns_draft_1
for (i in 2:10){
# Compose object by extracting the i element of every simulation serie
matrix_daily_return_iteration <- cbind(xts_simulated_return_asset_1[,i],
xts_simulated_return_asset_2[,i],
xts_simulated_return_asset_3[,i],
xts_simulated_return_asset_4[,i],
xts_simulated_return_asset_5[,i],
xts_simulated_return_asset_6[,i],
xts_simulated_return_asset_7[,i])
# Transform the matrix to an xts object
daily_return_iteration_xts <- as.xts(matrix_daily_return_iteration,
order.by = index(optimization_returns))
# Calculate the daily portfolio returns using the iteration return object
iteration_returns <- Return.portfolio(daily_return_iteration_xts,
extractWeights(portfolio_optimization))
# Create a combined object for each iteration of portfolio return
# This is the object that is needed in the end
iteration_returns_combined <<- cbind(iteration_returns_draft_combined,
iteration_returns_draft)
}
iteration_returns_combined_after_loop_view
Could somebody please help me to fix this issue, I would be extremely grateful for any information anyone can provide.
Thanks,
R-Rookie
By looking at the code, I surmise that the error is in the last line of your for loop.
iteration_returns_draft_combined
was never defined, so it is assumed to be NULL. Essentially, you only bind columns of the results from each iteration to a NULL object. Hence the output of your last loop is also bound by column to a NULL object, which is what you observe. Try the following:
iteration_returns_combined <- cbind(iteration_returns_combined,
iteration_returns)
This should work, hopefully!
Consider sapply and avoid expanding an object within a loop:
iteration_returns_combined <- sapply(2:10, function(i) {
# Compose object by extracting the i element of every simulation serie
matrix_daily_return_iteration <- cbind(xts_simulated_return_asset_1[,i],
xts_simulated_return_asset_2[,i],
xts_simulated_return_asset_3[,i],
xts_simulated_return_asset_4[,i],
xts_simulated_return_asset_5[,i],
xts_simulated_return_asset_6[,i],
xts_simulated_return_asset_7[,i])
# Transform the matrix to an xts object
daily_return_iteration_xts <- as.xts(matrix_daily_return_iteration,
order.by = index(optimization_returns))
# Calculate the daily portfolio returns using the iteration return object
iteration_returns <- Return.portfolio(daily_return_iteration_xts,
extractWeights(portfolio_optimization))
})
And if needed to column bind first vector/matrix, do so afterwards:
# CBIND INITIAL RUN
iteration_returns_combined <- cbind(iteration_returns_draft_1, iteration_returns_combined)

how to convert numeric type to "seconds" in R

I want to create a Time Series data frame by doing this:
x <- xts(data$length,data$Time.Elapsed)
Then, I got a warning message:
Error in xts(data$length, data$Time.Elapsed) :
order.by requires an appropriate time-based object
So, I was thinking the problem is my "Time.Elapsed" is numeric data. Then I want to convert the data type of "Time.Elapsed", how can I achieve that?
>data$Time Elapsed
Time Elapsed
0
1
2
3
4
5
I want to create a time series data frame, so I need to have a time-based object in R. Here, "Time Elapsed" is a numeric variable (those numbers represent seconds); how can I convert it to time type "seconds"? I searched the Data-time conversion function, like: as.POSIX* {base} But I don't think this function suits my case. Anyone can help me about this? Thank you very much!
I believe you're not going low-level enough on this. xts provides some convenience functions to help determine if you can convert something to xts or not.
xtsible(data) #Will probably tell you it fails with your current setup.
xts builds on zoo, and zoo is a bit more flexible though harder to work with.
library(zoo)
zooData <- zoo(data$length, data$Time.Elapsed)
xtsible(zooData) #Will probably tell you it's ok, but probably doesn't matter since
#most/all of xts's functions work on zoo objects.
xtsData <- xts(zooData)
require(lubridate)
x <- as.POSIXct(strptime(data$Time.Elapsed, format = "%S"))
as.duration(x)
This should do the trick.

R replicate function returns a numeric matrix instead of a list of 'zoo' type

I have a function that generates a "random" time series and returns a zoo object:
f = makeTrace()
{
...details...
trace = zoo(g, dt)
}
I then call this generating function with replicate to generate many of these random time series:
make2DHist <- function(N=1000, alignG = .5, log=TRUE )
{
v = replicate(10, makeTrace())
v
}
Now if I print out the result of d=make2DHist() I get
> class(d)
[1] "matrix"
And if I print out d, I see a matrix of values. Yet if I run the time series generator function and store that in a variable I do indeed get a 'zoo' class member.
> d = makeTrace()
> class(d)
[1] "zoo"
How can I generate an arbitrary number of time series and store them together? I looked over the replicate help pages but didn't see anything about this, and there's not much on so about the replicate function.
Second, related question. I want to make a 2d histogram of these time series (time vs. value). The easiest way seems to be to convert the zoo objects into two-column data frames and then rbind all the data frames together and then use hist2d. But this seems inelegant. Is there another way to do this, preferably using zoo objects rather than having to convert to data frames?
Thanks for any suggestions.
By default, the simplify argument for replicate is set to TRUE. This means that the function checks to see whether the results are conformable to a matrix, and if it is, it returns a matrix instead of a list.
To override this behavior, set simplify = FALSE in your replicate function.

internal NA time series, zoo, R

I have a zoo object in R that has daily data and is missing the weekends. When I try to run some functions (for example ar() ) on the object i get the error:
mkt.ar <- ar(zoo_object)
Error in na.fail.default(as.ts(x)) : missing values in object
If I do:
mkt.ar <- ar(zoo_object, na.action=na.omit)
Error in na.omit.ts(as.ts(x)) : time series contains internal NAs
This makes sense since when zoo tries to convert things to ts, the weekends are inherently missing. Other than converting things to a vector using coredata(zoo_object) and running ar() on that, is there a way to tell R to skip the missing data?
Thanks
I gather that every day is represented in your data including weekdays and weekends but the days for which no data is present are NA (as opposed to not being present at all). In the future please provide some test data for better clarity.
Aside from your solution, if you have enough data you could perform an ar on weekly data only by extracting the last non-missing value on or before Friday:
library(zoo)
# test data
library(chron) # is.weekend
z <- zoo(100:130, as.Date("2000-01-01") + 0:30)
z[is.weekend(time(z))] <- NA
# extract Fridays
zfri <- na.locf(z)[format(time(z), "%w") == 5]
(If there are no missing Fridays it can be shortened by replacing na.locf(z) with z.)
Another possibility is to use 1, 2, ... for the times but give them names in which case you could always find out what date a point belongs to by checking the name of its time.
z1 <- na.omit(z)
time(z1) <- setNames(seq_along(z1), time(z1))
Simplest method will be convert the ZOO object into data.frame object by
for example (z1 is zoo object):
dz1<-data.frame(na.omit(z1))
then convert it to time series object.
ts(dz1, frequency=5)

Resources