模拟随机资产价格路径的R代码

问题描述

考虑以下资产价格演变模型:

enter image description here

enter image description here

enter image description here

这就是我所做的(在 R 中)。我找不到随机输出 +1 或 -1 的函数,所以我决定调整内置的 rbinom 函数

## This code is in R

rm(list = ls())

library(dplyr)
library(dint)
library(magrittr)
library(stats)

path  = 
  function(T,mu,sigma,p,x0) {
    x    = rep(NA,T)
    x[1] = x0
    
    for(i in 2:T){
    z    = if_else(rbinom(1,1,p) == 0,-1,1)
    x[i] = x[i-1] * exp(mu + sigma*z)
    }
    return(x)
  }

## Just some testing
x_sim = path(T = 4,mu = 0,sigma = 0.01,p = 0.5,x0 = 100)

## Actual answer
Np = 10000
mc = matrix(nrow = 17,ncol = Np)
for(j in 1:Np){
  mc[,j] = path(T = 17,x0 = 100)
}
test     = mc[2:nrow(mc),] >= 100
sum_test = colSums(test)
comp     = sum(sum_test >= 1)/length(sum_test)
prob     = 1 - comp

这有意义吗?任何帮助/提示/建议将不胜感激。谢谢!

解决方法

接近你的代码,我想出了这个。直觉上,如果你仔细想想,由于参数的原因,这个概率应该相当低,我得到的概率大约为 6.7%,这大概是我使用赋值中的参数运行你的代码时得到的概率。

simpath <- function(t,mu,sigma,p,x0,seed){
  # set seed
  if(!missing(seed)){
    set.seed(seed)  
  }
  # set up matrix for storing the results
  res <- matrix(c(1:t,rep(NA,t*2)),ncol = 3)
  colnames(res) <- c('t','z_t','x_t')
  res[,'z_t'] <- sample(c(1,-1),size = t,prob = c(p,1-p),replace = TRUE)
  res[1,3] <- x0
  for(i in 2:t){
    res[i,3] <- res[i-1,3] * exp(mu+sigma*res[i,2])
  }
  return(res)
}

x_sim <- simpath(t = 4,mu = 0,sigma = 0.01,p = 0.5,x0 = 100,seed = 123)
x_sim2 <- simpath(t = 36,sigma = 0.03,seed = 123)

## Actual answer
Np <- 100000
mc <- matrix(nrow = 36,ncol = Np)
for (j in 1:Np){
  mc[,j] <- simpath(t = 36,x0 = 100)[,3]
}
test <- mc > 100
sum_test <- colSums(test)
comp     = sum(sum_test == 0)/length(sum_test)
prob     = comp
> prob
[1] 0.06759

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...