I am a rookie of VBA that I have a problem to use sqr() in VBA. Whenever I use Sqr() function in VBA, A message box appear" Run-time error'6' Overflow" on SigSqrdt = sigma * Sqr(dt) row. And I am trying to simulate the Brownian Motion only.
Sub Simulating_Geometric_Brownian_Motion()
Dim T, S, mu, sigma, dt, SigSqrdt, LogS, drift, i, N
T = InputBox("Enter the length of the time period (T)")
N = InputBox("Enter the number of periods (N)")
S = InputBox("Enter the initial stock price (S)")
mu = InputBox("Enter the expected rate of return (mu)")
sigma = InputBox("Enter the volatility (sigma)")
dt = T / N
SigSqrdt = sigma * Sqr(dt)
drift = (mu - 0.5 * sigma * sigma) * dt
LogS = Log(S)
ActiveCell.Value = "Time"
ActiveCell.Offset(0, 1) = "stock price"
ActiveCell.Offset(1, 0) = 0 ' beginning time
ActiveCell.Offset(1, 1) = S 'beginning stock price
For i = 1 To N
ActiveCell.Offset(i + 1, 0) = i * dt
LogS = LogS + SigSqrdt * RandN()
ActiveCell.Offset(i + 1, 1) = Exp(LogS)
Next i
End Sub
Function RandN()
RandN = Application.NormSInv(Rnd())
End Function
Sample inputs:
T=1000, N=1000, S=10, mu=10, sigma=1
SigSqrdt = sigma * Sqr(dt)the overflow is likely to be the*rather thanSqr(dt). Also, why not declare the types of the variables?Option Explicit, and declare your variables. If you declareDim SigSrdt As Doubleit will hold a fairly large value but it could still overflow when using very large numbers. NOTE: The largest number a double can hold is 1.79769313486231570 • 10^308