如何在R(quantmod包)中的data.frame上转换xts对象

时间:2018-03-24 21:06:53

标签: r time-series xts quantmod

我想在R。

中将xts对象转换为data.frame格式

然而,我刚刚解决了。 现在,我将与您分享。

示例:

正在加载包

library(quantmod) library(tidyverse)

获取SP500索引

SP500 <- getSymbols("^GSPC", src = "yahoo", from = as.Date("2002-01-01"), to = as.Date("2017-12-31"))

生成GSPC档案。

head(GSPC) GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted 2002-01-02 1148.08 1154.67 1136.23 1154.67 1171000000 1154.67 2002-01-03 1154.67 1165.27 1154.01 1165.27 1398900000 1165.27 2002-01-04 1165.27 1176.55 1163.42 1172.51 1513000000 1172.51 2002-01-07 1172.51 1176.97 1163.55 1164.89 1308300000 1164.89 2002-01-08 1164.89 1167.60 1157.46 1160.71 1258800000 1160.71 2002-01-09 1160.71 1174.26 1151.89 1155.14 1452000000 1155.14

class(GSPC) "[1] xts" "zoo"

如何解决?

Tibble将转换xts格式。

SP500 <- as.tibble(GSPC)

A tibble: 6 x 6 GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1148.08 1154.67 1136.23 1154.67 1171000000 1154.67 2 1154.67 1165.27 1154.01 1165.27 1398900000 1165.27 3 1165.27 1176.55 1163.42 1172.51 1513000000 1172.51 4 1172.51 1176.97 1163.55 1164.89 1308300000 1164.89 5 1164.89 1167.60 1157.46 1160.71 1258800000 1160.71 6 1160.71 1174.26 1151.89 1155.14 1452000000 1155.14

每个行名称在哪里?它在那里!

head(rownames(SP500)) [1] "2002-01-02" "2002-01-03" "2002-01-04" "2002-01-07" "2002-01-08" "2002-01-09"

输出是日期格式。

DATE <- rownames(SP500) DATE %<>% as.Date()

管道命令(%&gt;%)永远保存我们!

创建新变量并订购列名称

SP500 %<>% mutate(DATE = DATE) %>% select(DATE, GSPC.Open:GSPC.Adjusted)

然后..

# A tibble: 6 x 7 DATE GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 2002-01-02 1148.08 1154.67 1136.23 1154.67 1171000000 1154.67 2 2002-01-03 1154.67 1165.27 1154.01 1165.27 1398900000 1165.27 3 2002-01-04 1165.27 1176.55 1163.42 1172.51 1513000000 1172.51 4 2002-01-07 1172.51 1176.97 1163.55 1164.89 1308300000 1164.89 5 2002-01-08 1164.89 1167.60 1157.46 1160.71 1258800000 1160.71 6 2002-01-09 1160.71 1174.26 1151.89 1155.14 1452000000 1155.14

我希望这会有所帮助。 见到你。

1 个答案:

答案 0 :(得分:2)

通常这样做的方式是:

library(quantmod) # also pulls in xts and zoo
getSymbols("^GSPC")
DF <- fortify.zoo(GSPC)