r - 模拟带有漂移的随机游走(使用 for 循环)
问题描述
我正在尝试使用循环构建带有漂移的随机游走过程的模拟,但是,我无法获得任何输出,而是出现长度错误(要替换的项目数不是替换长度的倍数)我无法完全理解,因为我提供的长度会随任意数量的值(N)而变化。我应该能够提供特定的值,然后模拟随机游走。这是我的代码:
random_walk <- function(prices){
prices <- as.vector(prices)
ln_prices <- log(prices)
N <- length(prices)
phi0 <- (ln_prices[N] - ln_prices[1]) / N
sigma <- sd(ln_prices) / sqrt(ln_prices)
shock <- rnorm(ln_prices, 0, sigma)
rw1 <- c(ln_prices[1])
for (i in 2:N){
# I calculate the rw value for day t:
# rw <- drift + shock + rw of yesterday
rw1 <- rw1 + phi0 + shock
}
}```
解决方案
你需要从这个函数中返回一些东西,你可以使用 return 或者只是在最后一行调用你想要的名称
random_walk <- function(prices){
prices <- as.vector(prices)
ln_prices <- log(prices)
N <- length(prices)
phi0 <- (ln_prices[N] - ln_prices[1]) / N
sigma <- sd(ln_prices) / sqrt(ln_prices)
shock <- rnorm(ln_prices, 0, sigma)
rw1 <- c(ln_prices[1])
for (i in 2:N){
# I calculate the rw value for day t:
# rw <- drift + shock + rw of yesterday
rw1 <- rw1 + phi0 + shock
}
return(rw1)
}
price <- c(10,11,9,10.6,10.2,9.8,8.5,8,8.8,11)
random_walk(prices = price)
#> [1] 2.5747813 2.2403036 1.8345087 2.9714599 1.4440819 0.8269357 2.0922631
#> [8] 2.0563724 1.7999183 3.1020998
由reprex 包于 2021-06-03 创建 (v2.0.0 )
会话信息sessionInfo()
#> R version 4.1.0 (2021-05-18)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 21390)
#>
#> Matrix products: default
#>
#> locale:
#> [1] LC_COLLATE=Portuguese_Brazil.1252 LC_CTYPE=Portuguese_Brazil.1252
#> [3] LC_MONETARY=Portuguese_Brazil.1252 LC_NUMERIC=C
#> [5] LC_TIME=Portuguese_Brazil.1252
#>
#> attached base packages:
#> [1] stats graphics grDevices utils datasets methods base
#>
#> loaded via a namespace (and not attached):
#> [1] ps_1.6.0 digest_0.6.27 withr_2.4.2 magrittr_2.0.1
#> [5] reprex_2.0.0 evaluate_0.14 highr_0.9 stringi_1.6.2
#> [9] rlang_0.4.11 cli_2.5.0 rstudioapi_0.13 fs_1.5.0
#> [13] rmarkdown_2.8 tools_4.1.0 stringr_1.4.0 glue_1.4.2
#> [17] xfun_0.23 yaml_2.2.1 compiler_4.1.0 htmltools_0.5.1.1
#> [21] knitr_1.33
推荐阅读
- c# - 刷新失败,出现 403 Forbidden 错误。刷新令牌已撤销或过期
- python - python 正则表达式解析键值对,值中有多行
- angular - 带有 Angular2 的 vmwClarity 中的 CrlTab
- java - 如何防止后退按钮,直到确认消息?
- javascript - 导出带有图像的 excel 文件 - Reactjs
- nginx - 在 content-security-policy 中隐藏一个端口,以便 script-src 将 url 视为自己
- oracle - Oracle.DataAccess.Client.OracleException:无法加入分布式事务
- php - Twilio SDK PHP - 在房间里设置 mediaRegion?
- microservices - 在实践中设计微服务
- java - 将 JSON 字符串解析为 Java Double 时出现 NumberFormatException