您的位置:首页 > 其它

记录R语言在时间序列分析中的一些常用写法

2018-03-23 13:51 417 查看
由于经常在不同语言中切换,需要记录时间序列开发中常遇到实用写法,暂置于此,不断修改中。。。

常用的库

library(DMwR)
library(xts)
library(quantmod)
library(jsonlite)
library(RCurl)


查看变量的类型

class(theTS)

例如输出:

[1] "xts" "zoo"

取时间序列的首尾时间

start(theTS)

例如输出:

[1] "2017-04-05 CST"

end(theTS)


合并两个时间序列

rbind.zoo(currentTS,historyTS)

为了避免麻烦,需保证两个序列时间不重叠

改时间序列的列名

names(theTS) <- c("Open", "High","Low", "Close",    "Volume" ,  "Amount")

这个写法如此不同,左侧一般是变量,这里竟然是一个动作,R 语言有独到之处。

异常处理

tryCatch({
.....
},
error=function(e){
...
Sys.sleep(3)
...
},
finally={}
)


从文件读数据

theData <- na.omit(read.table(theFileName,sep=",",header=F,fill=TRUE,fileEncoding ="gb18030"))

文件中数据,用","区分数据列,没有header

写入文件

write.zoo(theTS,theFile,sep=",",col.names=FALSE)

以,分隔字段,不写入列名;

转换为时间序列

theTS <- try.xts(theData[,c(2)],as.POSIXct(theData[,1],tryFormats = c("%Y-%m-%d %H:%M:%OS","%Y-%m-%d")))

其中第一列是时间,格式 2017-12-08 或 2017-12-08 08:09:30

读取JSON数据

aa <- fromJSON(theURL)


画K线图

getVolume <- function(da){ da[,"Volume"] }
addVolumeToChart <- newTA(FUN=getVolume,col=1,legend="Volume")
chartSeries(last(theData,100) ,name=sym,type="candlesticks",
theme = 'white',up.col = 'red',dn.col = 'green',
TA=c( addVolumeToChart()))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  R 时间序列