【发布时间】:2020-08-07 20:20:32
【问题描述】:
我正在使用来自 Yahoo Finance 的 S&P500 股票价格数据(通过 getSymbols 函数下载数据)。
在周末,股票价格不变,因此不包括日期。
我想将所有缺失的日期(周末)添加为 NA 作为其余列中的值。 以2008-01-11和2008-01-14为例enter image description here
谢谢
【问题讨论】:
-
能否包含下载数据的代码?
我正在使用来自 Yahoo Finance 的 S&P500 股票价格数据(通过 getSymbols 函数下载数据)。
在周末,股票价格不变,因此不包括日期。
我想将所有缺失的日期(周末)添加为 NA 作为其余列中的值。 以2008-01-11和2008-01-14为例enter image description here
谢谢
【问题讨论】:
如果您不介意使用包,那么包timetk 可以提供帮助。有关更多信息,请参阅包装中的插图。
library(quantmod)
library(magrittr) # for the pipe %>% function
library(timetk)
out <- getSymbols("^GSPC", auto.assign = F) # get the data
out_padded <- out %>%
tk_tbl() %>% # transform into tibble
pad_by_time() %>% # add the missing records
tk_xts() # transform back into xts format.
# ignore warnings
head(out_padded)
GSPC.Open GSPC.High GSPC.Low GSPC.Close GSPC.Volume GSPC.Adjusted
2007-01-03 1418.03 1429.42 1407.86 1416.60 3429160000 1416.60
2007-01-04 1416.60 1421.84 1408.43 1418.34 3004460000 1418.34
2007-01-05 1418.34 1418.34 1405.75 1409.71 2919400000 1409.71
2007-01-06 NA NA NA NA NA NA
2007-01-07 NA NA NA NA NA NA
2007-01-08 1409.26 1414.98 1403.97 1412.84 2763340000 1412.84
当然,您也可以使用 tidyquant 和 tidyr 来做到这一点。
library(tidyquant)
out_tq <- tq_get("^GSPC")
out_tq_padded <- pad_by_time(out_tq) %>%
tidyr::fill(symbol) # using fill from tidyr to fill the NA's in the symbol column.
out_tq_padded
# A tibble: 3,763 x 8
symbol date open high low close volume adjusted
<chr> <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 ^GSPC 2010-01-04 1117. 1134. 1117. 1133. 3991400000 1133.
2 ^GSPC 2010-01-05 1133. 1137. 1130. 1137. 2491020000 1137.
3 ^GSPC 2010-01-06 1136. 1139. 1134. 1137. 4972660000 1137.
4 ^GSPC 2010-01-07 1136. 1142. 1131. 1142. 5270680000 1142.
5 ^GSPC 2010-01-08 1141. 1145. 1136. 1145. 4389590000 1145.
6 ^GSPC 2010-01-09 NA NA NA NA NA NA
7 ^GSPC 2010-01-10 NA NA NA NA NA NA
8 ^GSPC 2010-01-11 1146. 1150. 1142. 1147. 4255780000 1147.
9 ^GSPC 2010-01-12 1144. 1144. 1132. 1136. 4716160000 1136.
10 ^GSPC 2010-01-13 1137. 1148. 1133. 1146. 4170360000 1146.
# ... with 3,753 more rows
【讨论】: