Debian Codegraph @

tests/estimation/univariate/bayesian_param_names.mod

raw
1 // --+ options: json=compute +--
2 // https://www3.nd.edu/~rwilliam/stats1/OLS-Stata9.pdf
3
4 var income educ jobexp race;
5
6 varexo e;
7
8 parameters b1, b2, b3, b4;
9
10 b1 = 0.1;
11 b4 = 0.2;
12
13 model;
14
15 // The following three lines are required because the variables are declared as endogenous, but the equations
16 // have no consequences on the estimation of the last equation in the block.
17 educ = educ;
18 jobexp = jobexp;
19 race = race;
20
21 [name='eqols']
22 income = b1 + b2*educ + b3*jobexp + b4*race + e;
23
24 end;
25
26 // Load data.
27 ds = dseries('data.csv');
28
29 // Estimate last equatioon by OLS (ds is updated with the fitted values).
30 ds = dyn_ols(ds, {}, {'eqols'}, {'ols_eq'}, {{'b2'; 'b3'}});
31
32 /*
33 ** BAYESIAN ESTIMATION OF 'eqols'
34 */
35
36 // Set the number of estimated parameters.
37 n = length(oo_.ols.ols_eq.beta);
38
39 // We consider a kind of non informative prior by assuming that the inverse of the prior variance for β is zero.
40 V0 = diag(Inf(n, 1));
41
42 // We choose the prior mean for β randomly (around the OLS estimate).
43 beta0 = oo_.ols.ols_eq.beta + randn(n, 1);
44
45 // Set prior for the variance of the error
46 s2priormean = 17;
47 s2df = 1;
48
49 // Run bayesian estimation with normal-gamma prior. Because there is no closed
50 // form expression for the joint posterior marginal distribution of β, a Gibbs
51 // sampling algorithm is used (the prior for β and the inverse of σ² are independent).
52
53 gibbslength = 100000; // Set the number of iterations in Gibbs
54 burnin = 10000; // Set the number of iterations to be discarded (try to remove the effects of the initial condition).
55 steps = 10; // Do not record all iterations (try to remove the dependence between the draws).
56
57 ds = olsgibbs(ds, 'eqols', beta0, V0, s2priormean, s2df, gibbslength, burnin, steps, {'eqols', 'eqols_olsgibbs_fit'}, 'olsgibbs_eq',{'b2'; 'b3'});
58
59 // Since we use a diffuse prior for β, the posterior mean of β should be close to the OLS estimate.
60 if max(abs(oo_.ols.ols_eq.beta-oo_.olsgibbs.olsgibbs_eq.posterior.mean.beta))>.01
61 error('Something is wrong in the Gibbs sampling routine (univariate model)')
62 end
63
64 // We can plot the posterior distribution of the parameters:
65 post = oo_.olsgibbs.olsgibbs_eq.posterior.density.b2;
66 plot(post(:,1), post(:,2), '-k', 'linewidth', 2);
67 axis tight
68 box on
69 hold on
70 plot([oo_.olsgibbs.olsgibbs_eq.posterior.mean.beta(2), oo_.olsgibbs.olsgibbs_eq.posterior.mean.beta(2)], [0 max(post(:,2))], '-r')
71 hold off