Skip to content

Commit 5853344

Browse files
committed
Merge pull request #963 from springcoil/garch
Add Garch model
2 parents 55dd7bb + 04c980c commit 5853344

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

pymc3/examples/garch_example.py

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
from pymc3 import Normal, sample, Model, Bound
2+
import theano.tensor as tt
3+
import numpy as np
4+
import math
5+
"""
6+
Example from STAN
7+
// GARCH(1,1)
8+
9+
data {
10+
int<lower=0> T;
11+
real r[T];
12+
real<lower=0> sigma1;
13+
}
14+
parameters {
15+
real mu;
16+
real<lower=0> alpha0;
17+
real<lower=0,upper=1> alpha1;
18+
real<lower=0, upper=(1-alpha1)> beta1;
19+
}
20+
transformed parameters {
21+
real<lower=0> sigma[T];
22+
sigma[1] <- sigma1;
23+
for (t in 2:T)
24+
sigma[t] <- sqrt(alpha0
25+
+ alpha1 * pow(r[t-1] - mu, 2)
26+
+ beta1 * pow(sigma[t-1], 2));
27+
}
28+
model {
29+
r ~ normal(mu,sigma);
30+
}
31+
"""
32+
T = 8
33+
r = np.array([28, 8, -3, 7, -1, 1, 18, 12])
34+
sigma1 = np.array([15, 10, 16, 11, 9, 11, 10, 18])
35+
alpha0 = np.array([10, 10, 16, 8, 9, 11, 12, 18])
36+
37+
with Model() as garch:
38+
39+
alpha1 = Normal('alpha1', 0, 1, shape=T)
40+
BoundedNormal = Bound(Normal, upper=(1-alpha1))
41+
beta1 = BoundedNormal('beta1', 0, sd=1e6)
42+
mu = Normal('mu', 0, sd=1e6)
43+
44+
theta = tt.sqrt(alpha0 + alpha1*tt.pow(r - mu, 2) + beta1 * tt.pow(sigma1, 2))
45+
46+
obs = Normal('obs', mu, sd=theta, observed=r)
47+
48+
def run(n=1000):
49+
if n == "short":
50+
n = 50
51+
with garch:
52+
tr = sample(n)
53+
54+
if __name__ == '__main__':
55+
run()

0 commit comments

Comments
 (0)