我是分析时间序列数据的新手,正在寻找一些帮助从一些OHLC数据中提取月度高价和低价。当我尝试聚合每月的开盘价、高价、低价和收盘价时,只提取每个月最后一个日期的值,而不是每个月的max (高)和min (低)。任何帮助都是非常感谢的。
library(tidyquant)
library(tidyverse)
amzn.prices <- tq_get("AMZN", get = "stock.prices", from = '2010-12-31', to = "2013-12-31")
monthly.amzn <- tq_transmute(amzn.prices, mutate_fun = to.monthly)目前,它只是提取每个月的最后一个观察值。相反,我想要第一次打开,最高,最低,最后关闭和总音量。
发布于 2021-07-23 17:05:56
在写这篇文章的时候:仍然是一个bug,请参阅github issue 148。
一种可能的解决方法,使用tidyr、timetk和purrr。使用turn将数据转换为xts格式,将数据转换为每月(或任何其他时间段),然后再转换回data.frame格式。包括来自tidyr的嵌套和取消嵌套,以及来自purrr的map。
下面的代码将解决您的问题,即使对于多个自动收报机。
library(tidyquant)
library(dplyr)
library(tidyr)
library(timetk)
amzn.prices <- tq_get("AMZN", get = "stock.prices", from = '2010-12-31', to = "2013-12-31")
monthly.amzn <- amzn.prices %>%
group_by(symbol) %>%
nest() %>%
mutate(data = purrr::map(data, function(x) x %>%
select(date, Open = open, High = high, Low = low, Close = close, Volume = volume) %>%
tk_xts(x, select = c(Open, High, Low, Close, Volume), date_var = date) %>%
to.monthly %>%
tk_tbl)) %>%
unnest(data) %>%
rename_with( ~ tolower(gsub("..", "", .x, fixed = T))) %>%
rename(date = index)
# A tibble: 37 x 7
# Groups: symbol [1]
symbol date open high low close volume
<chr> <yearmon> <dbl> <dbl> <dbl> <dbl> <dbl>
1 AMZN dec 2010 182. 182. 180. 180 3451900
2 AMZN jan 2011 181. 192. 167. 170. 113611300
3 AMZN feb 2011 171. 191. 170. 173. 95776400
4 AMZN mrt 2011 174. 182. 161. 180. 118979100
5 AMZN apr 2011 182. 198. 175. 196. 116749400
6 AMZN mei 2011 197. 206. 191. 197. 106274500
7 AMZN jun 2011 196. 206. 182. 204. 95563700
8 AMZN jul 2011 206. 227. 204. 223. 92808500
9 AMZN aug 2011 225 227. 177. 215. 155194700
10 AMZN sep 2011 215. 244 204. 216. 143623300https://stackoverflow.com/questions/68490093
复制相似问题