简体   繁体   中英

How to get OHLC monthly high and low data using tq_transmute from tidyquant package in R

I am new to analyzing time series data and am looking for some help pull the monthly high and low prices from some OHLC data. When I try and aggregate the monthly open, high, low, and close prices, only the values from the last date of each month get pulled rather than the max (high) and min (low) for each month. Any help is greatly appreciated.

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)

Currently, it is just pulling the last observation of each month. Instead, I would like the first open, max high, min low, last closed, and total volume.

At the time of writing: still 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 monthly (or any other time period) and turn back into a data.frame format. Including nest and unnest from tidyr and map from purrr.

Code below will solve your issue even for multiple tickers.

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. 143623300

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM