Skip to content

Commit c51aea4

Browse files
author
Bob Carpenter
committed
added stochastic volatility example: source, optimized source, sim, and manual
1 parent d6e8c80 commit c51aea4

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
2+
data {
3+
int<lower=0> T; // # time points (equally spaced)
4+
vector[T] y; // mean corrected return at time t
5+
}
6+
parameters {
7+
real mu; // mean log volatility
8+
real<lower=-1,upper=1> phi; // persistence of volatility
9+
real<lower=0> sigma; // white noise shock scale
10+
vector[T] h_std; // std log volatility time t
11+
}
12+
transformed parameters {
13+
vector[T] h; // log volatility at time t
14+
h <- h_std * sigma;
15+
h[1] <- h[1] / sqrt(1 - phi * phi);
16+
h <- h + mu;
17+
for (t in 2:T)
18+
h[t] <- h[t] + phi * (h[t-1] - mu);
19+
}
20+
model {
21+
sigma ~ cauchy(0,5);
22+
mu ~ cauchy(0,10);
23+
h_std ~ normal(0,1);
24+
y ~ normal(0, exp(h / 2));
25+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
2+
phi <- 0.95;
3+
sigma <- 0.25;
4+
beta <- 0.6;
5+
mu <- 2 * log(beta);
6+
7+
T <- 500;
8+
9+
h <- rep(NA,T);
10+
h[1] <- rnorm(1, mu, sigma / sqrt(1 - phi * phi));
11+
for (t in 2:T)
12+
h[t] <- rnorm(1, mu + phi * (h[t-1] - mu), sigma);
13+
y <- rep(NA,T);
14+
for (t in 1:T)
15+
y[t] <- rnorm(1, 0, exp(h[t] / 2));
16+
17+
library("rstan");
18+
start_time <- proc.time();
19+
fit <- stan(file="stochastic-volatility.stan", data=list(T=T,y=y), iter=10000, chains=4, init=0, fit=fit);
20+
elapsed_time <- proc.time() - start_time;
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
data {
2+
int<lower=0> T; // # time points (equally spaced)
3+
vector[T] y; // mean corrected return at time t
4+
}
5+
parameters {
6+
real mu; // mean log volatility
7+
real<lower=-1,upper=1> phi; // persistence of volatility
8+
real<lower=0> sigma; // white noise shock scale
9+
vector[T] h; // log volatility at time t
10+
}
11+
model {
12+
phi ~ uniform(-1,1);
13+
sigma ~ cauchy(0,5);
14+
mu ~ cauchy(0,10);
15+
h[1] ~ normal(mu, sigma / sqrt(1 - phi * phi));
16+
for (t in 2:T)
17+
h[t] ~ normal(mu + phi * (h[t - 1] - mu), sigma);
18+
for (t in 1:T)
19+
y[t] ~ normal(0, exp(h[t] / 2));
20+
}

0 commit comments

Comments
 (0)