我正在处理来自雅虎的一些财务数据。
我的代码是
library(forecast)
library(tseries)
library(astsa)
library(fGarch)
library(quantmod)
getSymbols("^gspc",src='yahoo')
adj <- GSPC[, "GSPC.Adjusted", drop = FALSE]
n <- nrow(adj)
simpleReturn <- (adj[2:n,1] - adj[1:(n-1),1]) / adj[1:(n-1),1]
simpleReturn 是一个全是零的表 我检查了一下,甚至 adj[2,1] - adj[1,1] 结果为零,而它应该是 1.74
我希望代码返回第一个数据点之后的所有数据点的简单回报率
我觉得类/数据类型有些奇怪,以至于简单的减法不能按预期工作。我转换为小标题并计算出一切都很好:
library(tidyverse)
as_tibble(adj) |>
mutate(date = date(adj),
simple = (lead(GSPC.Adjusted)-GSPC.Adjusted)/GSPC.Adjusted)
#> # A tibble: 4,235 x 3
#> GSPC.Adjusted date simple
#> <dbl> <date> <dbl>
#> 1 1417. 2007-01-03 0.00123
#> 2 1418. 2007-01-04 -0.00608
#> 3 1410. 2007-01-05 0.00222
#> 4 1413. 2007-01-08 -0.000517
#> 5 1412. 2007-01-09 0.00194
#> 6 1415. 2007-01-10 0.00634
#> 7 1424. 2007-01-11 0.00485
#> 8 1431. 2007-01-12 0.000818
#> 9 1432. 2007-01-16 -0.000894
#> 10 1431. 2007-01-17 -0.00297
#> # i 4,225 more rows