Skip to content

Instantly share code, notes, and snippets.

@porterjamesj
Created March 20, 2014 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save porterjamesj/9673230 to your computer and use it in GitHub Desktop.
Save porterjamesj/9673230 to your computer and use it in GitHub Desktop.
@rawrjustin's bitcoin simulation
# some further optimizations
# Parameters
const S0 = 600; # current bitcoin price
const r = 0.02; # risk neutral payoff, assumed 2% for this exercise, in reality probably less.
const sigma = 2; # extremely high sigma due to spike in bitcoin prices late last year
const T = 1.0; # 1 Time cycle
const M = 100; # 100 steps
const dt = T / M # dt
# Simulating I paths with M time steps
function genS_jl_mine(I::Int)
const a = (r - 0.5 * ^(sigma,2)) * dt
const b = sigma * sqrt(dt)
# allocate M by I array in which to store results
S = Array(Float32, I, M)
# value at t =1 in each path is 600
S[:,1] = 600.0
for i in 1:I
for t in 2:M
z = randn()
S[i,t] = S[i,t-1] * exp(a + b * z)
end
end
return S
end
# run once so we don't measure compilation time
genS_jl(10)
# now measure
@elapsed genS_jl(100_000)
# => 0.312882383
#
# Simulating Geometric Brownian Motion with Julia
#
# Parameters
S0 = 600; # current bitcoin price
r = 0.02; # risk neutral payoff, assumed 2% for this exercise, in reality probably less.
sigma = 2; # extremely high sigma due to spike in bitcoin prices late last year
T = 1.0; # 1 Time cycle
M = 100; # 100 steps
dt = T / M # dt
# Simulating I paths with M time steps
function genS_jl(i::Int64)
S = {}
for i in 1:i
path = Float32[]
for t in 1:(M + 1)
if t == 1
push!(path, S0)
else
z = randn()
st = path[t - 1] * exp((r - 0.5 * ^(sigma,2)) * dt + sigma * sqrt(dt) * z)
push!(path, st)
end
end
push!(S,path)
end
return S
end
# run once so we don't measure compilation time
genS_jl(10)
# now measure
@elapsed genS_jl(100_000)
# => 10.584006556
# watch what happens when we declare the parameters as const
# Parameters
const S0 = 600; # current bitcoin price
const r = 0.02; # risk neutral payoff, assumed 2% for this exercise, in reality probably less.
const sigma = 2; # extremely high sigma due to spike in bitcoin prices late last year
const T = 1.0; # 1 Time cycle
const M = 100; # 100 steps
const dt = T / M # dt
# Simulating I paths with M time steps
function genS_jl(i::Int64)
S = {}
for i in 1:i
path = Float32[]
for t in 1:(M + 1)
if t == 1
push!(path, S0)
else
z = randn()
st = path[t - 1] * exp((r - 0.5 * ^(sigma,2)) * dt + sigma * sqrt(dt) * z)
push!(path, st)
end
end
push!(S,path)
end
return S
end
# run once so we don't measure compilation time
genS_jl(10)
# now measure
@elapsed genS_jl(100_000)
# => 1.238375246
# 10x speedup! global variables are not optimized, performance gotcha
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment