如何以滚动方式计算每日一年或52周高/低的库存

时间:2017-11-21 10:14:44

标签: r tidyverse tidyquant

我希望能够计算并包含在我的数据框中52周(或一年)高和低的特定股票。

计算52周的数据。一年高/低

library(tidyquant)
bhp <- tq_get("bhp")

我为计算高/低

而构建的功能
one_yea_high_low <- function(df, start, end){
  require(tidyverse)

  df1 <- df %>% filter(date <= end & date >= start)

  one_yr_high <- df1 %>% select(high) %>% as.vector %>% max() %>% as.data.frame()
  one_yr_low  <- df1 %>% select(low) %>% as.vector %>% min() %>% as.data.frame()

  df3 <- bind_cols(one_yr_high, one_yr_low) 
  colnames(df3) <- c("yr_high", "yr_low")

  return(df3)
}

一次只能进行一次搜索:

start_date <- min(bhp$date) 
end_date   <- start_date + years(1)
one_yea_high_low(bhp, start_date, end_date)
  yr_high yr_low
1   87.43  36.37

但我无法在整个数据框架上对其进行矢量化

这不起作用(真可惜!)

map(bhp$date, ~one_yea_high_low(df = bhp, start = (.x - years(1)), end = .x))
 Show Traceback

 Rerun with Debug
 Error in FUN(X[[i]], ...) : 
  only defined on a data frame with all numeric variables 
关于如何解决这个问题的任何想法,并将最终结果包含在主df中。

我真的想用日期计算滚动窗口,因为我的数据有差距,即没有交易的天数等。

1 个答案:

答案 0 :(得分:2)

看看tibbletime,非常简单。我现在调整了高点和低点。在这里,您可以通过创建年份的关键列来加入旧版本。

library(tidyquant)
library(tibbletime)
bhp <- tq_get("bhp")

bhp_tbltime <- tbl_time(bhp, index=date)

bhp_tbltime %>%
  time_summarise(
    period   = "yearly",
    high = max(adjusted),
    low  = min(adjusted)
  )

并且滚动将成为这些方面的内容:

    roll_max <- rollify(max, window = 252)
    roll_min <- rollify(min, window = 252)

    bhp_tbltime %>% 
      mutate(max252 = roll_max(adjusted),
             min252 = roll_min(adjusted)) %>% 
      tail()

# A time tibble: 6 x 9
# Index: date
        date  open  high   low close  volume adjusted max252   min252
*     <date> <dbl> <dbl> <dbl> <dbl>   <dbl>    <dbl>  <dbl>    <dbl>
1 2017-11-13 42.37 42.86 42.31 42.70 2134300    42.70  44.15 33.01988
2 2017-11-14 42.15 42.18 41.42 41.69 2795400    41.69  44.15 33.01988
3 2017-11-15 40.99 41.31 40.72 41.21 2540100    41.21  44.15 33.01988
4 2017-11-16 41.44 41.44 41.02 41.38 3029400    41.38  44.15 33.01988
5 2017-11-17 41.30 41.41 41.14 41.38 2183900    41.38  44.15 33.01988
6 2017-11-20 41.00 41.13 40.79 41.12 2211300    41.12  44.15 33.01988
相关问题