Home > Enterprise >  R Tidyquant adding a price difference column to a tibble
R Tidyquant adding a price difference column to a tibble

Time:04-18

I'm trying to add a column to a Tidyquant tibble. Here's the code:

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.

Now, I'm attempting to add the change_on_day column (that's just the difference in the 'adjusted' prices between one day and the next) using the following:

prices$change_on_day <- diff(prices$adjusted)

The error message is:

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.

How would I add this price difference column?

Thanks!

CodePudding user response:

If you are trying to get today's value from the previous date value then you should be able to do that with the lag() function

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

CodePudding user response:

We can use tq_transmute with quantmod::periodReturn setting the period argument to 'daily' in order to calculate daily returns.

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

Created on 2022-04-18 by the reprex package (v2.0.1)

For more information check this vignette

  • Related