I have this R code for simulating log-return from Normal distribution. I have understood the code but lacking some knowledge to transform it to Julia fully.
R-Code
rt.sim<-rnorm(sim.size,mean=(mu_hat-s^2/2),sd=s)
Asset.sim<-rep(NA,sim.size)
Asset.sim[1]<-Asset[n]*exp(rt.sim[1])
for(i in 2:sim.size)Asset.sim[i]<-Asset.sim[i-1]*exp(rt.sim[i])
yl<-min(Asset)*0.85
yu<-max(Asset)*1.9
plot(ts(Asset),xlim=c(0,(n sim.size)),ylim=c(yl,yu))
lines((n 1):(n sim.size),Asset.sim,col="red",lwd=2)
grid(col="black",lwd=2)
This is my Julia version. I tried in this way and got error for this code. Can anyone help me to fix it? Julia Code
FTSE = df[!,"FTSE"]
Asset = FTSE
sim.size = 500 #got error here
n = length(Asset)
## log-return
rt = diff(log.(Asset))
rbar = mean(rt)
s = sd(rt)
delta_t = 1
mu_hat = rbar s^2/2
Random.seed!(123)
## Simulate log-return from Normal distribution
rt.sim = rand(Normal(s^2/2, s),sim.size)
Asset.sim = Vector{Int}(undef,sim.size)
Asset.sim[1] = Asset[n]*exp(rt.sim[1])
for i in 2:sim.size
Asset.sim[i] = Asset.sim[i-1]*exp(rt.sim[i])
end
yl = min(Asset)*0.85
yu = max(Asset)*1.9
plot(ts(Asset),xlim=c(0,(n sim.size)),ylim=c(yl,yu))
lines((n 1):(n sim.size),Asset.sim,col="red",lwd=2)
# grid(col="black",lwd=2)
CodePudding user response:
As Bogumil says in the main you need to move from using .
in your variable names to _
or some other alternative.
The plot commands in your question aren't Julia syntax at all, here's a complete reproducible example:
using DataFrames, Distributions, MarketData, Plots, Statistics
# Get data from Yahoo
df = dropmissing(select(DataFrame(yahoo("^FTSE")), :timestamp, :AdjClose));
# Restricting range to have a similar number of observations to your plot
ftse = df.AdjClose[end-1900:end];
# Simulation dimensions
sim_size = 500;
n = length(ftse);
# Simulate log returns
log_return = diff(log.(ftse));
r̄ = mean(log_return);
σ = std(log_return);
μ̂ = r̄ σ^2/2;
rt_sim = rand(Normal(σ^2/2, σ), sim_size);
# More concise way of writing the loop
asset_sim = ftse[end] .* exp.(cumsum(rt_sim));
# Plot observed data and add simulated data to plot
plot(ftse, color = "black", xlabel = "Time", ylabel = "Close", label = "Observed data", legend = :topleft)
plot!(n 1:n sim_size, asset_sim, color = "red", label = "Simulated data")
This gives:
(Clearly I've been using a different date range to yours. Also your simulation seems to have a stronger positive trend, note that in R you are using what looks like a volatility drag adjusted mean return, in the Julia version you create a μ̂
variable but are actually just using σ^2/2
as the mean return when drawing simulated returns)