将新行合并到现有xts中(目的:将当前股票报价从quantmod添加到历史对象)

时间:2015-05-14 16:03:31

标签: r xts quantmod

我喜欢做的是获取并将当前股票价格附加到历史xts对象。例如,

require(quantmod)
x=getSymbols("AAPL", from = "2014-10-27" ,auto.assign=FALSE)
q = getQuote('AAPL')

# this produces, > tail(x)
           AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
2015-05-06    126.56    126.75   123.36     125.01    72141000        124.49
2015-05-07    124.77    126.08   124.02     125.26    43940900        125.26
2015-05-08    126.68    127.62   126.11     127.62    55550400        127.62
2015-05-11    127.39    127.56   125.63     126.32    42035800        126.32
2015-05-12    125.60    126.88   124.82     125.87    47109200        125.87
2015-05-13    126.15    127.19   125.87     126.01    34322000        126.01
> q
              Trade Time     Last Change % Change   Open   High    Low   Volume
AAPL 2015-05-14 11:38:00 128.3993 2.3893 +1.8961% 127.45 128.45 127.16 22635316

我喜欢做的是将q的“Last”列放在AAPL.Close列中,High&分别低到AAPL.High,AAPL.Close。到目前为止,我已经尝试通过缓慢添加新列,重命名它们并合并回原始xts来创建新数据帧,但它似乎不起作用。提前致谢。

2 个答案:

答案 0 :(得分:2)

您只需要从引用数据创建一个新的xts对象,并将rbind创建为历史数据。

require(quantmod)
x <- getSymbols("AAPL", from = "2014-10-27" ,auto.assign=FALSE)
q <- getQuote('AAPL')

qCols <- c("Open","High","Low","Last","Volume","Last")
qx <- xts(q[,qCols], as.Date(q[,"Trade Time"]))
y <- rbind(x, qx)

tail(y)
#            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
# 2015-05-07    124.77    126.08   124.02     125.26    43940900        125.26
# 2015-05-08    126.68    127.62   126.11     127.62    55550400        127.62
# 2015-05-11    127.39    127.56   125.63     126.32    42035800        126.32
# 2015-05-12    125.60    126.88   124.82     125.87    47109200        125.87
# 2015-05-13    126.15    127.19   125.87     126.01    34322000        126.01
# 2015-05-14    127.45    128.45   127.16     128.40    22635316        128.40

答案 1 :(得分:1)

getQuote返回上次交易时间和日期。如果你需要捕获这个时间以及日期,你可以尝试类似

的东西
require(quantmod)
ticker <- "AAPL"
x <- getSymbols(ticker, from = "2014-10-27" ,auto.assign=FALSE)
q  <-  getQuote(ticker)
mkt_close_time <- "16:00:00"
index(x) <- strptime(paste(index(x),mkt_close_time), format="%F %X", tz="EST5EDT")
x <- rbind(x,xts( with(q, data.frame(Open, High, Low, Last, Volume, Last)),
                  order.by=strptime(q$"Trade Time", format="%F %X", tz="EST5EDT")))