'basic stochastic volatility model
'QML estimation by state space
'12/14/2000 h.

create u 1 1000

'get data
%datafile = @runpath + "svpdx.dat"
read(skiprow=1) "{%datafile}" rt

'estimate GARCH(1,1) model
equation eq1.arch(1,1,m=500,c=1e-5,showopts) rt c
show eq1.output
'and get conditional variance series 
smpl 946 1000
eq1.forecast rhat rhat_se gt

smpl @all
'transformation for QML estimation
series y = log(rt*rt)

'variance of log chi-square distribution
!pi = @acos(-1)
scalar s2 = 0.5*!pi*!pi

'specify quasi-likelihood state-space
sspace sv
sv.append @signal y = -1.27 + ht + [var=s2]
sv.append @state ht = c(1) + c(2)*ht(-1) + [var=exp(c(3))]

'set starting values
c(1) = 0.01
c(2) = 0.9
c(3) = 0.1

'estimate
show sv.ml(showopts,m=500,c=1e-7)

'and retrieve state series
sv.makestate(t=pred) hf
sv.makestate(t=predse) hf_se
sv.makestate(t=filt) ht
sv.makestate(t=filtse) ht_se
sv.makestate(t=smooth) hs
sv.makestate(t=smoothse) hs_se

'plot to compare log variance from GARCH and stochastic volatility
graph graph1.line log(gt) hf hs
graph1.options size(8,2)
graph1.addtext(0.1,-0.3) Log volatility
graph1.setelem(1) legend(GARCH(1,1))
graph1.setelem(2) legend(One-step ahead)
graph1.setelem(3) legend(Smoothed)
graph1.legend columns(1) position(0,0)
show graph1

