我正在努力想出一个R脚本来读取多个股票价格(OHLCV)cvs文件并且只拿起关闭列然后合并到单个矩阵xts时间序列中,每个股票的colnames和关闭价格系列的列。我设法尝试sapply循环每个文件名向量,但结果矩阵似乎只是一个单一列的错误维度,每个关闭价格列表附加,而不是预期的muticolumn矩阵,任何建议?非常感谢。
将.csv文件转换为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)
}
以下是我尝试将所有收盘价合并为单个矩阵的内容:
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)
结果矩阵看起来像这样:
StockA
2013.07.01 12.2
....
StockB
2013.07.01 13.3
虽然我的意图是:
StockA StockB
2013.07.01 12.2 13.3