我试图用r中的潜在变量估计状态空间模型,但失败了。 我试图用rstan包来做。 有人知道如何做得更好吗?
假设我们有两个可观察的变量:gdp和通货膨胀。 我们还知道存在三个不可观察的变量:潜在增长,潜在gdp,产出缺口。 我们想要估计不可观察的变量和两个系数(a1和a2)。
我们的模型:
状态方程式:
测量方程:
此处生成了数据:
RequestBody body = RequestBody.create(MediaType.APPLICATION_JSON, pbody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
这是我的rstan代码:
a1 <- 0.7
a2 <- 0.3
grow <- c()
potential <- c()
gap <- c()
gdp <- c()
inflation <- c()
grow[1] <- 2
potential[1] <- 10
gap[1] <- 0
gdp[1] <- potential[1] + gap[1]/100
inflation[1] <- 2
for (i in 2:100) {
grow[i] <- grow[i-1] + rnorm(1, 0, 0.1)
potential[i] <- potential[i-1] + grow[i]/100 + rnorm(1, 0, 0.1)
gap[i] <- a1*gap[i-1] + rnorm(1,0,0.1)
gdp[i] <- potential[i] + gap[i]/100
inflation[i] <- inflation[i-1] + a2*gap[i] + rnorm(1,0,0.1)
}
我在这里尝试过模型
data {
int T; // number of obs
int P; //number of variables
matrix[T,P] Y; //dataset of generated series
}
parameters {
#Coefficients
vector[1] alfa1; //ar gap
vector[1] alfa2; //phillips curve
#State Variables (unobserved economic variables)
vector[T] gap; // output gap
vector[T] potential; // potential output
vector[T] grow; // growth of potential output
#Innovations
real<lower = 0> sigma_pot; // The scale of innovations to potential output
real<lower = 0> sigma_grow; // The scale of innovations to growth in potential output
real<lower = 0> sigma_gap; // The scale of innovations to output gap
real<lower = 0> sigma_inf; // The scale of innovations to phillips curve
}
model {
// priors
//Innovations
sigma_pot ~ cauchy(0.2,3);
sigma_grow ~ cauchy(0.3,3);
sigma_gap ~ cauchy(0.9,5);
sigma_inf ~ cauchy(2,5);
//coefficients
alfa1 ~ normal(0,1);
alfa2 ~ normal(0,1);
//Initialize State Equations
potential[1] ~ normal(0,1);
grow[1] ~ normal(0,1);
gap[1] ~ normal(0,1);
// State Equations
for(t in 2:T) {
grow[t] ~ normal(grow[t-1], sigma_grow);
potential[t] ~ normal(potential[t-1] + grow[t], sigma_pot);
gap[t] ~ normal( alfa1*gap[t-1], sigma_gap);
}
// Measurement Equations
for(t in 1:T) {
Y[t,1] = potential[t] + gap[t];
Y[t,2] ~ normal(Y[t-1,2] + alfa1*gap[t],sigma_inf);
}
}
这是我遇到的错误
mvf_model <- stan(file = "newstan.stan" ,
data = list(T = nrow(data),
P = ncol(data),
Y = data),
chains = 4)