Overall aim: Create a variable in a data frame of daily stock prices that indicates how many days have passed since the firm presented earnings. This should be done by looking up the date in another data frame.
I have two data frames: One containing daily stock prices (df1) and another containing quarterly observations with reported earnings by the firm (df2). In df1, I aim to create a new variable which is days from reported earnings i.e. the day earnings is reported is day 0, and the following day is 1 etc. untill it reaches next reporting date, where it should start over from 0.
How do I match the date of the stock price in df1 with the nearest date of reported earnings in df2 and assign it to a variable in df1? I have multiple firms in my dataset.
Example: Ideally, my final result in df1 should look like this where the last variable indicates that the earnings announcement of the firm was 2019/01/30:
date stock price days from earnings announcement
2019/01/30 4,4 0
2019/01/31 4,2 1
2019/02/01 4,5 2
2019/02/02 4,6 3
...
Now, assume that the firm presents new earnings announcement on 2019/04/30. If so, it should look like this:
date stock price days from earnings announcement
2019/01/30 x 0
2019/01/31 x 1
2019/02/01 x 2
2019/02/02 x 3
...
2019/04/29 x 89
2019/04/30 x 0
2019/05/01 x 1
...
Thus, it is indicated that 2019/04/29 is 89 days after the latest earnings announcement and on 2019/04/30 new earnings announcement was presented. The relevant files (including first steps of the code) can be found on this link to dropbox
stackoverflow.r:
setwd("~/R")
setwd("~/R/stackoverflow")
library(readr)
df2 <- read_delim("eps_forecasted_clean.csv",
";", escape_double = FALSE, col_types = cols(date = col_date(format = "%d-%m-%Y")),
trim_ws = TRUE)
View(df2) #use "date" to lookup
df1 <- read_delim("~/R/stackoverflow/stock_prices.csv",
";", escape_double = FALSE, trim_ws = TRUE)
View(df1)