Gretl Manual: Gnu Regression, Econometrics and Time-series Library | ||
---|---|---|
Prev | Chapter 10. Command Reference | Next |
Must be invoked after an estimation command. The variables in varlist are added to the previous model and the new model estimated. If more than one variable is added, the F statistic for the added variables will be printed (for the OLS procedure only) along with its p-value. A p-value below 0.05 means that the coefficients are jointly significant at the 5 percent level. A number of internal variables may be retrieved using the genr command, provided genr is invoked directly after this command. The -o flag causes the coefficient variance–covariance matrix to be printed.
Works like the add command, except that you specify a previous model (using its ID number, which is printed at the start of the model output) to take as the base for adding variables. The example above adds variables number 5, 7 and 9 to Model 2.
Computes statistics for two Dickey–Fuller tests. In each case the null hypothesis is that the variable in question exhibits a unit root. The first is a t-test based on the model
The null hypothesis is that g = 0. The second (augmented) test proceeds by estimating an unrestricted regression (with regressors a constant, a time trend, the first lag of the variable, and order lags of the first difference) and a restricted version (dropping the time trend and the first lag). The test statistic is where T is the sample size, k the number of parameters in the unrestricted model, and the subscripts u and r denote the unrestricted and restricted models respectively. Note that the critical values for these statistics are not the usual ones; a p-value range is printed, when it can be determined.Computes parameter estimates using the generalized Cochrane–Orcutt iterative procedure (see Section 9.5 of Ramanathan). Iteration is terminated when successive error sums of squares do not differ by more than 0.005 percent or after 20 iterations. lags is a list of lags in the residuals, terminated by a semicolon. In the above example, the error term is specified as
depvar is the dependent variable and indepvars is the list of independent variables. If the -o flag is given, the covariance matrix of regression coefficients is printed. Residuals of the transformed regression are stored under the name uhat, which can be retrieved by genr. A number of other internal variables may be retrieved using the genr command, provided genr is invoked after this command.Tests the model for ARCH (Autoregressive Conditional Heteroskedasticity) of the lag order specified in order, which must be an integer. If the LM test statistic has p-value below 0.10, then ARCH estimation is also carried out. If the predicted variance of any observation in the auxiliary regression is not positive, then the corresponding squared residual is used instead. Weighted least square estimation is then performed on the original model. The flag -o calls for the coefficient covariance matrix.
Must follow an OLS regression. Creates a dummy variable which equals 1 from the split point specified by obs to the end of the sample, 0 otherwise, and also creates interaction terms between this dummy and the original independent variables. An augmented regression is run including these terms and an F statistic is calculated, taking the augmented regression as the unrestricted and the original as restricted. This statistic is appropriate for testing the null hypothesis of no structural break at the given split point.
Must follow an regression. Calculates the sum of the coefficients on the variables in the indepvars list. Prints this sum along with its standard error and the p-value for the null hypothesis that the sum is zero.
Carries out Augmented Dickey–Fuller tests on the null hypothesis that each of the variables listed has a unit root, using the given lag order. The cointegrating regression is estimated, and an ADF test is run on the residuals from this regression. The Durbin–Watson statistic for the cointegrating regression is also given. Note that none of these test statistics can be referred to the usual statistical tables.
Carries out the Johansen trace test for cointegration among the listed variables for the given order. For details of this test see Hamilton (1994, Chapter 19). If the -o flag is given the results of the various auxiliary regressions are printed.
Arguments: | depvar indepvars [ -o ] |
Examples: | corc 1 0 2 4 6 7 |
corc -o 1 0 2 4 6 7 | |
corc y 0 x1 x2 x3 | |
corc -o y 0 x1 x2 x3 |
Computes parameter estimates using the Cochrane–Orcutt iterative procedure (see Section 9.4 of Ramanathan) with depvar as the dependent variable and indepvars as the list of independent variables. Iteration is terminated when successive estimates of the autocorrelation coefficient do not differ by more than 0.001 or after 20 iterations. If the -o flag is given, the covariance matrix of regression coefficients is printed. Residuals of this transformed regression are stored under the name uhat. Various internal variables may be retrieved using the genr command, provided genr is invoked immediately after this command.
Prints the pairwise correlation coefficients for the variables in varlist, or for all variables in the data set if varlist is not given.
Prints the values of the autocorrelation function for the
variable specified (either by name
or number). See Ramanathan, Section 11.7. It is thus
where
ut
is the tth observation of the variable
u and s is the
number of lags.
The partial autocorrelations are also shown: these are net of the effects of intervening lags. The command also graphs the correlogram and prints the Box-Pierce Q statistic for testing the null hypothesis that the series is "white noise". This is asymptotically distributed as chi-square with degrees of freedom equal to the number of lags used.
If an (optional) integer maxlag value is supplied the length of the correlogram is limited to at most that number of lags, otherwise the length is determined automatically.
Computes the model selection statistics (see Ramanathan, Section 4.3), given ess (error sum of squares), the number of observations (T), and the number of coefficients (k). T, k, and ess may be numerical values or names of previously defined variables.
If dist is t, X or F, prints out the critical values for the student's t, chi-square or F distribution respectively, for the common significance levels and using the specified degrees of freedom, given as param1 for t and chi-square, or param1 and param2 for F. If dist is d, prints the upper and lower values of the Durbin-Watson statistic at 5 percent significance, for the given number of observations, param1, and for the range of 1 to 5 explanatory variables.
Must follow the estimation of a model via OLS. Performs the CUSUM test for parameter stability. A series of (scaled) one-step ahead forecast errors is obtained by running a series of regressions: the first regression uses the first k observations and is used to generate a prediction of the dependent variable at observation at observation k + 1; the second uses the first k + 1 observations and generates a prediction for observation k + 2, and so on (where k is the number of parameters in the original model). The cumulated sum of the scaled forecast errors is printed and graphed. The null hypothesis of parameter stability is rejected at the 5 percent significance level if the cumulated sum strays outside of the 95 percent confidence band.
The Harvey–Collier t-statistic for testing the null hypothesis of parameter stability is also printed. See Chapter 7 of Greene's Econometric Analysis for details.
Reads the variables in varlist from a database (gretl or RATS 4.0), which must have been opened previously using the open command. In addition, a data frequency and sample range must be established using the the setobs and smpl commands prior to using this command. Here is a full example:
open macrodat.rat setobs 4 1959:1 smpl ; 1999:4 data GDP_JP GDP_UK
These commands open a database named macrodat.rat, establish a quarterly data set starting in the first quarter of 1959 and ending in the fourth quarter of 1999, and then import the series named GDP_JP and GDP_UK.
If the series to be read are of higher frequency than the working data set, you must specify a compaction method as below:
data (compact=average) LHUR PUNEW
The four available compaction methods are "average" (takes the mean of the high frequency observations), "last" (uses the last observation), "first" and "sum".
Removes the listed variables (given by name or number) from the dataset. Use with caution: no confirmation is asked, and any variables with higher ID numbers will be re-numbered.
If no varlist is given with this command, it deletes the last (highest numbered) variable from the dataset.
The first difference of each variable in varlist is obtained and the result stored in a new variable with the prefix d_. Thus diff x y creates the new variables d_x = x(t) - x(t-1) and d_y = y(t) - y(t-1).
Specifies an equation within a system of equations (see the system command). The sytax for specifying an equation is the same as that for, e.g., the ols command.
Must follow the estimation of a model via OLS. Prints the estimated model in the form of a LaTeX equation. If a filename is specified using the -f flag output goes to that file, otherwise it goes to a file with a name of the form equation_N.tex, where N is the number of models estimated to date in the current session. See also the tabprint command.
If the -o flag is given the LaTeX file is a complete document, ready for processing; otherwise it must be included in a document.
Must follow an estimation command. Forecasts are generated for the specified range (or the largest possible range if no startobs and endobs are given) and the values saved as newvarname, which can be printed, graphed, or plotted. The right-hand side variables are those in the original model. There is no provision to substitute other variables. If an autoregressive error process is specified (for hilu, corc, and ar) the forecast is conditional one step ahead and incorporates the error process.
After estimating an OLS model which includes a constant and at least one independent variable (these restrictions may be relaxed at some point) you can use this command to print out fitted values over the specified observation range, along with the estimated standard errors of those predictions and 95 percent confidence intervals. If the -o flag is given the results will also be displayed using gnuplot. The augmented regression method of Salkever (1976) is used to generate the forecast standard errors.
The fit command (must follow an estimation command) is a shortcut for the fcast command. It generates fitted values, in a series called autofit, for the current sample, based on the last regression. In the case of time-series models, fit also pops up a gnuplot graph of fitted and actual values of the dependent variable against time.
Prints the frequency distribution for var (given by name or number) along with a chi-square test for normality. In interactive mode a gnuplot graph of the distribution is displayed.
Creates new variables, usually through transformations of existing variables. See also diff, logs, lags, ldiff, multiply and square for shortcuts.
Supported arithmetical operators are, in order of precedence: ^ (exponentiation); *, / and % (modulus or remainder); + and -.
The available Boolean operators are (again, in order of precedence): ! (negation), & (logical AND), | (logical OR), >, <, =, >= (greater than or equal), <= (less than or equal) and != (not equal). The Boolean operators can be used in constructing dummy variables: for instance (x > 10) returns 1 if x > 10, 0 otherwise. Supported functions fall into these groups:
Standard math functions: abs, cos, exp, int (integer part), ln (natural log: log is a synonym), sin, sqrt.
Statistical functions: max (maximum value in a series), min (minimum), mean (arithmetic mean), median, var (variance) sd (standard deviation), sst (sum of squared deviations from the mean), sum, cov (covariance), corr (correlation coefficient), pvalue
Time-series functions: diff (first difference), ldiff (log-difference, or first difference of natural logs). To generate lags of a variable x, use the syntax x(-N), where N represents the desired lag length; to generate leads, use x(+N);
Miscellaneous: cum (cumulate), sort, uniform, normal, misszero (replace the missing observation code in a given series with zeros), zeromiss (the inverse operation to misszero), nobs (return the number of valid observations in a given data series).
All of the above functions with the exception of cov, corr, pvalue, uniform and normal take as their single argument either the name of a variable (note that you can't refer to variables by their ID numbers in a genr command) or a composite expression that evaluates to a variable (e.g. ln((x1+x2)/2)). cov and corr both require two arguments, and return respectively the covariance and the correlation coefficient between two named variables. The pvalue function takes the same arguments as the pvalue command (see below), but in this context commas should be placed between the arguments. uniform() and normal(), which do not take arguments, return pseudo-random series drawn from the uniform (0–1) and standard normal distributions respectively (see also the seed command). Uniform series are generated using the C library function rand(); for normal series the method of Box and Muller (1958) is used.
Besides the operators and functions just noted there are some special uses of genr:
genr time creates a time trend variable (1,2,3,…) called time. genr index does the same thing except that the variable is called index.
genr dummy creates dummy variables up to the periodicity of the data. E.g. in the case of quarterly data (periodicity 4), the program creates dummy_1 = 1 for first quarter and 0 in other quarters, dummy_2 = 1 for the second quarter and 0 in other quarters, and so on.
genr paneldum creates a set of special dummy variables for use with a panel data set — see Chapter 5 above.
Various internal variables defined in the course of running a regression can be retrieved using genr, as follows:
$ess | error sum of squares |
$rsq | unadjusted R-squared |
$T | number of observations used |
$df | degrees of freedom |
$trsq | TR-squared (sample size times R-squared) |
$sigma | standard error of residuals |
$lnl | log-likelihood (logit and probit models) |
$sigma | standard error of residuals |
coeff(var) | estimated coefficient for variable var |
stderr(var) | estimated standard error for variable var |
rho(i) | ith order autoregressive coefficient for residuals |
vcv(var1,var2) | covariance between coefficients for named variables var1 and var2 |
Note: In the command-line program, genr commands that retrieve model-related data always reference the model that was estimated most recently. This is also true in the GUI program, if one uses genr in the "gretl console" or enters a formula using the "Define new variable" option under the Variable menu in the main window. With the GUI, however, you have the option of retrieving data from any model currently displayed in a window (whether or not it's the most recent model). You do this under the "Model data" menu in the model's window.
The internal series uhat and yhat hold, respectively, the residuals and fitted values from the last regression.
Three other "internal" variables are available: $nobs holds the number of observations in the current sample range (note that this may or may not equal the value of $T, the number of observations used in estimating the last model). The variable t serves as an index of the observations. Thus for instance genr dum = (t=15) will generate a dummy variable that has value 1 for observation 15, 0 otherwise. The variable $pd holds the frequency or periodicity of the data (e.g. 4 for quarterly data).
Table 10-1 gives several examples of uses of genr with explanatory notes; here are a couple of tips on dummy variables:
Suppose x is coded with values 1, 2, or 3 and you want three dummy variables, d1 = 1 if x = 1, 0 otherwise, d2 = 1 if x = 2, and so on. To create these, use the commands:
genr d1 = (x=1) genr d2 = (x=2) genr d3 = (x=3)
To create z = max(x,y) do
genr d = x>y genr z = (x*d)+(y*(1-d))
Table 10-1. Examples of use of genr command
Command | Comment |
---|---|
genr y = x1^3 | x1 cubed |
genr y = ln((x1+x2)/x3) | |
genr z = x>y | sets z(t) to 1 if x(t) > y(t) else to 0 |
genr y = x(-2) | x lagged 2 periods |
genr y = x(2) | x led 2 periods |
genr y = diff(x) | y(t) = x(t) - x(t-1) |
genr y = ldiff(x) | y(t) = log x(t) - log x(t-1), the instantaneous rate of growth of x |
genr y = sort(x) | sorts x in increasing order and stores in y |
genr y = -sort(-x) | sort x in decreasing order |
genr y = int(x) | truncate x and store its integer value as y |
genr y = abs(x) | store the absolute values of x |
genr y = sum(x) | sum x values excluding missing −999 entries |
genr y = cum(x) | cumulation:
![]() |
genr aa = $ess | set aa equal to the Error Sum of Squares from last regression |
genr x = coeff(sqft) | grab the estimated coefficient on the variable sqft from the last regression |
genr rho4 = rho(4) | grab the 4th-order autoregressive coefficient from the last model (presumes an ar model) |
genr cvx1x2 = vcv(x1, x2) | grab the estimated coefficient covariance of vars x1 and x2 from the last model |
genr foo = uniform() | uniform pseudo-random variable in range 0–1 |
genr bar = 3 * normal() | normal pseudo-random variable, μ = 0, σ = 3 |
Arguments: | yvars xvar [ -o | -m ] |
Addendum: | { literal gnuplot commands } |
Alternate form: | -z yvar xvar dummy |
In the first case the yvars are graphed against xvar. If the flag -o is supplied the plot will use lines; if the flag -m is given the plot uses impulses (vertical lines); otherwise points will be used.
In the "alternate form" (with -z) yvar is graphed against xvar with the points shown in different colors depending on whether the value of dummy is 1 or 0.
To make a time-series graph, do gnuplot yvars time. If no variable named time already exists, then it will be generated automatically. Special dummy variables will be created for plotting quarterly and monthly data.
In interactive mode the result is piped to gnuplot for display. In batch mode a plot file named gpttmp01.plt is written. (With subsequent uses of gnuplot similar files are created, with the number in the file name incremented.) The plots can be generated later using the command gnuplot gpttmp.plt. (Under MS Windows, start wgnuplot and open the file gpttmp01.plt.)
A further option to this command is available: following the specification of the variables to be plotted and the option flag (if any), you may add literal gnuplot commands to control the appearance of the plot (for example, setting the plot title and/or the axis ranges). These commands should be enclosed in braces, and each gnuplot command must be terminated with a semi-colon. A backslash may be used to continue a set of gnuplot commands over more than one line. Here is an example of the syntax:
{ set title 'My Title'; set yrange [0:1000]; }
ASCII graphics. The yvars (which may be given by name or number) are graphed against xvar using ASCII symbols. The -o flag will graph with 40 rows and 60 columns. Without it, the graph will be 20 by 60 (for screen output). See also the gnuplot command.
This test is available only after estimating a model using the pooled command (see also panel and setobs). It tests the simple pooled model against the principal alternatives, the fixed effects and random effects models.
The fixed effects model adds a dummy variable for all but one of the cross-sectional units, allowing the intercept of the regression to vary across the units. An F-test for the joint significance of these dummies is presented. The random effects model decomposes the residual variance into two parts, one part specific to the cross-sectional unit and the other specific to the particular observation. (This estimator can be computed only if the number of cross-sectional units in the data set exceeds the number of parameters to be estimated.) The Breusch–Pagan LM statistic tests the null hypothesis (that the pooled OLS estimator is adequate) against the random effects alternative.
The pooled OLS model may be rejected against both of the alternatives, fixed effects and random effects. Provided the unit- or group-specific error is uncorrelated with the independent variables, the random effects estimator is more efficient than the fixed effects estimator; otherwise the random effects estimator is inconsistent and the fixed effects estimator is to be preferred. The null hypothesis for the Hausman test is that the group-specific error is not so correlated (and therefore the random effects model is preferable). A low p-value for this test counts against the random effects model and in favor of fixed effects.
Presents OLS estimates with the heteroskedasticity consistent covariance matrix estimates for the standard errors of regression coefficients using MacKinnon and White (1985) "jackknife" estimates (see Ramanathan, Section 8.3). The coefficient covariance matrix is printed if the -o flag is given.
Gives a list of available commands. help command describes command (e.g. help smpl). You can type man instead of help if you like.
Computes parameter estimates using the Hildreth–Lu search procedure (fine tuned by the CORC procedure) with depvar as the dependent variable and indepvars as the list of independent variables. The error sum of squares of the transformed model is graphed against the value of rho from −0.99 to 0.99. If the -o flag is present, the covariance matrix of regression coefficients will be printed. Residuals of this transformed regression are stored under the name uhat.
Prints heteroskedasticity corrected estimates (see Ramanathan, ch. 8) and associated statistics. The auxiliary regression predicts the log of the square of residuals (using squares of independent variables but not their cross products) from which weighted least squares estimates are obtained. If the -o flag is given, the covariance matrix of regression coefficients is printed. Various internal variables may be retrieved using the genr command, provided genr is invoked immediately after this command.
Flow control for command execution. The syntax is
condition must be a Boolean expression, for the syntax of which see the Section called genr. The else block is optional; if … endif blocks may be nested.
Without the -o flag, brings in data from a comma-separated values (CSV) format file, such as can easily be written from a spreadsheet program. The file should have variable names on the first line and a rectangular data matrix on the remaining lines. Variables should be arranged "by observation" (one column per variable; each row represents an observation). See Chapter 4 for details.
With the -o flag, reads a data file in BOX1 format, as can be obtained using the Data Extraction Service of the US Bureau of the Census.
info prints out any information contained in the header file corresponding to the current datafile. (This information must be enclosed between (* and *), these markers being placed on separate lines.)
Sets the descriptive label for the given variable (if the -d flag is given, followed by a string in double quotes) and/or the "display name" for the variable (if the -n flag is given, followed by a quoted string). If a variable has a display name, this is used when generating graphs.
Prints out the informative labels for any variables that have been generated using genr, and any labels added to the data set via the GUI.
Calculates a regression that minimizes the sum of the absolute deviations of the observed from the fitted values of the dependent variable. Coefficient estimates are derived using the Barrodale–Roberts simplex algorithm; a warning is printed if the solution is not unique. Standard errors are derived using the bootstrap procedure with 500 drawings.
Creates new variables which are lagged values of each of the variables in varlist. The number of lagged variables equals the periodicity. For example, if the periodicity is 4 (quarterly), the command lags x y creates x_1 = x(t-1), x_2 = x(t-2), x_3 = x(t-3) and x_4 x(t-4). Similarly for y. These variables must be referred to in the exact form, that is, with the underscore.
The first difference of the natural log of each variable in
varlist is obtained and the result stored in a new variable
with the prefix ld_. Thus ldiff x
y creates the new variables
ld_x =
and ld_y =
.
Must immediately follow an ols command.
Calculates the leverage (h, which must
lie in the range 0 to 1) for each data point in the sample on
which the previous model was estimated. Displays the residual
(u) for each observation along with its
leverage and a measure of its influence on the estimates,
. "Leverage points" for which
the value of h exceeds
2k/n (where
k is the number of parameters being
estmated and n is the sample size) are
flagged with an asterisk. For details on the concepts of
leverage and influence see Davidson and MacKinnon (1993,
Chapter 2).
Must immediately follow an ols command. Prints the Lagrange Multiplier test statistics (and associated p-values) for nonlinearity and heteroskedasticity (White's test) or, if the -o flag is given, the LMF test statistic for serial correlation up to the periodicity (see Kiviet, 1986). The corresponding auxiliary regression coefficients are also printed out. See Ramanathan, Chapters 7, 8, and 9 for details. In the case of White's test, only the squared independent variables are used and not their cross products. In the case of the autocorrelation test, if the p-value of the LMF statistic is less than 0.05 then serial correlation-robust standard errors are calculated and displayed. For details on the calculation of these standard errors see Wooldridge (2002, Chapter 12).
Binomial logit regression. The dependent variable should be a binary variable. Maximum likelihood estimates of the coefficients on indepvars are obtained via the EM or Expectation–Maximization method (see Ruud, 2000, Chapter 27). As the model is nonlinear the slopes depend on the values of the independent variables: the reported slopes are evaluated at the means of those variables. The chi-square statistic tests the null hypothesis that all coefficients are zero apart from the constant.
If you want to use logit for analysis of proportions (where the dependent variable is the proportion of cases having a certain characteristic, at each observation, rather than a 1 or 0 variable indicating whether the characteristic is present or not) you should not use the logit command, but rather construct the logit variable (e.g. genr lgt_p = log(p/(1 - p))) and use this as the dependent variable in an OLS regression. See Ramanathan, Chapter 12.
The natural log of each of the variables in varlist is obtained and the result stored in a new variable with the prefix l_ which is "el" underscore. logs x y creates the new variables l_x = ln(x) and l_y = ln(y).
Usage: | loop number_of_times |
loop while condition | |
loop for i= start.. end | |
Examples: | loop 1000 |
loop while essdiff > .00001 | |
loop for i=1991..2000 |
Opens a special mode in which the program accepts commands to be repeated either a specified number of times, or so long as a specified condition holds true, or for successive integer values of the (internal) index variable i. Within a loop, only 7 commands can be used: genr, ols, print, sim, smpl, store and summary (store can't be used in a "while" loop). You exit the mode of entering loop commands with endloop: at this point the stacked commands are executed. Loops cannot be nested. See Chapter 8 for details.
Calculates the t statistic for the null hypothesis that the population means are equal for the variables var1 and var2, and shows its p-value. Without the -o flag, the statistic is computed on the assumption that the variances are equal for the two variables; with the -o flag the variances are assumed to be unequal. (The flag will make a difference only if there are different numbers of non-missing observations for the two variables.)
Computes OLS estimates with depvar as the dependent variable and indepvars as the list of independent variables, using multiple precision floating-point arithmetic. The variables may be specified by name or number; use the number zero for a constant term. This command is available only if gretl is compiled with support for the Gnu Multiple Precision library (GMP).
To estimate a polynomial fit, using multiple precision arithmetic to generate the required powers of the independent variable, use the form, e.g. mpols y 0 x ; 2 3 4 This does a regression of y on x, x squared, x cubed and x to the fourth power. That is, the numbers (which must be positive integers) to the right of the semicolon specify the powers of x to be used. If more than one independent variable is specified, the last variable before the semicolon is taken to be the one that should be raised to various powers.
The variables in varlist (referenced by name or number) are multiplied by x, which may be either a numerical value or the name of a variable already defined. The products are named with the specified suffix (maximum 3 characters). The original variable names are truncated first if need be. For instance, suppose you want to create per capita versions of certain variables, and you have the variable pop (population). A suitable set of commands is then: genr invpop = 1/pop multiply invpop pc income expend which will create incomepc as the product of income and invpop, and expendpc as expend times invpop.
Performs Nonlinear Least Squares (NLS) estimation using a modified version of the Levenberg–Marquandt algorithm. The user must supply a function specification. The parameters of this function must be declared and given starting values (using the genr command) prior to estimation. Optionally, the user may specify the derivatives of the regression function with respect to each of the parameters; if analytical derivatives are not supplied, a numerical approximation to the Jacobian is computed.
It is easiest to show what is required by example. The following is a complete script to estimate the nonlinear consumption function set out in William Greene's Econometric Analysis, in chapter 11 of the 4th edition, or chapter 9 of the 5th. (The numbers to the left of the lines are for reference and are not part of the commands.)
1 open greene11_3.gdt 2 ols C 0 Y 3 genr alpha = coeff(0) 4 genr beta = coeff(Y) 5 genr gamma = 1.0 6 nls C = alpha + beta * Y^gamma 7 deriv alpha = 1 8 deriv beta = Y^gamma 9 deriv gamma = beta * Y^gamma * log(Y) 10 end nls
It is often convenient to initialize the parameters by reference to a related linear model; that is accomplished here on lines 2 to 5. The parameters alpha, beta and gamma could be set to any initial values (not necessarily based on a model estimated with OLS), although convergence of the NLS procedure is not guaranteed for an arbitrary starting point.
The actual NLS commands occupy lines 6 to 10. On line 6 the nls command is given: a dependent variable is specified, followed by an equals sign, followed by a function specification. The syntax for the expression on the right is the same as that for the genr command. The next three lines specify the derivatives of the regression function with respect to each of the parameters in turn. Each line begins with the keyword deriv, gives the name of a parameter, an equals sign, and an expression whereby the derivative can be calculated (again, the syntax here is the same as for genr). These deriv lines are optional, but it is recommended that you supply them if possible. Line 10, end nls, completes the command and calls for estimation.
For further details on NLS estimation please see Chapter 7.
Suppresses the echoing of commands and comments (other than those inserted using the print command) when executing a command script.
Establishes a "blank" data set, containing only a constant, with periodicity 1 and the specified number of observations. This may be used for simulation purposes: some of the genr commands (e.g. genr uniform(), genr normal(), genr time) will generate dummy data from scratch to fill out the data set. This command may be useful in conjunction with loop. See also the seed command.
Arguments: | depvar indepvars [ -o | -q ] |
Examples: | ols 1 0 2 4 6 7 |
ols -o y 0 x1 x2 x3 | |
ols -q y 0 x1 x2 x3 |
Computes ordinary least squares (OLS) estimates with depvar as the dependent variable and indepvars as the list of independent variables. The -o flag calls for printing of the covariance matrix of regression coefficients in addition to the various statistics that are printed by default. The -q flag suppresses the printing of output.
Variables may be specified by name or number; use the number zero for a constant term. The program also prints the p-values for t (two-tailed) and F-statistics. A p-value below 0.01 indicates significance at the 1 percent level and is denoted by ***. ** indicates significance between 1 and 5 percent and * indicates significance between 5 and 10 percent levels. Model selection statistics (described in Ramanathan, Section 4.3) are also printed. Various internal variables may be retrieved using the genr command, provided genr is invoked immediately after this command.
This command must be invoked after an estimation command. The variables in varlist are omitted from the previous model and the new model estimated. If more than one variable is omitted, the Wald F-statistic for the omitted variables will be printed along with its p-value (for the OLS procedure only). A p-value below 0.05 means that the coefficients are jointly significant at the 5 percent level. Various internal variables may be retrieved using the genr command, provided genr is invoked immediately after this command. The coefficient covariance matrix is printed if the -o flag is given.
Works like the omit command, except that you specify a previous model (using its ID number, which is printed at the start of the model output) to take as the base for omitting variables. The example above omits variables number 5, 7 and 9 from Model 2.
Opens a data file. If a data file is already open, it is replaced by the newly opened one. The program will try to detect the format of the data file (native, CSV or BOX1).
This command can also be used to open a database (gretl or RATS 4.0) for reading, in which case it should be followed by the data command to extract particular series from the database.
Divert output to filename, until further notice. Use the flag -a to append output to an existing file, or -w to start a new file (or overwrite an existing one). Only one file can be opened in this way at any given time.
The -c flag is used to close an output file that was previously opened as above. Output will then revert to the default stream.
In the example above, the results of one regression are written to the file regress.txt, which is then closed.
Rudimentary Principal Components Analysis. Prints the eigenvalues of the correlation matrix for the variables in varlist along with the proportion of the joint variance accounted for by each component. Also prints the corresponding eigenvectors ("component loadings").
If the -o flag is given, components with eigenvalues greater than 1.0 are saved to the dataset as variables, with names PC1, PC2 and so on. These artificial variables are formed as the sum of (component loading) times (standardized Xi), where Xi denotes the ith variable in varlist.
If the -a flag is given, all of the components are saved as described above.
Request that the current data set be interpreted as a panel (pooled cross section and time series). With no flag, or with the -s flag, the data set is taken to be in the form of stacked time series (successive blocks of data contain time series for each cross-sectional unit). With the -c flag, the data set is read as stacked cross-sections (successive blocks contain cross sections for each time period). See also the Section called setobs.
Computes and displays (and if not in batch mode, graphs) the spectrum of the specified variable. Without the -o flag the sample periodogram is given; with the flag a Bartlett lag window of length 2 root T (where T is the sample size) is used in estimating the spectrum (see Chapter 18 of Greene's Econometric Analysis). When the sample periodogram is printed, a t-test for fractional integration of the series ("long memory") is also given: the null hypothesis is that the integration order is zero.
Plots data values for specified variables, for the range of observations currently in effect, using ASCII symbols. Each line stands for an observation and the values are plotted horizontally. If the flag -o is present, x1 and x2 are plotted in the same scale, otherwise x1 and x2 are scaled appropriately. The -o flag should be used only if the variables have approximately the same range of values (e.g. observed and predicted dependent variable). See also gnuplot.
Estimates a model via OLS (see ols for details on syntax), and flags it as a pooled or panel model, so that the hausman test item becomes available.
If varlist is given, prints the values of the specified variables; if no list is given, prints the values of all variables in the current data file. If the -o flag is given the data are printed by observation, otherwise they are printed by variable. If the -t flag is given the data are printed by variable to 10 significant digits.
If the argument to print is a literal string (which must start with a double-quote, "), the string is printed as is.
Prints scalar values under the control of a format string (providing a small subset of the printf() statement in the C programming language). Recognized formats are %g and %f, in each case with the various modifiers available in C. Examples: the format %.10g prints a value to 10 significant figures; %12.6f prints a value to 6 decimal places, with a width of 12 characters.
The format string itself must be enclosed in double quotes. The values to be printed must follow the format string, separated by commas. These values should take the form of either (a) the names of variables in the dataset, or (b) expressions that are valid for the genr command. The following example prints the values of two variables plus that of a calculated expression:
ols 1 0 2 3 genr b = coeff(2) genr se_b = stderr(2) printf "b = %.8g, standard error %.8g, t = %.4f\n", b, se_b, b/se_b
The maximum length of a format string is 127 characters. The escape sequences \n (newline), \t (tab), \v (vertical tab) and \\ (literal backslash) are recognized. To print a literal percent sign, use %%.
Probit regression. The dependent variable should be a binary variable. Maximum likelihood estimates of the coefficients on indepvars are obtained via iterated least squares (the EM or Expectation–Maximization method). As the model is nonlinear the slopes depend on the values of the independent variables: the reported slopes are evaluated at the means of those variables. The chi-square statistic tests the null hypothesis that all coefficients are zero apart from the constant.
Probit for analysis of proportions is not implemented in gretl at this point.
Usage: | |
pvalue 1 xvalue (normal distribution) | |
pvalue 2 df xvalue (t distribution) | |
pvalue 3 df xvalue (chi-square distribution) | |
pvalue 4 dfn dfd xvalue (F distribution) | |
pvalue 5 mean variance xvalue (Gamma distribution) |
Computes the area to the right of xvalue in the specified distribution. df is the degrees of freedom, dfn is the d.f. for the numerator, dfd is the d.f. for the denominator. Instead of the code numbers you can use z, t, X, F and G for the normal, t, chi-square, F, and gamma distributions respectively.
Exits from the program, giving you the option of saving the output from the session on the way out.
Changes the name of the variable with identification number varnumber to newname. The varnumber must be between 1 and the number of variables in the dataset. The new name must be of 8 characters maximum, must start with a letter, and must be composed of only letters, digits, and the underscore character.
Must immediately follow the estimation of a model via OLS. Carries out Ramsey's RESET test for model specification (non-linearity) by adding the square and the cube of the fitted values to the regression and calculating the F statistic for the null hypothesis that the parameters on the two added terms are zero.
Creates rho-differenced counterparts of the variables (given by number or by name) in varlist and adds them to the data set, using the suffix # for the new variables. Given variable v1 in varlist, and entries r1 and r2 in rholist, v1# = v1(t) - r1*v1(t-1) - r2*v1(t-2) is created. The rholist entries can be given as numerical values or as the names of variables previously defined.
Range–mean plot: this command creates a simple graph to help in deciding whether a time series, y(t), has constant variance or not. We take the full sample t=1,...,T and divide it into small subsamples of arbitrary size k. The first subsample is formed by y(1),...,y(k), the second is y(k+1), ..., y(2k), and so on. For each subsample we calculate the sample mean and range (= maximum minus minimum), and we construct a graph with the means on the horizontal axis and the ranges on the vertical. So each subsample is represented by a point in this plane. If the variance of the series is constant we would expect the subsample range to be independent of the subsample mean; if we see the points approximate an upward-sloping line this suggests the variance of the series is increasing in its mean; and if the points approximate a downward sloping line this suggests the variance is decreasing in the mean.
Besides the graph, gretl displays the means and ranges for each subsample, along with the slope coefficient for an OLS regression of the range on the mean and the p-value for the null hypothesis that this slope is zero. If the slope coefficient is significant at the 10 percent significance level then the fitted line from the regression of range on mean is shown on the graph.
Carries out the nonparametric "runs" test for randomness of the specified variable. If you want to test for randomness of deviations from the median, for a variable named x1 with a non-zero median, you can do the following:
genr signx1 = x1 - median(x1) runs signx1
Argument: | yvar ; xvarlist |
scatters yvarlist ; xvar | |
Examples: | scatters 1 ; 2 3 4 5 |
scatters 1 2 3 4 5 6 ; time |
Plots pairwise scatters of yvar against all the variables in xvarlist, or of all the variables in yvarlist against xvar. The first example above puts variable 1 on the y-axis and draws four graphs, the first having variable 2 on the x-axis, the second variable 3 on the x-axis, and so on. The second example plots each of variables 1 through 6 against time. Scanning a set of such plots can be a useful step in exploratory data analysis. The maximum number of plots is six; any extra variable in the list will be ignored.
Sets the seed for the pseudo-random number generator for the uniform() and normal() functions (see the genr command). By default the seed is set when the program is started, using the system time. If you want to obtain repeatable sequences of pseudo-random numbers you will need to set the seed manually.
Force the program to interpret the current data set as time series or panel, when the data have been read in as simple undated series. periodicity must be an integer; startobs is a string representing the date or panel ID of the first observation. See also Chapter 5.
Get the program to interpret some specific numerical data value (the first parameter to the command) as a code for "missing", in the case of imported data. If this value is the only parameter, as in the first example above, the interpretation will be applied to all series in the data set. If value is followed by a list of variables, by name or number, the interpretation is confined to the specified variable(s). Thus in the second example the data value 100 is interpreted as a code for "missing", but only for the variable x2.
A ! at the beginning of a command line is interpreted as an escape to the user's shell. Thus arbitrary shell commands can be executed from within the program.
Arguments: | [ startobs endobs ] y a0 a1 a2 … |
Examples: | sim 1979.2 1983.1 y 0 0.9 | creates y(t) = 0.9*y(t-1) |
sim 15 25 y 10 0.8 x | creates y(t) = 10 + 0.8*y(t-1) + x(t)*y(t-2) | |
sim y 10 0.8 -x | creates y(t) = 10 + 0.8*y(t-1) - x(t)*y(t-2) |
Simulates values for y for the current sample range, or for the range startobs through endobs if these optional arguments are given. The variable y must have been defined earlier with appropriate initial values. The formula used is y(t) = a0(t) + a1(t)*y(t-1) + a2(t)*y(t-2) + … The ai(t) may be either numerical constants or variable names previously defined; these terms may be prefixed with minus sign.
Note that as of gretl 1.2.0, genr (see the Section called genr above) works dynamically, and you will probably find it easier than sim for creating an autoregressive series. For example
genr y = 0 * const genr y = .8*y(-1) -.2*y(-2) + normal()
now achieves the same object as (and with greater clarity than):
genr y = 0 * const genr u = normal() sim y u .8 -.2
Resets the sample range. In the first form startobs and endobs must be consistent with the periodicity of the data. In the second form, the integers i and j are taken as offsets relative to the existing sample range. In the third form dummyvar must be an indicator variable with values 0 or 1 at each observation; the sample will be restricted to observations where the value is 1. The fourth form, smpl -o, drops all observations for which values of one or more variables are missing. The fifth form (-r) restricts the sample to observations that satisfy the given (Boolean) condition. The last form, smpl full, restores the full data range.
smpl 3 10 | data with periodicity 1 |
smpl 1950 1990 | annual data, periodicity 1 |
smpl 1960.2 1982.4 | quarterly data |
smpl 1960.04 1985.10 | monthly data |
smpl 1960.2 ; | keep endobs unchanged |
smpl ; 1984.3 | keep startobs unchanged |
smpl +1 -1 | advance the starting observation by one; move the ending observation back one |
smpl -o dum1 | draw sample of observations where dum1=1 |
smpl -r income > 30000 | sample cases where income has a value greater than 30000. |
The intenal variable obs may be used in the last-noted form of smpl above, to exclude particular observations from the sample. For example, smpl -r obs!=4 will drop just the fourth observation. If the data points are identified by labels, smpl -r obs!="USA" will drop the observation with label "USA".
One point should be noted about the -o and -r forms of smpl: Any "structural" information in the data header file (regarding the time series or panel nature of the data) is lost when this command is issued. You may reimpose structure with the setobs command.
Prints Spearman's rank correlation coefficient for the two variables x and y. The variables do not have to be ranked manually in advance; the function takes care of this. If the -o flag is supplied, the original data and the ranked data are printed out side by side.
The automatic ranking is from largest to smallest (i.e. the largest data value gets rank 1). If you need to invert this ranking, create a new variable which is the negative of the original first. For example:
genr altx = -x spearman altx y
Generates new variables which are squares and cross products of the variables in varlist (-o will create the cross products). For example square x y will generate sq_x = x squared, sq_y = y squared and x_y = x times y. If a particular variable is a dummy variable it is not squared because we will get the same variable.
datafile is the name of the file in which the values should be stored.
If varlist is absent, the values of all the data series in the current data set will be stored. Note that any scalar variables will not be saved automatically: if you wish to save scalars you must explicitly list them in varlist.
By default storage is in native gretl XML format. There are six valid (mutually exclusive) flags:
-z | The default format, but gzip compressed. |
-o | Store the data by variables, in binary format using double precision. |
-s | Store the data by variables, in binary format using single precision. |
-c | Store the data in CSV (comma-separated values) format. Such data can be read directly by spreadsheet programs. |
-r | Store the data in GNU R format. |
-m | Store the data in GNU Octave format. |
-t | Store the data in "traditional" ESL format, with an ascii data file and a separate informative header file. |
Print summary statistics for the variables in varlist, or for all the variables in the data set if varlist is omitted. Output consists of the mean, standard deviation (sd), coefficient of variation (= sd/mean), median, minimum, maximum, skewness coefficient, and excess kurtosis.
Arguments: | type=systype [ savevars=vars ] |
Examples: | system type=sur |
system type=sur save=resids | |
system type=sur save=resids,fitted |
Starts a system of equations. At present the only type of system supported is sur (Seemingly Unrelated Regressions). In the optional save= field of the command you can specify whether to save the residuals (resids) and/or the fitted values (fitted). The system must contain at least two equations specified using the equation command, and it must be terminated with the line end system.
Must follow the estimation of a model via OLS. Prints the estimated model in the form of a LaTeX tabular environment. If a filename is specified using the -f flag output goes to that file, otherwise it goes to a file with a name of the form model_N.tex, where N is the number of models estimated to date in the current session. See also the eqnprint command.
If the -o flag is given the LaTeX file is a complete document, ready for processing; otherwise it must be included in a document.
Must follow a model estimation command. Gives the frequency distribution for the residual from the model along with a chi-square test for normality.
Computes two-stage least squares (TSLS) estimates of parameters. depvar is the dependent variable, varlist1 is the list of independent variables (including right-hand side endogenous variables) in the structural equation for which TSLS estimates are needed. varlist2 is the combined list of exogenous and predetermined variables in all the equations. If varlist2 is not at least as long as varlist1, the model is not identified. The -o flag will print the covariance matrix of the coefficients. In the above example, the ys are the endogenous variables and the xs are the exogenous and predetermined variables. A number of internal variables may be retrieved using the genr command, provided genr is invoked immediately after this command.
Sets up and estimates (using OLS) a vector autoregression (VAR). The first argument specifies the lag order, then follows the setup for the first equation. Don't include lags among the elements of varlist — they will be added automatically. The semi-colon separates the stochastic variables, for which order lags will be included, from deterministic terms in detlist, such as the constant, a time trend, and dummy variables.
In fact, gretl is able to recognize the more common deterministic variables (constant, time trend, dummy variables with no values other than 0 and 1) as such, so these do not have to placed after the semi-colon. More complex deterministic variables (e.g. a time trend interacted with a dummy variable) must be put after the semi-colon.
A separate regression is run for each variable in varlist. Output for each equation includes F-tests for zero restrictions on all lags of each of the variables; an F-test for the significance of the maximum lag; forecast variance decompositions; and impulse response functions.
The variance decompositions and impulse responses are based on the Cholesky decomposition of the contemporaneous covariance matrix, and in this context the order in which the (stochastic) variables are given matters. The first variable in the list is assumed to be "most exogenous" within-period.
Calculates the F statistic for the null hypothesis that the population variances for the variables var1 and var2 are equal, and shows its p-value.
Weighted least squares estimates are obtained using weightvar as the weight, depvar as the dependent variable and indepvars as the list of independent variables. More specifically, an OLS regression is run on weightvar * depvar against weight * indepvars. If the weightvar is a dummy variable, this is equivalent to eliminating all observations with the number zero for weightvar. The flag -o will print the covariance matrix of coefficients. A number of internal variables may be retrieved using the genr command, provided genr is invoked immediately after this command.