如何配置具有初始值的累积股息再投资

问题描述 投票:0回答:1

我的初始投资已转化为一定数量的股票(例如 1000 美元约为 44.4 股)

My Data.frame() 由 yahoo 金融数据组成,缩写为

Date
Avg_Price
Dividends

我的问题是同时获得股息支付和累积新股数量。我的理解是: (输入+[原累计股数])*股息/平均价格) 我尝试了一个 for 循环,这样我就可以在 2:nrow(data.frame()) 之间操纵 i 的值

我不确定我还有哪些其他选择。我在 Excel 中创建了相同的 data.table,但我可以使用 4 个列,名称为:

New Shares
Cumulative New Shares
New Share Total
Total Share Value
(它们都是相互依赖的,但我似乎无法在 R 中复制这一点)

我已经尝试过:

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

我希望输入+股票(从累积股息支付回新股)以获得该股票每月股息支付后的总股票价值

您可以使用以下功能:(从finance yahoo拉取data.frame())

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))
}
r finance cumulative-sum yahoo-finance
1个回答
0
投票

经过一番尝试和错误后找到了答案。使用了for循环。代码在这里:

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]
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.