Iterated least squares

A second form of loop structure is designed primarily for carrying out iterated least squares. Greene (2000, ch. 11) shows how this method can be used to estimate nonlinear models.

To open this sort of loop you need to specify a condition rather than an unconditional number of times to iterate. This should take the form of the keyword while followed by an inequality: the left-hand term should be the name of a variable that is already defined; the right-hand side may be either a numerical constant or the name of another predefined variable. For example,

loop while essdiff > .00001

Execution of the commands within the loop (i.e. until endloop is encountered) will continue so long as the specified condition evaluates as true.

I assume that if you specify a "number of times" loop you are probably doing a Monte Carlo analysis, and hence you're not interested in the results from each individual iteration but rather the moments of certain variables over the ensemble of iterations. On the other hand, if you specify a "while" loop you're probably doing something like iterated least squares, and so you'd like to see the final result — as well, perhaps, as the value of some variable(s) (e.g. the error sum of squares from a regression) from each time round the loop. The behavior of the print and ols commands are tailored to this assumption. In a "while" loop print behaves as usual; thus you get a printout of the specified variable(s) from each iteration. The ols command prints out the results from the final estimation.

Example 7-2 uses a "while" loop to replicate the estimation of a nonlinear consumption function of the form as presented in Greene (2000, Example 11.3). This script is included in the gretl distribution under the name greene11_3.inp; you can find it in gretl under the menu item "File, Open command file, practice file, Greene...".

Example 7-2. Nonlinear consumption function


	  open greene11_3.gdt 
	  (* run initial OLS *) 
	  ols C 0 Y 
	  genr essbak = $ess 
	  genr essdiff = 1
	  genr b0 = coeff(Y) 
	  genr gamma0 = 1 
	  (* form the linearized variables *) 
	  genr C0 = C + gamma0 * b0 * Y^gamma0 * log(Y) 
	  genr x1 = Y^gamma0 
	  genr x2 = b0 * Y^gamma0 * log(Y) 
	  (* iterate OLS till the error sum of squares converges *) 
	  loop while essdiff > .00001 
	    ols C0 0 x1 x2 -o 
	    genr b0 = coeff(x1) 
	    genr gamma0 = coeff(x2) 
	    genr C0 = C + gamma0 * b0 * Y^gamma0 * log(Y) 
	    genr x1 = Y^gamma0 genr x2 = b0 * Y^gamma0 * log(Y) 
	    genr ess = $ess genr
	    essdiff = abs(ess - essbak)/essbak 
	    genr essbak = ess 
	  endloop 
	  (* print parameter estimates using their "proper names" *) 
	  genr alpha = coeff(0) 
	  genr beta = coeff(x1) 
	  genr gamma = coeff(x2)
	  print alpha beta gamma