R Tidyquant在标签中添加价格差异列



我正在尝试向Tidyquant标题添加一列。下面是代码:

library(tidyquant)
symbol <- 'AAPL'
start_date <- as.Date('2022-01-01')  
end_date <- as.Date('2022-03-31')    
prices <- tq_get(symbol,
from = start_date,
to = end_date,
get = 'stock.prices')
head(prices)
# A tibble: 6 x 8
symbol date        open  high   low close    volume adjusted
<chr>  <date>     <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
1 AAPL   2022-01-03  178.  183.  178.  182. 104487900     182.
2 AAPL   2022-01-04  183.  183.  179.  180.  99310400     179.
3 AAPL   2022-01-05  180.  180.  175.  175.  94537600     175.
4 AAPL   2022-01-06  173.  175.  172.  172   96904000     172.
5 AAPL   2022-01-07  173.  174.  171.  172.  86709100     172.
6 AAPL   2022-01-10  169.  172.  168.  172. 106765600     172.

现在,我正在尝试添加change_on_day列(这只是一天与第二天之间"调整"价格的差异),使用以下命令:

prices$change_on_day <- diff(prices$adjusted)

错误信息是:

Error: Assigned data `diff(prices$adjusted)` must be compatible with existing data.
x Existing data has 61 rows.
x Assigned data has 60 rows.
i Only vectors of size 1 are recycled.

我如何添加这个价格差异列?

谢谢!

如果您试图从前一个日期值中获取今天的值,那么您应该能够使用lag()函数

prices %>% 
mutate(change_on_day=adjusted-lag(adjusted,1))

我们可以使用tq_transmutequantmod::periodReturn将period参数设置为'daily',以便计算每日收益。

library(tidyquant)
symbol <- "AAPL"
start_date <- as.Date("2022-01-01")
end_date <- as.Date("2022-03-31")
prices <- tq_get(symbol,
from = start_date,
to = end_date,
get = "stock.prices"
)

stock_returns_monthly <- prices %>%
tq_transmute(
select = adjusted,
mutate_fun = periodReturn,
period = "daily",
col_rename = "change_on_day"
)
stock_returns_monthly
#> # A tibble: 61 × 2
#>    date       change_on_day
#>    <date>             <dbl>
#>  1 2022-01-03      0       
#>  2 2022-01-04     -0.0127  
#>  3 2022-01-05     -0.0266  
#>  4 2022-01-06     -0.0167  
#>  5 2022-01-07      0.000988
#>  6 2022-01-10      0.000116
#>  7 2022-01-11      0.0168  
#>  8 2022-01-12      0.00257 
#>  9 2022-01-13     -0.0190  
#> 10 2022-01-14      0.00511 
#> # … with 51 more rows

由reprex包(v2.0.1)于2022-04-18创建

有关更多信息,请查看此小插图

相关内容

  • 没有找到相关文章

最新更新