将每日股票系列转换为每月股票系列时出错

时间:2018-01-03 19:58:21

标签: r time-series xts

我是R的新手,很难在xts课程中将每日股票系列转换为每月一次。

我有一个股票数据,关于从Yahoo!Finance下载到.csv(逗号分隔)文件中的股票代码IOO,如下所示:

Date        Open    High    Low     Close   Adjusted Close  Volume

12/31/2012  63      63.95   63      63.95   56.11           87900

1/2/2013    64.94   65.19   64.62   65.08   57.09           77900

1/3/2013    64.94   64.98   64.63   64.68   56.74           36000

1/4/2013    64.70   65.13   64.63   65.12   57.13           49400

1/7/2013    64.83   64.91   64.61   64.88   56.93           102000

1/8/2013    64.65   64.76   64.37   64.58   56.66           31600

我在R中写了以下内容以便阅读,将其转换为xts并每日转换为每月:

library(tseries)

library(xts)

library(PerformanceAnalytics)

IOO <- read.csv(file = “IOO.csv”, header = TRUE, sep = “,”)

IOO <- subset(IOO[, c(1,2,3,4,6)])

colnames(IOO) <- c(“Date”, “Open”, “High”, “Low”, “Close”)

IOO[,“Date”] <- as.Date(IOO[,“Date”], format = “%m / %d / %Y”)

IOO <- as.xts(IOO, order.by = as.Date(rownames(IOO), “%Y-%m-%d”), dateFormat = “POSIXct”, frequency = NULL, .RECLASS = FALSE)

IOO_monthly <- to.monthly(IOO, indexAt=‘yearmon’, drop.time = TRUE, name = NULL)
  

to.period(x,“months”,indexAt = indexAt,name = name,...)出错:   不支持的类型

IOO_monthly <- to.period(IOO, period = “months”, indexAt=‘yearmon’, name = NULL)
  

to.period出错(IOO,句号=“月”,indexAt =“yearmon”,名称= NULL):   不支持的类型

IOO_monthly <- to.period(IOO, period = “months”, indexAt= NULL, name = NULL)
  

to.period出错(IOO,句号=“月”,indexAt = NULL,name = NULL):   不支持的类型

我在to.periodto.monthly中尝试了许多其他参数组合,但它没有用完。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

要回答您的实际问题:问题是您在xts对象的"Date"中添加了coredata列。 xts和zoo对象很简单,带有索引属性的矩阵(不是索引)。由于矩阵中不能包含混合列类型,因此所有数据都将转换为单一类型(在本例中为字符)。

library(xts)
# Example data
IOO <- read.csv(text="Date,Open,High,Low,Close,Adjusted,Close,Volume
12/31/2012,63,63.95,63,63.95,56.11,87900
1/2/2013,64.94,65.19,64.62,65.08,57.09,77900
1/3/2013,64.94,64.98,64.63,64.68,56.74,36000
1/4/2013,64.70,65.13,64.63,65.12,57.13,49400
1/7/2013,64.83,64.91,64.61,64.88,56.93,102000
1/8/2013,64.65,64.76,64.37,64.58,56.66,31600")
# Omit 'Close' and 'Volume' columns
IOO <- IOO[, c(1,2,3,4,6)]
# Rename 'Adjusted' column to 'Close'
colnames(IOO) <- c("Date", "Open", "High", "Low", "Close")
# Convert 'Date' column to actual Date class
IOO[, "Date"] <- as.Date(IOO[, "Date"], format = "%m/%d/%Y")
# Create xts object, using 'Date' column as index, and everything else as coredata
IOO <- xts(IOO[,-1], IOO[,1])
# Aggregate to monthly
IOO_monthly <- to.monthly(IOO)
IOO_monthly
#          IOO.Open IOO.High IOO.Low IOO.Close
# Dec 2012    63.00    63.95   63.00     56.11
# Jan 2013    64.94    65.19   64.37     56.66