How to convert an array to xts - r

library(quantmod)
getSymbols('AAPL')
n <- nrow(AAPL)
a <- runif(n)
I would like to convert a to an xts object with dates equal to the dates of AAPL.
So far I wasn't able to do it by any way.

This is very simple:
a <- xts(runif(nrow(AAPL)), index(AAPL))

Related

How to convert stock data from xts object to ts object

I used quantmod to download stock data from yahoo finance. Here msft is a xts object.
library(quantmod)
library(forecast)
library(xts)
library(zoo)
start <- as.Date('2018-01-01')
end <- as.Date('2018-08-14')
getSymbols('MSFT', src='yahoo', from=start, to=end)
msft <- MSFT[, 'MSFT.Adjusted']
I'm trying to convert xts object to ts object. Below is what I did. My result is kind of weird. What frequency should I put in this case? The stock data are daily data (weekdays only). Thanks a lot for help.
ts(msft, start=c(2018,1,1), frequency = 365)
You can use as.timeSeries.xts from the xts library.
msft <- as.timeSeries.xts(MSFT)
str(as.timeSeries.xts(msft))
plot(msft)
I hope this will help
msft1<- as.data.frame(msft) #converting it to Data frame
rownames(msft1) <- NULL #Nullify all the rownames
timeseries<-ts(msft1, start=c(2018,1,1), frequency = 365) #convert it into a ts object
plot(timeseries) ## Plot to verify the time series
you can select weekdays from the below code
# install.packages('timeDate')
require(timeDate)
# A ’timeDate’ Sequence
tS <- timeSequence(as.Date("1991/1/4"), as.Date("2010/3/1"))
tS
# Subset weekdays
tW <- tS[isWeekday(tS)]; tW
dayOfWeek(tW)

Convert all cells in a matrix to time format in R

I have a large matrix full of times in character format like this
a <- as.matrix(c("18:12:30", "6:15:30", "12:31:40"))
b <- as.matrix(c("1:50:30", "9:50:32", "5:30:43"))
c <- as.matrix(c("7:54:23", "22:45:34", "12:54:23"))
mat <- cbind(a,b,c)
I would like to convert each of the values to a time format. I know I could do it row by row using
a <- strptime(a, "%H:%M:%OS")
b <- strptime(b, "%H:%M:%OS")
c <- strptime(b, "%H:%M:%OS")
But I have a large matrix, so I'm looking for a function that could do this even if I have many more columns and rows.
Beware of how your time and date data is stored. strptime converts to POSIXlt, which always includes a date, so strptime inserts today's date if you don't specify one. That can create huge reproducibility problems.
Instead, you need to use a package to get a suitable time data structure. chron has a nice simple one. To recreate a data.frame of times (matrices can only store numbers):
library(chron)
# lapply chron over the columns of your data; collect in data.frame
time_mat <- do.call(data.frame, lapply(list(a, b, c), function(x){chron(times. = x)}))
# make the names prettier
names(time_mat) <- c('a', 'b', 'c')
which gives you
> time_mat
a b c
1 18:12:30 01:50:30 07:54:23
2 06:15:30 09:50:32 22:45:34
3 12:31:40 05:30:43 12:54:23
with a class of times, which will be consistent in any usage.

Extracting the numerical values of a xts object

I want to extract the numerical values of a xts object. Let's look at an example
data <- new.env()
starting.date <- as.Date("2006-01-01")
nlookback <- 20
getSymbols("UBS", env = data, src = "yahoo", from = starting.date)
Reg.curve <- rollapply(Cl(data$UBS), nlookback, mean, align="right")
The Reg.cuve is still a xts object but actually I'm just interested in the running means. How can I modify Reg.curve to get a numerical vector?
Use coredata:
reg.curve.num <- coredata(Reg.curve)
# or, if you want a vector:
reg.curve.num <- drop(coredata(Reg.curve))
To extract the numerical values of any xts, ts, or zoo object use:
as.numeric(Reg.curve)

Charting cumulative returns of a non time-based object

I have a vector of asset returns without dates in each row.
Is there a similar method as chart.CumReturns from package PerformanceAnalytics that does not require having to have a vector, dataframe etc. which is a time-based object (I do not have dates in rows).
If you want to keep all the functionality of chart.CumReturns and appearance of plots generated by the function, you may create fake dates, convert the vector to a format that chart.CumReturns accepts (e.g. xts or zoo), and then plot using chart.CumReturns with the fake x axis removed. It seems that chart.CumReturns does not handle order.by = index(x), thus you need a 'real' date.
library(PerformanceAnalytics)
library(xts)
# an example vector
vec <- coredata(edhec)[ , "Funds of Funds"]
# create fake dates, e.g.:
date <- seq(Sys.Date(), by = "1 month", length.out = length(vec))
# convert to xts (or zoo) object
xt <- xts(x = vec, order.by = date)
# plot without fake x axis
chart.CumReturns(xt, main = "Cumulative Returns", xaxis = FALSE)

Storing complex time-series in R

I have a dataframe with several columns:
state
county
year
Then x, y, and z, where x, y, and z are observations unique to the triplet listed above. I am looking for a sane way to store this in a time series and xts will not let me since there are multiple observations for each time index. I have looked at the hts package, but am having trouble figuring out how to get my data into it from the dataframe.
(Yes, I did post the same question on Quora, and was advised to bring it here!)
One option is to reshape your data so you have a column for every State-County combination. This allows you to construct an xts matrix :
require(reshape)
Opt1 <- as.data.frame(cast(Data, Date ~ county + State, value="Val"))
rownames(Opt1) <- Opt1$Date
Opt1$Date <- NULL
as.xts(Opt1)
Alternatively, you could work with a list of xts objects, each time making sure that you have the correct format as asked by xts. Same goes for any of the other timeseries packages. A possible solution would be :
Opt2 <-
with(Data,
by(Data,list(county,State,year),
function(x){
rownames(x) <- x$Date
x <- x["Val"]
as.xts(x)
}
)
)
Which would allow something like :
Opt2[["d","b","2012"]]
to select a specific time series. You can use all xts options on that. You can loop through the counties, states and years to construct plots like this one :
Code for plot :
counties <- dimnames(Opt2)[[1]]
states <- dimnames(Opt2)[[2]]
years <- dimnames(Opt2)[[3]]
op <- par(mfrow=c(3,6))
apply(
expand.grid(counties,states,years),1,
function(i){
plot(Opt2[[i[1],i[2],i[3]]],main=paste(i,collapse="-"))
invisible()
}
)
par(op)
Test-data :
Data <- data.frame( State = rep(letters[1:3],each=90),
county = rep(letters[4:6],90),
Date = rep(seq(as.Date("2011-01-01"),by="month",length.out=30),each=3),
Val = runif(270)
)
Data$year <- as.POSIXlt(Data$Date)$year + 1900

Resources