Question

I want to extract the time for some stock market to fit tree model. For example these codes are for loading Nikkei Market data:

library(quantmod)
library(zoo)
symbols=c('^N225')
getSymbols(symbols,src='yahoo', from="2003-04-28", to="2007-10-29")

After that, I want to extract the time that the market is work (we could see the time in the first left column of the market data after we write N225). when we save these data with csv format the time column is replaced with ID number. Someone say that use the zoo format and after I save the data with these code:

N<-data.frame(N225)
Ndata<-read.zoo(N)

the warning has appeared as follow:

In zoo(rval, index(x)[i]) :
some methods for “zoo” objects do not work if the index entries in ‘order.by’ are not unique

and when we write Ndata the time column is replaced with some number that is not the time. how can I extract the time?

Was it helpful?

Solution

I can't get your code to run, but this will get the same info. from the St. Louis Fed:

library(quantmod)
library(zoo)
symbols=c('NIKKEI225')
getSymbols(symbols,src='FRED')

df <- as.data.frame(NIKKEI225)
df <- cbind(date=as.Date(rownames(df)),df)
write.csv(df,file="Ndata.csv, row.names=F)

The problem is that getSymbols(...) returns a timeseries object, where the times are implicit. So when you save you just get the "time index", rather than a data-time variable. The code above makes the times explicit by putting them in a column of the dataframe, and explicitly setting them to class Date.

As @GSee points out in the comment below, this is another, better way:

df <- data.frame(date=index(NIKKEI225),NIKKEI225)
write.csv(df,file="Ndata.csv, row.names=F)

OTHER TIPS

Looks like getSymbols might be giving you trouble. I don't have a API key for Yahoo so I had to manually download the file and I did not have any trouble.

library(quantmod)
symbols=c('^N225')
getSymbols(symbols,src='yahoo', from="2003-04-28", to="2007-10-29")
#this returned an error so I had to manually read in the CSV file
N225 <- read.csv("table.csv")
Ndata <- read.zoo(N225)
head(Ndata)
           Open High  Low Close Volume Adj.Close
2003-04-28 7679 7685 7604  7608  46000      7608
2003-04-30 7695 7831 7695  7831  63200      7831
2003-05-01 7804 7896 7746  7863  55800      7863
2003-05-02 7863 7907 7792  7907  53400      7907
2003-05-06 7995 8133 7995  8084  61400      8084
2003-05-07 8127 8156 8062  8110  57600      8110
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top