How to configure Cumulative Dividend Reinvestment with an initial Value

21 views Asked by At

I have an initial Investment turned into a number of Shares (Ex. $1000 is ~44.4 Shares)

My Data.frame() consists of finance yahoo data, being shortened to Date, Avg_Price, and Dividends.

My problem is getting both a Dividends payment and a Cumulative New Share number. I understand it's: (Input + [former cumulative Shares] )* Dividend / Avg_Price) I've tried a for loop so I could manipulate the values of i between 2:nrow(data.frame())

I'm not sure what other options I have at my disposal. I have created this same data.table in excel, but there I'm able to use 4 columns named: New Shares, Cumulative New Shares, New Share Total, and Total Share Value (They're all interdependent on each other, but I can't seem to replicate that in R)

I've tried:

data.frame1 <- fy.pull() # My own finance yahoo Data puller
  mutate(Col1 = ...lag(Col1)) # but I can't get a lag from the same column; or
  
  mutate(Col1 = ...cumsum()) # not sure why cumsum won't work for previous data

for (i in 2:nrow(data.frame)) {
  TSV[i] <- ((Input + TSV[i-1]) * data.frame$Dividends [i] / data.frame$Avg_Price[i]
}
data.frame$TSV <- TSV

I was hoping for a The Input + Shares (from cumulative Dividends payouts made back into new shares) to get the total Share Value after each monthly dividend payment of the said Stock

You can use the function: (to pull the data.frame() from finance yahoo)

D_NVDY_Pull <- function() {
  NVDY1 <- as.data.frame(read_csv("https://query1.finance.yahoo.com/v7/finance/download/NVDY?period1=1683811800&period2=1709314910&interval=1d&events=dividends&includeAdjustedClose=true"))
  NVDY2 <- as.data.frame(read_csv("https://query1.finance.yahoo.com/v7/finance/download/NVDY?period1=1683811800&period2=1709256228&interval=1d&events=history&includeAdjustedClose=true"))
  NVDY3 <- NVDY2 %>% 
    left_join(NVDY1)
  NVDY4 <- NVDY3 %>% 
    select(Date, Open, Close, `Adj Close`, Dividends) %>% 
    na.omit() %>% 
    mutate(Avg_Price = (Open + Close + `Adj Close`)/3) %>% 
    select(Date, Avg_Price, Dividends) %>% 
    arrange((Date))
}
1

There are 1 answers

0
TheNautical_Sailor On

Figured out the answer after some trial and error. Used a for loop. The code is here:

DivTest1 <- D_NVDY_Pull() # Pull the data frame
ShareCount <- c(Input,rep(NA,nrow(DivTest1)-1)) # makes NA value vector with input as starting value
Div_to_Shares <- as.numeric(rep(NA,nrow(DivTest1))) # another NA vector
DivTest1$ShareCount <- ShareCount # adds into data.frame
DivTest1$Div_to_Shares <- Div_to_Shares # adds second vector in
for (i in 1:nrow(DivTest1)) {
  DivTest1$Div_to_Shares[i] = (DivTest1$ShareCount[i] * DivTest1$Dividends[i])/ DivTest1$Avg_Price[i]
  if (i == nrow(DivTest1)) break 
  if (is.na(DivTest1$ShareCount[i + 1])) {
    DivTest1$ShareCount[i + 1] = DivTest1$ShareCount[i] + DivTest1$Div_to_Shares[i]
  }
}