简体   繁体   中英

Find the first rows in a data frame which meet a dynamic condition

Here's some sample code:

library(quantmod)
library(dplyr)


stock.prices <- getSymbols(Symbols = 'AAPL', from = '2017-08-08', to = '2017-08-17', env = NULL)[,c(2,4)]
stock.dividends <- getDividends(Symbol = 'AAPL', from = '2017-08-08', to = '2017-08-17')

summary <- merge(stock.prices, stock.dividends)
summary <- data.frame(date=index(summary), coredata(summary))
summary <- mutate(summary, buy.price = ifelse(is.na(AAPL.div), NA, lag(AAPL.Close, 1)))
summary

It produces this data:

        date AAPL.High AAPL.Close AAPL.div lag.buy.price
1 2017-08-08    161.83     160.08       NA            NA
2 2017-08-09    161.27     161.06       NA            NA
3 2017-08-10    160.00     155.32     0.63        161.06
4 2017-08-11    158.57     157.48       NA            NA
5 2017-08-14    160.21     159.85       NA            NA
6 2017-08-15    162.20     161.60       NA            NA
7 2017-08-16    162.51     160.95       NA            NA

I would like to append a column like so:

        date AAPL.High AAPL.Close AAPL.div lag.buy.price    sell.date
1 2017-08-08    161.83     160.08       NA            NA           NA
2 2017-08-09    161.27     161.06       NA            NA           NA
3 2017-08-10    160.00     155.32     0.63        161.06   2017-08-15
4 2017-08-11    158.57     157.48       NA            NA           NA
5 2017-08-14    160.21     159.85       NA            NA           NA
6 2017-08-15    162.20     161.60       NA            NA           NA
7 2017-08-16    162.51     160.95       NA            NA           NA

This finds the first date that I can sell to break even...I buy stock on 2017-08-09 to be eligible for the dividend the following day. I pay 161.06 per share. Having received the dividend, I'd now like to sell at >= 161.06. 2017-08-15 is the first day that I can do this.

I can run a for-loop to achieve this but it seems rather crude and inefficient.

Is there a way to produce the 'sell.date' column using dplyr?

This should get you there:

library(quantmod)
library(tidyverse)


stock.prices <- getSymbols(Symbols = 'AAPL', from = '2017-08-08', to = '2017-08-17', env = NULL)[,c(2,4)]
stock.dividends <- getDividends(Symbol = 'AAPL', from = '2017-08-08', to = '2017-08-17')

summary <- merge(stock.prices, stock.dividends) %>% 
  as_tibble() %>% 
  rownames_to_column('date') %>% 
  coredata() %>% 
  mutate(buy.price = ifelse(is.na(AAPL.div), NA, lag(AAPL.Close, 1)))

new_summary <- summary %>% 
  rownames_to_column() %>%
  mutate(rowname = as.numeric(rowname),
         sell.date = map2_chr(rowname, buy.price, function(row, buy){
           if(is.na(row) | is.na(buy)){
             NA
          }else{
            data <- summary %>% 
              mutate(lt_buy = AAPL.High >= buy) %>% 
              filter(lt_buy == T, rowname > row) 

            min(data$date)
          }
        }))

First, you need to append the row numbers to the data frame. Then, you should use purrr::map to iterate over the data (I changed your library(dplyr) to library(tidyverse) to get purrr ). purrr::map2 takes two vector inputs (in this case two columns of your data.frame -- which I took the liberty to switching to a tibble ) and runs a function over those inputs. The anonymous function I wrote there filters your summary tibble for dates beyond the input date and prices that are higher than the buy price. It then returns the minimum date meeting that criteria.

I also made some changes to your data setup so that it uses a pipe chain and a more tidy type of structure.

Hope this helps!

df[is.na(df$AAPL.div),'AAPL.div'] <- 0

sell.date <- 
with(df, {
  bought <- date > as.Date('2017-08-09')
  date[which.max(bought & (AAPL.Close + cumsum(AAPL.div*bought)) > 161.06)]})
sell.date     
#[1] "2017-08-15"

To add this as a column

df$sell.date <- ifelse(is.na(df$lag.buy.price), NA, sell.date)

df
#          date AAPL.High AAPL.Close AAPL.div lag.buy.price  sell.date
# 1: 2017-08-08    161.83     160.08     0.00            NA       <NA>
# 2: 2017-08-09    161.27     161.06     0.00            NA       <NA>
# 3: 2017-08-10    160.00     155.32     0.63        161.06 2017-08-15
# 4: 2017-08-11    158.57     157.48     0.00            NA       <NA>
# 5: 2017-08-14    160.21     159.85     0.00            NA       <NA>
# 6: 2017-08-15    162.20     161.60     0.00            NA       <NA>
# 7: 2017-08-16    162.51     160.95     0.00            NA       <NA>

data used

library(data.table)
df <- fread("
a        date AAPL.High AAPL.Close AAPL.div lag.buy.price
1 2017-08-08    161.83     160.08       NA            NA
2 2017-08-09    161.27     161.06       NA            NA
3 2017-08-10    160.00     155.32     0.63        161.06
4 2017-08-11    158.57     157.48       NA            NA
5 2017-08-14    160.21     159.85       NA            NA
6 2017-08-15    162.20     161.60       NA            NA
7 2017-08-16    162.51     160.95       NA            NA
")[, -1]

this solution is not entirely without a for loop, but i guess you meant a loop to compare each value (that part is vectorized here). Just in case you have more than one dividend that you observe this loop will be needed:

summary$sell.date<-as.Date(rep(NA,7))


for(i in 1:length(which(!is.na(summary$buy.price))))
summary$sell.date[which(!is.na(summary$buy.price))[i]]<- summary[c(rep(FALSE,which(!is.na(summary$buy.price))[i]-1),(summary[which(!is.na(summary$buy.price))[i]:nrow(summary),"AAPL.High"]>summary[!is.na(summary$buy.price),"buy.price"][i])),"date"][1]

it produces the following result:

     date AAPL.High AAPL.Close AAPL.div buy.price  sell.date
1 2017-08-08    161.83     160.08       NA        NA       <NA>
2 2017-08-09    161.27     161.06       NA        NA       <NA>
3 2017-08-10    160.00     155.32     0.63    161.06 2017-08-15
4 2017-08-11    158.57     157.48       NA        NA       <NA>
5 2017-08-14    160.21     159.85       NA        NA       <NA>
6 2017-08-15    162.20     161.60       NA        NA       <NA>
7 2017-08-16    162.51     160.95       NA        NA       <NA>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM