Search code examples
rindexingquantmod

matching the stock price with the dividend payout date


I have the following code:

library(quantmod)
AAPL_dividend<-getDividends("AAPL",from='2017-01-01',to='2022-01-01')
getSymbols("AAPL",from='2017-01-01',to='2022-01-01')
AAPL_Price<-AAPL$AAPL.Close

What I would like to do here is that, under the time frame, I would like to locate the stock price from AAPL_Price with respect to the dividend payout date from AAPL_dividend. May I know if there is such a function to do so? Thanks a lot.


Solution

  • We may merge the datasets by the index, convert to data.frame (fortify.zoo) and drop the na

    library(dplyr)
    library(zoo)
    library(tidyr)
    merge(AAPL, AAPL_dividend) %>% 
      fortify.zoo() %>% 
      drop_na(AAPL.div)
    

    -output

            Index AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted AAPL.div
    1  2017-02-09   32.9125   33.1125  32.7800    33.1050   113399600      31.16726 0.035625
    2  2017-05-11   38.1125   38.5175  38.0775    38.4875   109020400      36.38427 0.039375
    3  2017-08-10   39.9750   40.0000  38.6575    38.8300   163217200      36.85221 0.039375
    4  2017-11-10   43.7775   43.8450  43.5675    43.6675   100582000      41.59229 0.039375
    5  2018-02-09   39.2675   39.4725  37.5600    39.1025   282690400      37.39608 0.039375
    6  2018-05-11   47.3725   47.5150  46.8625    47.1475   104848800      45.26388 0.045625
    7  2018-08-10   51.8400   52.2750  51.6675    51.8825    98444800      49.98439 0.045625
    8  2018-11-08   52.4950   52.5300  51.6875    52.1225   101450400      50.39082 0.045625
    9  2019-02-08   42.2475   42.6650  42.1050    42.6025    95280000      41.36375 0.045625
    10 2019-05-10   49.3550   49.7125  48.1925    49.2950   164834800      48.04597 0.048125
    11 2019-08-09   50.3250   50.6900  49.8225    50.2475    98478800      49.16042 0.048125
    12 2019-11-07   64.6850   65.0875  64.5275    64.8575    94940400      63.64484 0.048125
    13 2020-02-07   80.5925   80.8500  79.5000    80.0075   117684000      78.69791 0.048125
    14 2020-05-08   76.4100   77.5875  76.0725    77.5325   133838400      76.46986 0.051250
    15 2020-08-07  113.2050  113.6750 110.2925   111.1125   198045600     109.78722 0.051250
    16 2020-11-06  118.3200  119.2000 116.1300   118.6900   114457900     117.47666 0.205000
    17 2021-02-05  137.3500  137.4200 135.8600   136.7600    75693800     135.56421 0.205000
    18 2021-05-07  130.8500  131.2600 129.4800   130.2100    78973300     129.29073 0.220000
    19 2021-08-06  146.3500  147.1100 145.6300   146.1400    54126800     145.32565 0.220000
    20 2021-11-05  151.8900  152.2000 150.0600   151.2800    65463900     150.65659 0.220000