# Finance with Monte Carlo Sample Code Essay

Submitted By cmd4856
Words: 510
Pages: 3

Random walk:
> set.seed(100)
> n=1000
> x=cumsum(sample(c(-1,1),n,replace=TRUE))
> plot(x,type="l")

ARW:
Deltat= 10 %# time periods
T = 100 %Time(days)
N=T/deltat %# steps
For (t in 1:N)
{
rnorm(t,0,1)
}

1/19

arm.fun=function(x0,t,deltat,mu,sigma)
{
n=t/deltat
x.t=vector(length=n)
x.t[1]=x0+(mu*deltat+sigma*sqrt(deltat)*rnorm(1)) for (I in 2:n)
{
x.t[i]=x.t[i-1]+(mu*deltat+sigma*sqrt(deltat)*rnorm(1))
}
return(x.t)
}

1/26

end.fun=function(s0,t,mu,sigma,m){ end.s=vector(length=m) for (j in 1:m){ temp=gbm.fun(s0,t,mu,sigma) end.s[j]=temp[length(temp)]} return(end.s)}

gbm.fun=function(s0,t,mu,sigma){ deltat=1/365 n=t/deltat s.t=vector(length=n) deltas=s0*(mu*deltat+sigma*sqrt(deltat)*rnorm(1)) s.t[1]=deltas+s0 for (i in 2:n){ deltas=s.t[i-1]*(mu*deltat+sigma*sqrt(deltat)*rnorm(1)) s.t[i]=s.t[i-1]+deltas} return(s.t)}

Moving average:

n=length(prices)
Ma=vector(length=n)
Si=vector(length=n)
For (i in 1:n){ Si=prices[n-i]}
Return (si)

For (t in n-1:r) {
A=0
For (I in 0:n-1) {
A=a+si[t-i] }
Ma=a/n }
Return(ma)

Algorithm 5:
App.fun=function(n){
Z=vector(length=n)
For i in [1:n] {
Z=Z+runif(1) }
Z
2/1

bopm.fun=function(x0,u,d,n){ x=c( ) %collection…need to find relationship b/w # of nodes to put in vector form x[1] =x0 count=2 for (i in 1:n) { for (j in 0:i){ x[count]=x0 *u^j *d^(i-j) count=count+1} } return(x) }

2/15/15

ma.fun=function(prices,n)
{N=length(prices)
m=N-n+1 Ma=vector(length=m) for (i in 1:m) {Ma[i]=mean(prices[i:(i+n-1)])} return(Ma)}

risk.return=function(N,mu1,mu2,mu3,sig1,sig2,sig3,cov12,cov13,cov23){ for (i in 1:N){ sum=0 for (j in 1:3){ w[j]=runif(1) sum= sum + w[j] } for (j in 1:3){…