如何在R中用几何布朗运动模拟相关股票收益?

时间:2016-10-30 14:49:04

标签: r simulation montecarlo portfolio

我正在尝试扩展我已有的代码。我的目标是通过使用历史漂移和波动来模拟具有几何布朗运动的5个相关股票的投资组合收益(对数收益)。我之前使用过代码来模拟只有一个股票的回报,而且效果很好。

背景:我开始从雅虎财务下载5家公司的股票价格(过去5年)并提取收盘价(所以现在每个股票价格只是一个列向量,而不是矩阵)。然后我使用returns.DAI = diff(log(price.DAI))(这只是戴姆勒股票的一个例子)将这5个价格向量中的每一个转换为带有日志返回的向量。然后我创建了一个矩阵来组合5个日志返回向量(returns.matrix)并计算返回矩阵的协方差矩阵。然后我用chol.decomp=chol(cov.matrix)对协方差矩阵进行了Cholesky分解。我还创建了一个带有历史漂移(mu)mu.portfolio=rbind(mu.DAI,mu.ADS,mu.BAS,mu.FME,mu.HEI)

的向量

您可能需要加载一些库 库(quantmod);库(PerformanceAnalytics)

现在是完整的代码:

# download prices from yahoo for 5 stocks manually because there are
# mistakes in the data when you use getSymbols()!!!

# ALSO, unfortunately I had to sort the csv's in Excel because 
# when you download it from yahoo, it shows the newest price first. ^^
DAI=read.csv("LOCATION ON YOUR COMPUTER/NAME OF YOUR FILE.csv")
ADS=read.csv("LOCATION ON YOUR COMPUTER/NAME OF YOUR FILE.csv")
BAS=read.csv("LOCATION ON YOUR COMPUTER/NAME OF YOUR FILE.csv")
FME=read.csv("LOCATION ON YOUR COMPUTER/NAME OF YOUR FILE.csv")
HEI=read.csv("LOCATION ON YOUR COMPUTER/NAME OF YOUR FILE.csv")

# extracting close prices
price.DAI=DAI[,5]
price.ADS=ADS[,5]
price.BAS=BAS[,5]
price.FME=FME[,5]
price.HEI=HEI[,5]

# calculating log returns
returns.DAI = diff(log(price.DAI))
returns.ADS = diff(log(price.ADS))
returns.BAS = diff(log(price.BAS))
returns.FME = diff(log(price.FME))
returns.HEI = diff(log(price.HEI))

# matrix of returns
returns.matrix=cbind(returns.DAI,returns.ADS,returns.BAS,returns.FME,returns.HEI)

# calculate mu (drift)
mu.DAI=mean(returns.DAI)
mu.ADS=mean(returns.ADS)
mu.BAS=mean(returns.BAS)
mu.FME=mean(returns.FME)
mu.HEI=mean(returns.HEI)
mu.portfolio=rbind(mu.DAI,mu.ADS,mu.BAS,mu.FME,mu.HEI)

# calculate sigma
sigma.DAI=sd(returns.DAI)
sigma.ADS=sd(returns.ADS)
sigma.BAS=sd(returns.BAS)
sigma.FME=sd(returns.FME)
sigma.HEI=sd(returns.HEI)
sigma.pf=rbind(sigma.DAI,sigma.ADS,sigma.BAS,sigma.FME,sigma.HEI)

# covariance matrix
cov.matrix=cov(returns.matrix)

# Cholesky decomposition
chol.decomp=chol(cov.matrix)

现在,这是我已经扩展但有缺陷的功能:

brownian.motion = function(number,dt,mu=c(0,0,0,0,0),sigma=cov.matrix){
  t=seq(from=0,to=number*dt,by=dt)
  n=length(t)
  # normally distributed gains
  dw=rnorm(n-1,mean=mu.portfolio*dt,sd=chol.decomp*sqrt(dt))
  # start in 0
  w=c(0,lapply(lapply(dw, cumsum), cumsum))
  return(w)
}

number=250       #DAX stocks are approximately traded on 250 days per year so that's a one year simulation.
dt=1/number      #delta (time steps)
sim=10000        #10000 simulations for each stock return
bm=matrix(nrow = number+1,ncol = sim)

for (i in 1:sim){
  bm[,i]=brownian.motion(number,dt,mu.portfolio,cov.matrix)
}

运行此代码时出现以下错误: “bm [,i]中的错误= brownian.motion(数字,dt,mu.portfolio,cov.matrix):矩阵上的下标数量不正确

有人可以帮帮我吗?我变得绝望,因为我尝试了很多,而且总会有另一个错误。如果我把chlesky分解和协方差矩阵放在数学上是正确的,我甚至不是100%肯定。

0 个答案:

没有答案