【问题标题】:Attempting to make a new column using the previous value in new column (XTS)尝试使用新列中的先前值创建新列 (XTS)
【发布时间】:2021-04-17 17:58:20
【问题描述】:

我正在使用 R 和 xts 来创建一个理论场景,将 10k 投资于一只股票,并看看它会如何增长。我可以做所有事情来计算股票收益,但我不知道如何在 xts 中添加一个新列,这将占用 10k 并估计随时间的增长。

简单地说,我如何让 xts 创建一个新列,其中 x (10K) 是起始值,之后的每个点都是上个月的 x*returns?

到目前为止我的代码:

quantmod::getSymbols("^GSPC", src="yahoo")
GSPC.Returns <- quantmod::periodReturn(GSPC)
GSPC.Returns <- GSPC.Returns*100+100
y <- GSPC.Returns["2019/"]
x <- 10000

y$blargh <- x*y[,"monthly.returns"] # This is the problematic line

【问题讨论】:

    标签: r finance xts quantmod


    【解决方案1】:

    您似乎一直在寻找累积产品。我想您可能会发现 cumprod 功能很有帮助。这会返回预期的结果吗?

    GSPC.Returns <- quantmod::periodReturn(GSPC)
    GSPC.Returns <- GSPC.Returns*100+100
    y <- GSPC.Returns["2019/"]
    x <- 10000
    
    y$blargh <- ave(y / 100, FUN = cumprod) * x
    
    > y
               monthly.returns   blargh
    2019-01-31       107.86844 10786.84
    2019-02-28       102.97289 11107.52
    2019-03-29       101.79243 11306.62
    2019-04-30       103.93135 11751.12
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多