0

我希望能够计算给定股票 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 的任何想法。

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

4

1 回答 1

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
于 2017-11-21T10:24:56.487 回答