1

I am struggling to come up with a R script to read multiple stock price (OHLCV) cvs files and only pick up the Close column then merge into a single matrix xts time series with colnames of each stocks and column of Close prices series. I managed to have tried sapply to loop each file names vector but resulting matrix seems to be in wrong dimension of just one single column with each Close price list appended, instead of the ecpected muticolumn matrix, any suggestions? Many thanks.


Convert .csv files into RData:

filenames <- list.files(path="/data/stockdata/", pattern=".*csv")
names <-substr(filenames,1,8)

for(i in names){
filepath <- file.path("/data/stockdata/",paste(i,".csv",sep=""))
assign(i, i<-read.csv(filepath, sep = ",",dec="."))
i<-xts((as.matrix(i[,-1])),(as.POSIXct(paste(i[,1]),"%y/%m/%d")))
colnames(i) <- c('Open','High','Low','Close','Volume','Adjusted')
save(i,file = filepath)
}

Below is what I tried to merge all the Close price into a single matrix:

filenames <- list.files(path="/data/stockdata/",pattern=".*")
stocknames<-as.vector(substr(filenames,1,8))

mergeclose = function(f) {
# read different stocks and take the Close price into a merged array
fullpath<-paste("/data/stockdata/",f,".RData",sep="")
load(fullpath)
assign(f,f<-i[,4])
cbind(f)
}

allstocks_close <- sapply(stocknames, mergeclose)

The resulting matrix looks this way:

StockA
2013.07.01 12.2
....
StockB 
2013.07.01 13.3

while what I intended was:

          StockA StockB
2013.07.01 12.2  13.3
C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134
Hao
  • 59
  • 6

0 Answers0