Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

data.table - Converting daily data to weekly data using R

I have the daily data of two stocks (Apple and Google)

library(tidyquant)
dt = tidyquant::tq_get(c("AAPL", "GOOG")) %>%
  arrange(symbol, date)

I am trying to convert this data from daily to weekly using the following code

result = dt %>%
  group_by(symbol) %>%
  tidyquant::tq_transmute(mutate_fun = to.weekly) %>% data.table
result[symbol == "AAPL" & date == "2017-02-03"]

Somehow, the result is wrong. As an example, the weekly data for AAPL on 2017-02-03 is coming as follows using the above code-

   symbol       date    open    high   low close   volume 
1:   AAPL 2017-02-03 32.0775 32.2975 32.04 32.27 98029200 

However, the correct result should be -

   symbol       date     open     high      low  close   volume 
1:   AAPL 2017-02-03  30.2325  32.6225  30.1550  32.2700 999124986   

Can someone help me here?

Thanks!

question from:https://stackoverflow.com/questions/65873070/converting-daily-data-to-weekly-data-using-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

At the time of writing: a bug, see github issue 148.

A possible workaround, using tidyr and timetk and purrr. Using timetk to get the data into xts format, transform data into weekly and turn back into a data.frame format. Including nest and unnest from tidyr and map from purrr. data.table is not needed but prints the data a lot better than tibbles.

library(tidyr)
library(timetk)
# library(purrr)

result <- dt %>% 
  group_by(symbol) %>% 
  nest() %>%   
  mutate(data = purrr::map(data, function(x) x %>% 
                             select(date, Open = open, High = high, Low = low, Close = close) %>% 
                             tk_xts(x, select = c(Open, High, Low, Close), date_var = date) %>% 
                             to.weekly %>% 
                             tk_tbl)) %>% 
  unnest(data) %>% 
  rename_with( ~ tolower(gsub("..", "", .x, fixed = T))) %>% 
  rename(date = index)

result %>% 
  data.table %>% 
  filter(date == "2017-02-03")

   symbol       date     open     high     low  close
1:   AAPL 2017-02-03  30.2325  32.6225  30.155  32.27
2:   GOOG 2017-02-03 814.6600 815.8400 790.520 801.49

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...