1headings 10
2Tests 22
3add
4adf
5chow
6coeffsum
7coint
8coint2
9cusum
10difftest
11hausman
12kpss
13leverage
14levinlin
15meantest
16modtest
17normtest
18omit
19qlrtest
20reset
21restrict
22runs
23vartest
24vif
25Graphs 8
26boxplot
27gnuplot
28graphpg
29plot
30qqplot
31rmplot
32scatters
33textplot
34Statistics 13
35anova
36corr
37corrgm
38fractint
39freq
40hurst
41mahal
42pca
43pergm
44spearman
45summary
46xcorrgm
47xtab
48Dataset 18
49append
50data
51dataset
52delete
53genr
54info
55join
56labels
57markers
58nulldata
59open
60rename
61setinfo
62setmiss
63setobs
64smpl
65store
66varlist
67Estimation 32
68ar
69ar1
70arch
71arima
72biprobit
73dpanel
74duration
75equation
76estimate
77garch
78gmm
79heckit
80hsk
81intreg
82lad
83logistic
84logit
85mle
86mpols
87negbin
88nls
89ols
90panel
91poisson
92probit
93quantreg
94system
95tobit
96tsls
97var
98vecm
99wls
100Programming 18
101break
102catch
103clear
104elif
105else
106end
107endif
108endloop
109flush
110foreign
111function
112if
113include
114loop
115makepkg
116run
117set
118setopt
119Transformations 9
120diff
121discrete
122dummify
123lags
124ldiff
125logs
126orthdev
127sdiff
128square
129Printing 7
130eqnprint
131modprint
132outfile
133print
134printf
135sprintf
136tabprint
137Utilities 7
138eval
139help
140install
141modeltab
142pvalue
143quit
144shell
145Prediction 1
146fcast
147
148# add Tests
149
150Argumento:  lista-de-variáveis
151Opções:     --lm (fazer um teste LM, apenas para MQO)
152            --quiet (mostrar apenas o resultado básico do teste)
153            --silent (não mostrar nada)
154            --vcv (mostrar matriz de covariância para o modelo aumentado)
155            --both (apenas para estimação com variáveis instrumentais, ver abaixo)
156Exemplos:   add 5 7 9
157            add xx yy zz --quiet
158
159Tem que ser invocado após um comando de estimação. Realiza um teste
160conjunto para a adição das variáveis especificadas no último modelo. Os
161resultados desse teste podem ser recuperados via funções de acesso "$test"
162e "$pvalue".
163
164Por omissão é efetuada uma estimação da versão aumentada do modelo
165original, com a inclusão das variáveis da lista-de-variáveis. É
166realizado um teste de Wald sobre o modelo aumentado, que substitui o
167original como o "modelo corrente" para o propósito de, por exemplo, obter
168os resíduos como $uhat ou realizar testes adicionais.
169
170Alternativamente, utilizando a opção --lm (disponível apenas no caso de
171modelos estimados via MQO), será efetuado um teste LM. Uma regressão
172auxiliar é executada, na qual a variável dependente é o resíduo do
173modelo anterior e as variáveis independentes são as mesmas do modelo
174anterior mais as da lista-de-variáveis. De acordo com a hipótese nula de
175que as variáveis acrescentadas não aumentam o poder explicativo, o tamanho
176da amostra vezes o R quadrado não-ajustado desta regressão tem uma
177distribuição qui-quadrado com graus de liberdade iguais ao número de
178regressores adicionados. Neste caso o modelo original não é substituído.
179
180A opção --both é específica para o método dos mínimos quadrados de
181dois estágios: indica que as novas variáveis devem ser acrescentadas tanto
182à lista de regressores quanto à lista de instrumentos, por padrão, neste
183caso, apenas serão acrescentadas à lista de regressores.
184
185Caminho de Menu:    Janela do modelo, /Testes/Acrescentar variáveis
186
187# adf Tests
188
189Argumentos: ordem lista-de-variáveis
190Opções:     --nc (teste sem constante)
191            --c (apenas com constante)
192            --ct (com constante e tendência)
193            --ctt (com constante, tendência e quadrado da tendência)
194            --seasonals (incluir variáveis dummy sazonais)
195            --gls (remover média ou tendência usando GLS)
196            --verbose (mostrar resultados da regressão)
197            --quiet (não mostrar resultados)
198            --difference (usar a primeira diferença da variável)
199            --test-down[=critério] (quantidade de defasagens automática)
200            --perron-qu (ver abaixo)
201Exemplos:   adf 0 y
202            adf 2 y --nc --c --ct
203            adf 12 y --c --test-down
204            Ver tambémjgm-1996.inp
205
206As opções mostradas acima e a discussão que se segue é sobre o uso do
207comando adf com dados de séries temporais típicas. Para usar este comando
208com dados em painel, ver mais abaixo.
209
210Calcula um conjunto de testes de Dickey-Fuller sobre cada uma das variáveis
211listadas, sendo a hipótese nula de que a variável em questão tem uma raiz
212unitária. Mas quando é dada a opção --difference, é calculada sobre as
213primeiras diferenças, assim, a discussão abaixo deve ser entendida como
214sendo sobre a variável transformada.
215
216Por padrão, são apresentadas duas variantes do teste: uma baseada na
217regressão contendo uma constante e uma usando uma constante e uma
218tendência linear. Você pode controlar as variantes que são apresentadas
219ao especificar uma ou mais opções.
220
221A opção --gls pode ser utilizada em conjunto com uma ou mais opções, --c
222e --ct (ou seja, o modelo com constante ou modelo com constante e
223tendência). O efeito desta opção é que a remoção da média ou da
224tendênciação da variável a ser testada é feita usando o procedimento de
225Mínimos Quadrados Generalizados (GLS) sugerido por Elliott, Rothenberg e
226Stock (1996), o que resulta num teste com maior força do que a abordagem
227padrão de Dickey-Fuller. Esta opção não é compatível com a opção
228--nc, --ctt ou --seasonals.
229
230Em todos os casos a variável dependente é a primeira diferença da
231variável especificada, y, e a variável independente chave é a primeira
232desfasagem de y. O modelo é construido de modo que o coeficiente da
233defasagem de y seja igual a raiz em questão menos 1. Por exemplo, o modelo
234com uma constante pode ser escrito como
235
236  (1 - L)y(t) = b0 + (a-1)y(t-1) + e(t)
237
238Sobre a hipótese nula de que o coeficiente da variável desfasada y é
239igual a zero. Sobre a alternativa de que y é estacionária, este
240coeficiente é negativo.
241
242Seleção do nível desfasamentos
243
244Se o número de defasagens (daqui em diante, k) é maior que 0, então k
245desfasagens da variável dependente são incluidas no lado direito das
246regressões de teste. Se a ordem for dada como -1, o valor de k segue a
247recomendação de Schwert (1989), ou seja, a parte inteira de 12(T/100)
248^0.25, onde T é o tamanho da amostra. Em ambos os casos, se a opção
249--test-down for dada, k é considerada como sendo a desfasagem máxima e a
250ordem de desfasamento efetivamente usada é obtida testando os modelos da
251maior para a menor defasagem. O critério para a escolha da defasagem pode
252ser selecionado usando o parâmetro opcional, que deve ser AIC, BIC ou
253tstat. Por padrão é utilizado AIC.
254
255Quando se testa para baixo usando AIC ou BIC, a quantidade final de
256defasagens para a equação ADF é tal que otimiza o critério de
257informação escolhido (de Akaike ou Bayesiano de Schwarz). O procedimento
258exato depende se foi indicada ou não a opção --gls: quando a remoção de
259tendência no GLS é especificada, os AIC e BIC são versões "modificadas"
260descritas em Ng e Perron (2001), caso contrário, elas são as versões
261padrão. No caso GLS existe um refinamento: se a opção adicional
262--perron-qu tiver sido dada, o critério de informação modificado é
263calculado de acordo com o método revisto recomendado por Perron e Qu
264(2007).
265
266Quando se testa para baixo usando o método da estatística t, o
267procedimento é o seguinte:
268
2691. Estimar a regressão de Dickey-Fuller com k desfasagens da variável
270   dependente.
271
2722. A última desfasagem é significante? Se sim, executar o teste com k
273   defasagens. Caso contrário, fazer k = k - 1. Se k for igual a 0,
274   executar o teste com a 0 defasagens, caso contrário ir para o passo 1.
275
276No contexto do passo 2 acima, "significante" quer dizer que para o último
277desfasamento, a estatística t para a última defasagem tem um p-valor
278bilateral assintótico, contra uma distribuição normal, menor ou igual a
2790,10.
280
281Os p valores para os testes de Dickey-Fuller baseiam-se em MacKinnon (1996).
282O código relevante é incluído com a generosa permissão do autor. No caso
283de teste usando a tendência linear (GLS) estes p valores não são
284aplicáveis. Neste caso usam-se os valores críticos da Tabela 1 em Elliott,
285Rothenberg e Stock (1996).
286
287Dados em painel
288
289Quando o comando adf é usado com dados em painel, para produzir testes de
290raiz unitária em painel, as opções disponíveis e os resultados
291apresentados são ligeiramente diferentes.
292
293Em primeiro lugar, enquanto vocIe pode fornecer uma lista de variáveis para
294serem testadas no caso de séries temporais regulares, com dados em painels
295apenas uma variável pode ser testada por comando. Segundo, as opções que
296ontrolam a inclusão de termos determinísticos passam a ser mutuamente
297exclusivas: você deve escolher entre sem constante, apenas com constante e
298constante mais tendência. O padrão é apenas constante. Adicionalmente, a
299opção --seasonals não está disponível. Terceiro, a opção --verbose
300possui um significado diferente: ela prduz um breve detalhamento do teste
301para cada uma das variáveis de séries temporais de forma individual (sendo
302o padrão mostrar apenas o resultado geral).
303
304O teste geral (hipótese nula: a série em questão possui uma raiz
305unitária para todas as unidades de painel) é calculado de uma ou de ambas
306as maneiras: utilizando o método de Im, Pesaran and Shin (Journal of
307Econometrics, 2003) ou o de Choi (Journal of International Money and
308Finance, 2001). O teste de Choi requer que os p-valores estejam disponíveis
309para os testes individuais, se esse não for o caso (dependendo das opções
310selecionadas) ele é omitido. A estatística particular dada para o teste de
311Im, Pesaran, Shin varia como se segue: se o número de defasagens para o
312teste for diferente de zero a estatística W é mostrada, caso contrário,
313se os tamanhos das séries de tempo forem diferentes entre os indivíduos a
314estatístca Z é mostrada, caso contrário a estatística t-barra é
315mostrada.
316
317Caminho de Menu:    /Variável/Teste de Dickey-Fuller aumentado
318
319# anova Statistics
320
321Argumentos: resposta tratamento [ controlo ]
322Opção:      --quiet (não mostrar resultados)
323
324Análise de Variância: resposta é uma série que mede um efeito com
325interesse e tratamento tem que ser uma variável discreta que codifica dois
326ou mais tipos de tratamento (ou não-tratamento). Para ANOVA de duas-vias, a
327variável controlo (que também deve ser discreta) codifica os valores de
328uma variável de controlo.
329
330Quando não se usa a opção --quiet, este comando mostra a tabela das somas
331de quadrados e médias quadradas juntamente com um teste F. O teste F e o
332seu valor P podem ser obtidos usando os acessores $test e $pvalue
333respetivamente.
334
335A hipótese nula do teste F é de que a resposta média é invariante com o
336tipo de tratamento, ou por outras palavras, que o tratamento não produz
337efeito. Em termos formais, o teste é apenas válido se a variância da
338resposta for igual para todos os tipos de tratamentos.
339
340Note que os resultados apresentados por este comando pertencem a um
341subconjunto da informação resultante do procedimento seguinte, que é
342facilmente implementável em gretl. Crie um conjunto de variáveis
343auxiliares que codifiquem todos os tipos de tratamentos, exceto um. No caso
344da ANOVA de duas-vias, adicionalmente, crie um conjunto de variáveis
345auxiliares que codifiquem todos os "controlos" , exceto um. De seguida
346efectue uma regressão sobre resposta com uma constante e com as variáveis
347auxiliares usando "ols". No caso da ANOVA singular (ou uma-via) a tabela é
348produzida passando a opção --anova para ols. No caso da ANOVA de duas-vias
349o teste F relevante, é obtido usando o comando "omit". Por exemplo
350(assumindo que y é a resposta, xt codifica os tratamentos, e xb codifica os
351controlos):
352
353	# uma-via
354	list dxt = dummify(xt)
355	ols y 0 dxt --anova
356	# duas-vias
357	list dxb = dummify(xb)
358	ols y 0 dxt dxb
359	# teste da significância conjunta de dxt
360	omit dxt --quiet
361
362Caminho de Menu:    /Modelo/Outros modelos lineares/ANOVA
363
364# append Dataset
365
366Argumento:  ficheiro-de-dados
367Opções:     --time-series (ver abaixo)
368            --fixed-sample (ver abaixo)
369            --update-overlap (ver abaixo)
370            Ver abaixo para opções especializadas adicionais
371
372Abre um ficheiro de dados e acrescenta esse conteúdo ao conjunto de dados
373actual, se os novos dados forem compatíveis. O programa tentará determinar
374o formato do ficheiro de dados (nativo, texto simples, CSV, Gnumeric, Excel,
375etc.).
376
377Os dados acrescentados podem tomar a forma de observações adicionais em
378variáveis já existentes, ou em novas variáveis. Caso sejam novas
379variáveis, estas terão que ser compatíveis de acordo com: (a) o número
380de observações dos novos dados seja o mesmo que nos dados existentes, ou
381(b) que os novos dados estejam acompanhados de informação clara sobre as
382observações de modo que gretl possa decidir onde colocar os valores.
383
384Existe uma funcionalidade especial para acrescentar a um conjunto de dados
385de painel. Seja n o número de unidades de secção cruzada no painel, T o
386número de períodos temporais, e m o número de observações dos novos
387dados. Se m = n os novos dados serão tomados como invariantes-temporais, e
388serão copiados para a posição em cada período temporal. Por outro lado,
389se m = T os dados serão tratados como sendo não-variantes a longo das
390unidades de painel, e serão copiados para a posição em cada unidade. Se o
391painel é "quadrado", e m é igual a n e a T, acontece uma ambiguidade.
392Neste caso, por omissão, trata-se cada novos dados como sendo
393invariantes-temporais, mas você pode forçar gretl para tratar os novos
394dados como sendo série temporal ao fornecer a opção --time-series. (Esta
395opção é ignorada nos outros casos.)
396
397When a data file is selected for appending, there may be an area of overlap
398with the existing dataset; that is, one or more series may have one or more
399observations in common across the two sources. If the option
400--update-overlap is given, the append operation will replace any overlapping
401observations with the values from the selected data file, otherwise the
402values currently in place will be unaffected.
403
404The additional specialized options --sheet, --coloffset, --rowoffset and
405--fixed-cols work in the same way as with "open"; see that command for
406explanations.
407
408Ver também o comando "join" para um manuseamento mais sofisticado com
409várias fontes de dados.
410
411Caminho de Menu:    /Ficheiro/Acrescentar dados
412
413# ar Estimation
414
415Argumentos: desfasamentos ; variável-dependente variáveis-independentes
416Opção:      --vcv (mostrar matriz de covariância)
417Exemplo:    ar 1 3 4 ; y 0 x1 x2 x3
418
419Determina estimativas para os parâmetros usando o procedimento iteractivo e
420generalizado de Cochrane-Orcutt (ver a Secção 9.5 de Ramanathan, 2002). A
421iteração termina quando os erros das somas de quadrados sucessivos não
422difiram em mais que 0,005 porcento ou após 20 iterações.
423
424"desfasamentos" é uma lista de desfasamentos nos resíduos, terminada por
425um ponto-e-vírgula. No exemplo acima o termo do erro é especificado como
426
427  u(t) = rho(1)*u(t-1) + rho(3)*u(t-3) + rho(4)*u(t-4)
428
429Caminho de Menu:    /Modelo/Série temporal/Estimação autoregressiva
430
431# ar1 Estimation
432
433Argumentos: variável-dependente variáveis-independentes
434Opções:     --hilu (usar o procedimento Hildreth-Lu)
435            --pwe (usar o estimador Prais-Winsten)
436            --vcv (mostrar a matriz de covariância)
437            --no-corc (não aperfeiçoar os resultados com Cochrane-Orcutt)
438            --loose (usar critério de convergência mais relaxado)
439Exemplos:   ar1 1 0 2 4 6 7
440            ar1 y 0 xlist --pwe
441            ar1 y 0 xlist --hilu --no-corc
442
443Determina estimativas admissíveis GLS para um modelo em que se assume que o
444termo de erro segue um processo autoregressivo de primeira-ordem.
445
446O método por omissão é o procedimento iterativo de Cochrane-Orcutt (ver,
447por exemplo, a Secção 9.4 de Ramanathan, 2002). A iteração termina
448quando as estimativas sucessivas do coeficiente de autocorrelação não
449diferirem por mais de 0.001 ou após 20 iterações.
450
451Se tiver sido dada a opção --hilu, é utilizado o procedimento de pesquisa
452de Hildreth-Lu. Os resultados são depois aperfeiçoados usando o método
453Cochrane-Orcutt, exceto se tiver sido indicada a opção --no-corc. (Esta
454última opção é ignorada se não tiver sido usado --hilu).
455
456Se tiver sido dada a opção --pwe, é usado o estimador de Prais-Winsten.
457Isto involve uma iteração semelhante à de Cochrane-Orcutt; a diferença
458é que equanto Cochrane-Orcutt descarta a primeira observação, a de
459Prais-Winsten faz uso dela. Para mais detalhes ver, por exemplo, o Capítulo
46013 do livro de Greene, Econometric Analysis (2000).
461
462Caminho de Menu:    /Modelo/Série temporal/AR(1)
463
464# arch Estimation
465
466Argumentos: ordem variável-dependente variáveis-independentes
467Exemplo:    arch 4 y 0 x1 x2 x3
468
469This command is retained at present for backward compatibility, but you are
470better off using the maximum likelihood estimator offered by the "garch"
471command; for a plain ARCH model, set the first GARCH parameter to 0.
472
473Estima a especificação do modelo fornecido aceitando em ARCH
474(Heterosquedicidade Condicional Autoregressiva). O modelo é primeiramente
475estimado em OLS, e depois é efectuada uma regressão auxiliar, na qual, o
476quadrado dos resíduos da primeira fase é regredido com os seus próprios
477valores desfasados. A fase final é uma estimação por mínimos quadrados
478com pesos, usando como pesos os recíprocos das variâncias de erro
479ajustadas da regressão auxiliar. (Se a variância predita de de alguma
480observação na regressão auxiliar for não positiva, então será usada o
481correspondente resíduo quadrado).
482
483Os valores alpha mostrados abaixo dos coeficientes são os parâmetros
484estimados do processo ARCH da regressão auxiliar.
485
486Ver também "garch" e "modtest" (a opção --arch).
487
488Caminho de Menu:    /Modelo/Série temporal/ARCH
489
490# arima Estimation
491
492Argumentos: p d q [ ; P D Q ] ; variável-dependente [ variáveis-independentes ]
493Opções:     --verbose (mostrar detalhes das iterações)
494            --vcv (mostrar matriz de covariância)
495            --hessian (ver abaixo)
496            --opg (ver abaixo)
497            --nc (não incluir uma constante)
498            --conditional (usar verosimilhança máxima condicional)
499            --x-12-arima (usar X-12-ARIMA para estimação)
500            --lbfgs (usar maximizador L-BFGS-B)
501            --y-diff-only (ARIMAX especial, ver abaixo)
502            --save-ehat (ver abaixo)
503Exemplos:   arima 1 0 2 ; y
504            arima 2 0 2 ; y 0 x1 x2 --verbose
505            arima 0 1 1 ; 0 1 1 ; y --nc
506
507Advertência: arma é uma alcunha aceitável para esta instrução.
508
509Se não for dada a lista de variáveis-independentes, é estimado um modelo
510ARIMA (Média Móvel, Autoregressiva, Integrada) univariado. O valores
511inteiros p, d e q representam respectivamente, a ordem autoregressiva (AR),
512a ordem de diferenciação, e ordem da média móvel (MA). Estes valores
513podem ser fornecidos na forma numérica, ou como nome de variáveis
514escalares pré-existentes. Por exemplo, um valor de 1 em d, significa que a
515primeira diferença da variável dependente deve ser obtida antes de estimar
516os parâmetros ARMA.
517
518Se você pretender apenas incluir no modelo desfasamentos específicos AR ou
519MA (e não todos os desfasamentos até uma certa ordem) você pode
520substituir p e/ou q de acordo com: (a) o nome de uma matriz pré-definida
521contendo um conjunto de valores inteiros, ou (b) uma expressão tal como {1
5224}; ou seja, um conjunto de desfasamentos separados por espaços dentro de
523chavetas.
524
525Os valores inteiros opcionais,P, D e Q representam respectivamente, a
526sazonalidade AR, a ordem para diferenciação de sazonalidade e a ordem de
527sazonalidade MA. Estes são apenas aplicáveis se os dados tiverem uma
528frequência superior a 1 (por exemplo, trimestral ou mensal). Mais uma vez,
529estas ordens podem ser dadas na forma numérica ou como variáveis.
530
531No caso univariado é incluído no modelo por omissão, um interceptor, mas
532isto pode ser suprimido com a opção --nc. Se forem fornecidas
533variáveis-independentes, o modelo passa a ser ARMAX; neste caso a constante
534deve ser explicitamente incluída se você pretender um interceptor (tal
535como no segundo exemplo acima).
536
537Existe outra forma alternativa para este comando: se você não pretende
538aplicar diferenciação (seja sazonal ou não-sazonal), você pode omitir
539ambos os parâmetros d e D, em vez de entrar explicitamente zeros. Além
540disso, arma é um sinónimo ou aliás para arima. Assim, por exemplo, o
541comando seguinte é válido para especificar o modelo ARMA(2, 1):
542
543	arma 2 1 ; y
544
545O normal é usar a funcionalidade "nativa" gretl ARMA, com estimação de
546Máxima Verosimilhança (ML) exata (usando o filtro de Kalman). Outras
547opções são: código nativo, ML condicional; X-12-ARIMA, ML exata; e
548X-12-ARIMA, ML condicional. (As últimas duas opções estão disponíveis
549apenas se o programa X-12-ARIMA estiver instalado.) Para detalhes sobre
550estas opções, veja por favor guia de utilização do Gretl (Capítulo 31).
551
552Quando o código nativo ML é usado, os erros padrão são por omissão
553baseados numa aproximação numérica da (inversa negativa da) Hessiana, ou
554em recurso, no produto externo do gradiente (OPG) caso falhe o cálculo da
555Hessiana numérica. Podem ser usadas duas opções (mutualmente exclusivas)
556para forçar a situação: a opção --opg força o uso do método OPG, sem
557tentar obter a Hessiana, enquanto a opção --hessian desativa o OPG em
558último recurso. Note que a falha na determinação da Hessiana numérica
559indica, em geral um modelo incorretamente especificado.
560
561A opção --lbfgs é específica para estimação usando código nativo ARMA
562e ML exata: significa o uso do algoritmo de "memória limitada" L-BFGS-B em
563vez do usual maximizador BFGS. Isto pode ajudar em alguns casos onde a
564convergência é difícil de atingir.
565
566A opção --y-diff-only é específica na estimação de modelos ARIMAX
567(modelos com uma ordem de integração não-nula e que incluam regressores
568exógenos), e aplica-se apenas quando se usa a ML exata e nativa de gretl.
569Para esses modelos o comportamento normal é de diferenciar tanto as
570variáveis dependentes como as regressoras, mas quando esta opção é
571fornecida, apenas é diferenciada a variável dependente, mantendo-se as
572variáveis regressoras na forma de nível.
573
574A opção --save-ehat é aplicável apenas quando se usa estimação ML
575nativa e exata. O efeito é o de disponibilizar um vector contendo a
576estimativa óptima de período t da perturbação data-t ou inovação: isto
577pode ser recuperado com o uso do acessor $ehat. Estes valores diferem da
578série dos resíduos ($uhat), que contém os erros de predição
579um-passo-à-frente.
580
581O valor AIC retornado em ligação com os modelos ARIMA é calculado
582conforme a definição usada no programa X-12-ARIMA, nomeadamente
583
584  AIC = -2L + 2k
585
586onde L é o logaritmo da verosimilhança e k é o número total de
587parâmetros estimados. Note-se que o programa X-12-ARIMA não produz
588critérios de informação tal como o AIC quando a estimação é por ML
589condicional.
590
591As raízes AR e MA apresentadas em ligação com a estimação ARMA são
592baseadas na seguinte representação de um processo ARMA(p,q):
593
594	(1 - a_1*L - a_2*L^2 - ... - a_p*L^p)Y =
595          c + (1 + b_1*L + b_2*L^2 + ... + b_q*L^q) e_t
596
597As raízes AR são portanto as soluções de
598
599         1 - a_1*z - a_2*z^2 - ... - a_p*L^p = 0
600
601e a estabilidade requer que estas raízes estejam fora do círculo
602unitário.
603
604A imagem da "frequência" apresentada em ligação com as raízes AR e MA é
605o valor lambda que resolve z = r * exp(i*2*pi*lambda) onde z é a raiz em
606questão e r o seu módulo.
607
608Caminho de Menu:    /Modelo/Série temporal/ARIMA
609Acesso alternativo: Menu de contexto da janela principal (selecção singular)
610
611# biprobit Estimation
612
613Argumentos: variável-dependente1 variável-dependente2 variáveis-independentes1 [ ; variáveis-independentes2 ]
614Opções:     --vcv (mostrar a matriz de covariância)
615            --robust (erros padrão robustos)
616            --cluster=variável-agrupada (ver a explicação em "logit")
617            --opg (ver abaixo)
618            --save-xbeta (ver abaixo)
619            --verbose (mostrar informação adicional)
620Exemplos:   biprobit y1 y2 0 x1 x2
621            biprobit y1 y2 0 x11 x12 ; 0 x21 x22
622            Ver tambémbiprobit.inp
623
624Estima um modelo probit bivariado, usando o método de Newton-Raphson para
625maximizar a verosimilhança.
626
627A lista de argumentos começa com as duas variáveis dependentes
628(binárias), seguidas pela lista de regressores. Se a segunda lista tiver
629sido dada, separada por um ponto-e-vírgula, ela será interpretada como
630sendo o conjunto de regressores para a segunda equação, e as
631variáveis-independentes1 são específicas para a primeira equação; caso
632contrário as variáveis-independentes1 são consideradas representando o
633conjunto de regressores comum.
634
635Por omissão, os erros padrão são calculados usando uma aproximação
636númerica por convergência da Hessiana. Mas se tiver sido dada a opção
637--opg a matriz de covariância será baseada no produto externo do gradiente
638(OPG), ou se a opção --robust tiver sido dada, o erros padrão QML serão
639calulados usando a "sandwich" entre a inversa da Hessiana e a OPG.
640
641Depois duma estimação com sucesso, o acessor $uhat obtém uma matriz de
642duas colunas que são os resíduos generalizados das duas equações; ou
643seja, os valores esperados das perturbações condicionadas pelos resultados
644observados e covariados. Por omissão o $yhat obtém a matriz com quatro
645colunas, que são as probabilidades estimadas para os quatro possíveis
646resultados conjuntos para (y_1, y_2), e pela ordem (1,1), (1,0), (0,1),
647(0,0). Alternativamente, se tiver sido usada a opção --save-xbeta, o $yhat
648tem duas colunas e contém os valores das funções de índice para as
649respectivas equações.
650
651A saída inclui o teste de razões de verosimilhança para a hipótese nula
652de que as perturbações nas duas equações são não-correlacionadas.
653
654# boxplot Graphs
655
656Argumento:  lista-de-variáveis
657Opções:     --notches (mostrar intervalo de 90 porcento para a mediana delimitado por entalhes)
658            --factorized (ver abaixo)
659            --panel (ver abaixo)
660            --matrix=nome (mostra o gráfico das colunas da matriz indicada)
661            --output=nome-de-ficheiro (envia a saída para o ficheiro especificado)
662
663Estes gráficos apresentam a distribuição de uma variável. A caixa
664central contém os 50 porcento dos dados centrais, i.e. está limitada pelos
665primeiro e terceiro quartis. Os "bigodes" estendem-se até aos valores
666mínimo e máximo. É desenhada uma linha que corta a caixa na mediana. Um
667símbolo "+" indica a média. Se tiver sido selecionada a opção de mostrar
668o intervalo de confiança para a média, ele é obtido pelo método
669'bootstrap' e apresentado na forma de linhas a tracejado acima e abaixo da
670mediana.
671
672A opção --factorized permite examinar a distribuição de uma variável
673condicionada pelo valor de um fator discreto. Por exemplo, se um conjunto de
674dados contém salários e uma variável auxiliar para o sexo, você pode
675selecionar a variável salário como alvo e o sexo como fator para
676visualizar lado a lado gráficos caixas-com-bigodes dos salários de homens
677e mulheres, como em
678
679	boxplot salario sexo --factorized
680
681Note que neste caso você tem que especificar exatamente duas variáveis,
682com a variável fator em segundo lugar.
683
684Se o conjunto de dados atual é de painel, e apenas tiver sido especificada
685uma variável, a opção --panel produz uma série de gráficos
686caixas-com-bigodes lado a lado, para cada uma das "unidades" do painel ou
687grupo.
688
689Em modo interativo o resultado é mostrado imediatamente. Em modo lote
690('batch') o comportamento normal é o de criar um ficheiro de script gnuplot
691na diretoria de trabalho do utilizador, cujo nome segue a forma gpttmpN.plt,
692iniciando com N = 01. Esses gráficos poderão ser posteriormente gerados
693com o programa gnuplot (em MS Windows, wgnuplot). Este comportamento pode
694ser modificado usando a opção --output= nome-de-ficheiro. Para mais
695detalhes, ver o comando "gnuplot".
696
697Caminho de Menu:    /Ver/Gráfico das variáveis/Caixa com bigodes
698
699# break Programming
700
701Sai de um ciclo. Este comando pode apenas ser usado dentro de um ciclo; ele
702termina a execução de comandos e sai de dentro do ciclo (o mais interior).
703Ver também "loop".
704
705# catch Programming
706
707Sintaxe:    catch command
708
709Isto não é um comando em sentido estrito mas pode ser usado como um
710prefixo na maior parte dos comandos: o efeito é o de prevenir a eventual
711interrupção da execução de comandos (ou de um ficheiro de comandos)
712quando ocorra um erro num comando. Se acontecer um erro, este fica registado
713como sendo um erro interno que pode ser acedido com $error (um valor de zero
714indica sucesso). O valor de $error deve ser sempre verificado imediatamente
715a seguir ao uso de catch, e deve ser tomada a ação adequada se o comando
716falhou.
717
718A palavra reservada catch não pode ser usada antes de if, elif ou endif.
719
720# chow Tests
721
722Variantes:  chow observação
723            chow variável-auxiliar --dummy
724Opções:     --dummy (usar uma variável auxiliar pré-existente)
725            --quiet (não mostrar estimativas para o modelo aumentado)
726            --limit-to=list (limit test to subset of regressors)
727Exemplos:   chow 25
728            chow 1988:1
729            chow female --dummy
730
731Tem que se seguir a uma regressão de Mínimos Quadrados (OLS). Se um
732número de observação ou uma data tiver sido dado, produz um teste sobre a
733hipótese nula de não haver quebra estrutural no ponto de separação
734indicado. O procedimento cria uma variável auxiliar que é igual a 1 a
735partir do ponto especificado por observação até ao final da amostra, caso
736contrário é 0, e cria também termos de interação entre esta variável
737auxiliar e as variáveis regressoras originais. Se tiver sido dada uma
738variável auxiliar, será testada a hipótese nula de homogeneidade
739estrutural no que diz respeito a essa variável auxiliar. Mais uma vez, os
740termos de interação são acrescentados. Em quaisquer dos casos, é
741executada uma regressão aumentada que inclui estes termos e é calculada a
742estatística F, considerando a regressão aumentada como não restringida e
743a original como restringida. Mas se o modelo original usou um estimador
744robusto para a matriz de covariância, a estatística de teste é um valor
745de qui-quadrado de Wald baseada num estimador robusto da matriz de
746covariância da regressão aumentada.
747
748Caminho de Menu:    Janela do modelo, /Testes/Teste de Chow
749
750# clear Programming
751
752Opção:      --dataset (apagar apenas o conjunto de dados)
753
754Sem opções, apaga da memória todos os objetos gravados, incluindo o
755conjunto de dados corrente. Note que ao abrir um novo conjunto de dados, ou
756ao usar o comando "nulldata" para criar um conjunto de dados vazio, obterá
757o mesmo efeito, por isso o uso de "clear" normalmente não é necessário.
758
759Se tiver sido dada a opção --dataset, então apenas o conjunto de dados é
760apagado; os outros objetos gravados como matrizes e escalares serão
761preservados.
762
763# coeffsum Tests
764
765Argumento:  lista-de-variáveis
766Exemplos:   coeffsum xt xt_1 xr_2
767            Ver tambémrestrict.inp
768
769Tem que se seguir a uma regressão. Calcula a soma dos coeficientes nas
770variáveis indicadas na lista-de-variáveis. Apresenta esta soma juntamente
771com o seu erro padrão e o p-value para a hipótese nula de que a soma é
772zero.
773
774Note-se a diferença entre este teste e "omit", que testa a hipótese nula
775de que os coeficientes num conjunto especificado de variáveis independentes
776são todos iguais a zero.
777
778Caminho de Menu:    Janela do modelo, /Testes/Soma de coeficientes
779
780# coint Tests
781
782Argumentos: ordem variável-dependente variáveis-independentes
783Opções:     --nc (não incluir uma constante)
784            --ct (incluir constante e tendência)
785            --ctt (incluir constante e tendência quadrática)
786            --skip-df (não efectuar testes DF nas variáveis individuais)
787            --test-down[=criterion] (ordem de desfasamento automática)
788            --verbose (mostrar detalhes adicionais das regressões)
789            --silent (don't print anything)
790Exemplos:   coint 4 y x1 x2
791            coint 0 y x1 x2 --ct --skip-df
792
793O teste de cointegração Engle-Granger. O procedimento por omissão é: (1)
794efetuar testes de Dickey-Fuller (DF) segundo a hipótese nula de que cada
795variável listada tem uma raiz unitária; (2) estima a regressão de
796cointegração; e (3) executar um teste DF sobre os resíduos da regressão
797de cointegração. Se for dada a opção --skip-df, o passo (1) é omitido.
798
799Se a ordem de desfasamento especificada é positiva, todos os testes
800Dickey-Fuller usam essa ordem, com esta qualificação: se a opção
801--test-down for dada, o valor indicado é tomado como sendo o máximo e a
802ordem de desfasamento efetivamente usada em cada caso é obtida testando
803para baixo. Ver o comando "adf" para detalhes sobre este procedimento.
804
805Por omissão, a regressão de cointegração contém uma constante. Se você
806deseja suprimir a constante, acrescente a opção --nc. Se você deseja
807aumentar a lista de termos determinísticos na regressão de cointegração
808com uma tendência linear ou quadrática, use a opção --ct ou --ctt. Estas
809opções são mutualmente exclusivas.
810
811Os P-values para este teste são baseados em MacKinnon (1996). O código
812relevante é incluído com a generosa permissão do autor.
813
814Caminho de Menu:    /Modelo/Série temporal/Testes de Cointegração/Engle-Granger
815
816# coint2 Tests
817
818Argumentos: ordem listaY [ ; listaX ] [ ; listaRx ]
819Opções:     --nc (sem constante)
820            --rc (constante restringida)
821            --uc (constante não restringida)
822            --crt (constante e tendência restringida)
823            --ct (constante e tendência não restringida)
824            --seasonals (incluir auxiliares sazonais centradas)
825            --asy (registar valores p assimtóticos)
826            --quiet (apenas mostrar os testes)
827            --silent (não mostrar nada)
828            --verbose (mostrar detalhes das regressões auxiliares)
829Exemplos:   coint2 2 y x
830            coint2 4 y x1 x2 --verbose
831            coint2 3 y x1 x2 --rc
832
833Executa o teste de Johansen para a cointegração entre as variáveis em
834listaY para a dada ordem de desfasamento. Para detalhes sobre este teste ver
835guia de utilização do Gretl (Capítulo 33) ou Hamilton (1994), Capítulo
83620. Os valores p são calculados usando a aproximação gama de Doornik
837(Doornik, 1998). São mostrados dois conjuntos de valores p para o teste
838traço, valores assintóticos imediatos e valores ajustados para o tamanho
839da amostra. Por omissão, o acessor $pvalue obtém a variante ajustada, mas
840se opção --asy for dada, pode ser usado para registar os valores
841assintóticos.
842
843A inclusão de termos determinísticos no modelo é controlada por
844intermédio das opções. Por omissão, se não tiver sido indicada nenhuma
845opção, será incluída uma "constante não restringida", o que permite a
846presença de um interceptor não-nulo nas relações cointegrantes assim
847como uma tendência nos níveis das variáveis endógenas. Na literatura
848derivada do trabalho de Johansen (ver por exemplo o livro dele de 1995) isto
849é frequentemente referido como sendo o "caso 3". As primeiras quatro
850opções apresentadas acima, que são mutualmente exclusivas, produzem
851respectivamente os casos 1, 2, 4, e 5. O significado destes casos e os
852critérios para seleccionar um caso estão explicados no guia de
853utilização do Gretl (Capítulo 33).
854
855As listas opcionais listaX e listaRx permite-lhe controlar as variáveis
856exógenas: estas entram no sistema como não restringidas (listaX) ou
857restringidas ao espaço de cointegração (listaRx). Estas listas são
858separadas da listaY e entre elas usando ponto-e-vírgulas.
859
860A opção --seasonals, que pode ser combinada com qualquer outra opção,
861especifica a inclusão de um conjunto de variáveis auxiliares sazonais.
862Esta opção apenas está disponível para dados trimestrais ou mensais.
863
864A seguinte tabela serve como um guia à interpretação dos resultados
865apresentados pelo teste, num caso de 3-variáveis. H0 significa a hipótese
866nula, H1 a hipótese alternativa, e c o número de relações cointegrantes.
867
868         Ordem    Teste Traço        Teste Lmax
869                  H0     H1          H0     H1
870         ---------------------------------------
871          0      c = 0  c = 3       c = 0  c = 1
872          1      c = 1  c = 3       c = 1  c = 2
873          2      c = 2  c = 3       c = 2  c = 3
874         ---------------------------------------
875
876Ver também o comando "vecm".
877
878Caminho de Menu:    /Modelo/Série temporal/Testes de Cointegração/Johansen
879
880# corr Statistics
881
882Argumento:  [ lista-de-variáveis ]
883Opções:     --uniform (garante amostra uniforme)
884            --spearman (Ró de Spearman)
885            --kendall (Tau de Kendall)
886            --verbose (mostra classificações ('rankings'))
887Exemplos:   corr y x1 x2 x3
888            corr ylist --uniform
889            corr x y --spearman
890            corr --matrix=X --plot=display
891
892Por omissão, apresenta os coeficientes de correlação emparelhados
893(correlação momento-produto de Pearson) para as variáveis
894lista-de-variáveis, ou para todas as variáveis no conjunto de dados se
895não tiver sido indicada lista-de-variáveis. O comportamento normal é o de
896usar todas as observações disponíveis para calcular cada coeficiente
897emparelhado, mas se tiver sido dada a opção --uniform a amostra será
898limitada (caso seja necessário) de modo que o mesmo conjunto de
899observações seja usado em todos os coeficientes. Esta opção apenas tem
900efeito se existirem valores omissos em quantidades diferentes para as
901variáveis usadas.
902
903As opções (mutualmente exclusivas) --spearman e --kendall produzem,
904respetivamente, o Ró de correlação de Spearman e o Tau de correlação de
905ordem de Kendall em vez do usual coeficiente de Pearson. Quando uma destas
906opções é dada, a lista-de-variáveis deve apenas conter duas variáveis.
907
908Ao calcular uma correlação de ordem, pode ser dada a opção --verbose
909para mostrar os dados originais e ordenados (caso contrário esta opção
910será ignorada).
911
912Caminho de Menu:    /Ver/Matriz de correlação
913Acesso alternativo: Menu de contexto da janela principal (selecção múltipla)
914
915# corrgm Statistics
916
917Argumentos: série [ ordem ]
918Opções:     --bartlett (use Bartlett standard errors)
919            --plot=modo ou nome-de-ficheiro (ver abaixo)
920Exemplo:    corrgm x 12
921
922Apresenta os valores da função de autocorrelação para a série, que pode
923ser especificada por nome ou por número. Os valores são definidos como
924rho(u_t, u_t-s) onde u_t é a t-ésima observação da variável u e s é o
925número de desfasamentos.
926
927Também são apresentadas as autocorrelações parciais (obtidas segundo o
928algoritmo de Durbin-Levinson): estas constituem a rede dos efeitos dos
929desfasamentos intervenientes. Adicionalmente, é apresentada a estatística
930de teste Q de Ljung-Box. Esta pode ser usada para testar a hipótese nula de
931que a série é "ruído branco": terá uma distribuição qui-quadrado
932assimptótico com os graus de liberdade iguais ao número de desfasamentos
933usados.
934
935Se o valor ordem for especificado o comprimento do correlograma fica
936limitado a esse máximo número de desfasamentos, senão o comprimento é
937determinado automaticamente, como uma função da frequência dos dados e do
938número de observações.
939
940Por omissão é apresentado um gráfico do correlograma: um gráfico gnuplot
941em modo interativo ou um gráfico ASCII em modo de lote de comandos. Isto
942pode ser ajustado por via da opção --plot. Os parâmetros válidos para
943esta opção são none (para suprimir o gráfico); ascii (para produzir um
944gráfico de texto mesmo em modo interativo); display (para produzir um
945gráfico gnuplot mesmo em modo de lote de comandos); ou o nome de um
946ficheiro. O efeito de se fornecer um nome de ficheiro é como descrito para
947a opção --output do comando "gnuplot".
948
949Depois de completar com sucesso, os acessores $test e $pvalue contêm os
950respectivos valores do teste de Ljung-Box para a maior ordem apresentada.
951Note que se você apenas quiser determinar a estatística Q, provavelmente
952você quererá usar a função "ljungbox".
953
954Caminho de Menu:    /Variável/Correlograma
955Acesso alternativo: Menu de contexto da janela principal (selecção singular)
956
957# cusum Tests
958
959Opções:     --squares (executa o teste CUSUMSQ)
960            --quiet (apenas mostra o teste Harvey-Collier)
961
962Tem que se seguir à estimação de um modelo por via de OLS. Executa o
963teste CUSUM -- ou se for dada a opção --squares, o teste CUSUMSQ -- para a
964estabilidade dos parâmetros. É obtida uma série temporal de erros de
965predição um passo-à-frente, pela execução de séries de regressões: a
966primeira regressão usa as primeiras k observações e é usada para gerar a
967predição da variável dependente na observação k + 1; a segunda usa a
968primeira predição para a observação k + 2, e por aí a diante (onde k é
969o número de parâmetros no modelo original).
970
971A soma acumulada dos erros de predição escalados, ou os quadrados desses
972erros, é mostrada e apresentada em gráfico. A hipótese nula para a
973estabilidade dos parâmetros é rejeitada ao nível de cinco porcento, se a
974soma acumulada se desviar do intervalo de confiança de 95 porcento.
975
976No caso do teste CUSUM, é também apresentada a estatística de teste t de
977Harvey-Collier, para a hipótese nula da estabilidade dos parâmetros. Ver o
978livro Econometric Analysis de Greene para mais detalhes. Para o teste
979CUSUMSQ, o intervalo de confiança a 95 porcento é calculado de acordo com
980o algoritmo apresentado por Edgerton e Wells (1994).
981
982Caminho de Menu:    Janela do modelo, /Testes/Teste CUSUM(SQ)
983
984# data Dataset
985
986Argumento:  lista-de-variáveis
987Opções:     --compact=method (specify compaction method)
988            --interpolate (do interpolation for low-frequency data)
989            --quiet (não reportar resultados exceto quando hajam erros)
990
991Lê as variáveis indicadas na lista-de-variáveis a partir de uma base de
992dados (gretl, RATS 4.0 ou PcGive), que deve ter sido préviamente aberta
993usando o comando "open". A frequência dos dados e o intervalo da amostra
994podem ser definidos pelos comandos "setobs" e "smpl" antes de usar este
995comando. Apresenta-se um exemplo completo:
996
997	open macrodat.rat
998	setobs 4 1959:1
999	smpl ; 1999:4
1000	data GDP_JP GDP_UK
1001
1002Os comandos acima abrem a base de dados com o nome macrodat.rat, definem um
1003conjunto de dados trimestral iniciando no primeiro trimestre de 1959 e
1004terminando no quarto trimestre de 1999, e depois importam as séries
1005temporais com os nomes GDP_JP e GDP_UK.
1006
1007Se os comandos setobs e smpl não tiverem sido especificados deste modo, a
1008frequência dos dados e o intervalo da amostra serão definidos usando a
1009primeira variável lida da base de dados.
1010
1011Se as séries temporais a serem lidas forem de frequência superior à do
1012conjunto de dados em uso, você pode especificar um método de compactação
1013tal como abaixo:
1014
1015	data (compact=average) LHUR PUNEW
1016
1017Os quatro métodos de compactação disponíveis são: Média; "average"
1018(usa a média das observações de maior frequência), Último; "last" (usa
1019a última observação), Primeiro; "first" e Soma; "sum". Se não tiver sido
1020indicado nenhum métod, será usado a Média.
1021
1022If the series to be read are of lower frequency than the working dataset,
1023the default is to repeat the values of the added data as required, but the
1024--interpolate option can be used to request interpolation using the method
1025of Chow and Lin (1971): the regressors are a constant and quadratic trend
1026and an AR(1) disturbance process is assumed. Note, however, that this option
1027is available only for conversion from quarterly data to monthly or annual
1028data to quarterly.
1029
1030In the case of native gretl databases (only), the "glob" characters * and ?
1031can be used in varlist to import series that match the given pattern. For
1032example, the following will import all series in the database whose names
1033begin with cpi:
1034
1035	data cpi*
1036
1037Caminho de Menu:    /Ficheiro/Bases de Dados
1038
1039# dataset Dataset
1040
1041Argumentos: palavra-chave parâmetros
1042Exemplos:   dataset addobs 24
1043            dataset insobs 10
1044            dataset compact 1
1045            dataset compact 4 last
1046            dataset expand interp
1047            dataset transpose
1048            dataset sortby x1
1049            dataset resample 500
1050            dataset renumber x 4
1051            dataset pad-daily 7
1052            dataset clear
1053
1054Efectua diversas operações sobre o conjunto de dados como um todo,
1055dependendo da palavra-chave, que tem que ser addobs, insobs, clear, compact,
1056expand, transpose, sortby, dsortby, resample ou renumber. Nota: exceptuando
1057clear, estas ações não estão disponíveis enquanto o conjunto de dados
1058estiver subamostrado por seleção de casos com algum critério Booleano.
1059
1060addobs: Tem que ser seguida por um inteiro positivo. Acrescenta o número
1061indicado de observações adicionais no final do conjunto de dados em uso.
1062Essencialmente, isto é pretendido para efeitos de predição. Os valores na
1063maior parte das variáveis no intervalo acrescentado, serão marcados como
1064omissos, mas certas variáveis determinísticas são reconhecidas e
1065extendidas, nomeadamente, uma tendência linear simples e variáveis
1066periódicas auxiliares.
1067
1068insobs: Tem que ser seguida por um inteiro positivo que não seja maior que
1069o número de observações atual. Inserte uma única observação na
1070posição indicada. Todos os dados subsequentes são deslocados uma
1071posição e o conjunto de dados fica extendido com mais uma observação.
1072Todas as variáveis exceto a constante recebem um valor omisso na nova
1073observação. Esta ação não está disponível para conjuntos de dados de
1074painel.
1075
1076clear: Não necessita parâmetros. Limpa o conjunto de dados corrente,
1077ficando gretl no seu estado "vazio" inicial.
1078
1079compact: Tem que ser seguida por um inteiro positivo representando uma nova
1080frequência, que deve ser inferior à frequência atual (por exemplo, um
1081valor 4 quando a frequência corrente é 12, indica a compactação de
1082mensal para trimestral). Este comando apenas está disponível para séries
1083temporais; ele compacta todas as séries temporais do conjunto de dados para
1084a nova frequência. Pode ser dado um segundo parâmetro, nomeadamente um de
1085sum, first ou last, para especificar, respectivamente, compactação usando
1086a soma dos valores de maior frequência, valores de ínicio e de fim de
1087período. Por omissão é feita compactação por média.
1088
1089expand: Este comando está apenas disponível para séries temporais anuais
1090ou trimestrais: dados anuais podem ser expandidos para trimestrais, e dados
1091trimestrais para frequência mensal. Por omissão todas as séries temporais
1092no conjunto de dados são preenchidas com repetição de valores existentes
1093até atingirem a nova frequência, mas se tiver sido acrescentado o
1094modificador interp então as séries temporais serão expandidas usando a
1095interpolação de Chow-Lin: os regressores são a constante e a tendência
1096quadrada e é assumido um processo de perturbação AR(1).
1097
1098transpose: Não necessita parâmetros. Transpõe o conjunto de dados actual.
1099Isto é, cada observação (linha) será tratada como uma variável
1100(coluna), e cada variável como uma observação. Este comando pode ser
1101útil se quando os dados tenham sido lidos a partir de uma origem externa em
1102que as linhas da tabela de dados representam variáveis.
1103
1104sortby: É necessário o nome de uma lista ou de uma única série de dados.
1105Se tiver sido dada uma série de dados, as observações em todas as
1106variáveis do conjunto de dados são re-ordenadas por ordem crescente da
1107série especificada. Se tiver sido dada uma lista, a ordenação é
1108hierárquica: se as observações estiverem empatadas no que diz respeito à
1109primeira variável chave então é usada a segunda chave para desempatar, e
1110assim sucessivamente até que não haja empates ou se tenham esgotado as
1111chaves. Note que este comando apenas está disponível para dados sem data.
1112
1113dsortby: Funciona como sortby exceto que a re-ordenação é por ordem
1114decrescente das séries chave.
1115
1116resample: Constrói um novo conjunto de dados por amostragem aleatória, com
1117substituição das linhas do conjunto de dados corrente. Requer um
1118argumento, designadamente o número de linhas a incluir. Este pode ser
1119menor, igual ou maior que o número de observações nos dados originais. O
1120conjunto de dados original pode ser obtido usando o comando smpl full.
1121
1122renumber: Requer o nome de uma de uma série seguido por um inteiro entre 1
1123e o número de séries no conjunto de dados menos 1. Move a série
1124especificada para a posição indicada dentro do conjunto de dados,
1125renumerando adequadamente as restantes séries. (A posição 0 está ocupada
1126pela constante, que não pode ser movida.)
1127
1128Caminho de Menu:    /Dados
1129
1130# delete Dataset
1131
1132Variantes:  delete lista-de-variáveis
1133            delete nome-de-variável
1134            delete --type=nome-de-tipo
1135Opção:      --db (apaga séries em base de dados)
1136
1137Este comando é um destrutor geral para variáveis com nome (quer sejam
1138séries, escalares, matrizes, texto, ou 'bundles'). Tem que ser usada com
1139cuidado; não será peguntada nenhuma confirmação.
1140
1141No caso de uma série nome-de-variável pode tomar a forma de uma lista com
1142nome, o que faz com que todas as séries nessa lista sejam apagadas, ou pode
1143tomar a forma de uma lista explícita de séries por nome ou número ID.
1144Note que quando você apaga séries, quaisquer séries com números ID
1145superiores àquelas que estão na lista a apagar serão renumeradas.
1146
1147Se for dada a opção --db, o comando apaga as séries listadas não do
1148conjunto de dados atual mas de uma base de dados gretl, assumindo que a base
1149de dados está aberta e que o utilizador tem permissão de escrita no
1150ficheiro em questão. Ver também o comando "open".
1151
1152Se tiver sido dada a opção --type ela terá de ser acompanhada por um dos
1153seguintes nomes-de-tipo: matrix (matriz), bundle ('bundle'), string (texto),
1154list (lista), ou scalar (escalar). O efeito é o de apagar todas as
1155variáveis do tipo dado. Neste caso (somente neste), não deve ser indicado
1156o argumento nome-de-variável.
1157
1158Caminho de Menu:    Menu de contexto da janela principal (selecção singular)
1159
1160# diff Transformations
1161
1162Argumento:  lista-de-variáveis
1163
1164É obtida a primeira diferença de cada variável na lista-de-variáveis e o
1165resultado é guardado numa nova variável com o prefixo d_. Portanto "diff x
1166y" cria as duas novas variáveis
1167
1168	d_x = x(t) - x(t-1)
1169	d_y = y(t) - y(t-1)
1170
1171Caminho de Menu:    /Acrescentar/Primeiras diferenças das variáveis selecionadas
1172
1173# difftest Tests
1174
1175Argumentos: variável1 variável2
1176Opções:     --sign (Teste dos Sinais, por omissão)
1177            --rank-sum (Teste ordinal da soma de Wilcoxon)
1178            --signed-rank (Teste ordinal dos sinais de Wilcoxon)
1179            --verbose (mostrar detalhes)
1180
1181Realiza um teste não-paramétrico para a diferença entre duas populações
1182ou grupos, o teste específico depende da opção selecionada.
1183
1184Com a opção --sign, é executado o teste dos Sinais. Este teste baseia-se
1185no facto de duas amostras x e y, terem sido extraídas aleatóriamente de
1186uma mesma distribuição, a probabilidade de x_i > y_i, para cada
1187observação i, deve ser igual a 0,5. A estatística de teste é w, o
1188número de observações para as quais x_i > y_i. Sob a hipótese nula de
1189que segue uma distribuição Binomial com os parâmetros (n, 0,5), onde n é
1190o número de observações.
1191
1192Com a opção --rank-sum, é executado o teste ordinal da soma de Wilcoxon.
1193Este teste consiste em ordenar as observações de ambas as amostras
1194conjuntamente, da menor para a maior, e depois determinar a soma das ordens
1195de uma das amostras. As duas amostras não necessitam ser do mesmo tamanho,
1196e se isso acontece então usa-se a de menor dimensão no cálculo da soma
1197das ordens. Sob a hipótese nula de que as amostras terem sido extraídas de
1198populações com a mesma mediana, a distribuição de probabilidade da soma
1199das ordens pode ser determinada para quaisquer tamanhos das amostras; e para
1200amostras consideravelmente grandes existe uma forte aproximação a uma
1201distribuição Normal.
1202
1203Com a opção --signed-rank, é executado o teste ordinal dos sinais de
1204Wilcoxon. Este destina-se para pares de dados associados assim como, por
1205exemplo, os valores das variáveis de uma amostra de indivíduos antes e
1206depois de algum tratamento. O teste começa por encontrar as diferenças
1207entre as observações emparelhadas, x_i - y_i, ordenando estas diferenças
1208por valor absoluto, e então atribuindo a cada par um posto com sinal,
1209coincidindo o sinal com o sinal da diferença. De seguida é calculado o
1210W_+, que é a soma dos postos com sinal positivo. Tal como o teste ordinal
1211da soma, esta estatística tem uma distribuição bem definida, sob a
1212hipótese nula de que a diferença mediana é zero, que converge para a
1213distribuição Normal em amostras de tamanho razoável.
1214
1215Para os testes de Wilcoxon, se a opção --verbose tiver sido dada então
1216será mostrado as ordens. (Esta opção não tem efeito se tiver sido
1217selecionado o teste dos Sinais.)
1218
1219# discrete Transformations
1220
1221Argumento:  lista-de-variáveis
1222Opção:      --reverse (marca variáveis como sendo contínuas)
1223
1224Marca cada variável em lista-de-variáveis como sendo discreta. Por
1225omissão todas as variáveis são tratadas como sendo contínuas; ao marcar
1226uma variável como sendo discreta afeta o modo como a variável é usada em
1227diagramas de frequência, e também permite-lhe selecionar a variável para
1228o comando "dummify".
1229
1230Se a opção --reverse tiver sido dada, é feito o contrário; ou seja, as
1231variáveis em lista-de-variáveis são marcadas como sendo contínuas.
1232
1233Caminho de Menu:    /Variável/Editar caraterísticas
1234
1235# dpanel Estimation
1236
1237Argumento:  p ; variável-dependente variáveis-independentes [ ; instrumentos ]
1238Opções:     --quiet (não mostrar o modelo estimado)
1239            --vcv (mostrar a matriz de covariância)
1240            --two-step (efetuar estimação GMM de dois passos)
1241            --system (acrescentar equações por níveis)
1242            --time-dummies (acrescentar variáveis auxiliares tempo)
1243            --dpdstyle (comportamento semelhante ao do pacote DPD do Ox)
1244            --asymptotic (erros padrão assimptóticos não corrigidos)
1245Exemplos:   dpanel 2 ; y x1 x2
1246            dpanel 2 ; y x1 x2 --system
1247            dpanel {2 3} ; y x1 x2 ; x1
1248            dpanel 1 ; y x1 x2 ; x1 GMM(x2,2,3)
1249            Ver tambémbbond98.inp
1250
1251Efectua a estimação de modelos de dados de painel dinâmico (ou seja,
1252modelos de painel que incluem um ou mais desfasamentos da variável
1253dependente) usando os métodos GMM-DIF ou GMM-SYS.
1254
1255O parâmetro p representa a ordem de autoregressão para a variável
1256dependente. Na forma mais simples esta é um valor escalar, mas este
1257argumento pode ser uma matriz pré-definida, para especificar um conjunto
1258(eventualmente descontínuo) de desfasamentos a serem usados.
1259
1260A variável dependente e os regressores devem ser dados na forma de níveis;
1261eles serão automaticamente diferenciados (pois este estimador usa
1262diferenciação para anular os efeitos individuais).
1263
1264O último campo (opcional) do comando é para especificar instrumentos. Se
1265não tiver sido dado instrumentos, é assumido que todas as variáveis
1266independentes são estritamente exógenas. Caso você especifique alguns
1267intrumentos, deverá incluir na lista variáveis independentes estritamente
1268exógenas. Para regressores pré-determinados, você pode usar a função
1269GMM para incluir a especificação de uma gama de desfasamentos numa forma
1270bloco-diagonal. Isto está exemplificado no terceiro exemplo acima. O
1271primeiro argumento de GMM é o nome da variável em questão, o segundo é o
1272desfasamento mínimo a ser usado como instrumento, e o terceiro é o
1273desfasamento máximo. A mesma sintaxe pode ser utilizada na função
1274GMMlevel para especificar instrumentos do tipo GMM para as equações nos
1275níveis.
1276
1277Por omissão são apresentados os resultados da estimação a um passo
1278(juntamente com erros padrão robustos). Opcionalmente você pode selecionar
1279a estimação a dois passos. Em ambos os casos são determinados os testes
1280de autocorrelação de ordem 1 e 2, assim como o teste de Sargan para a
1281sobre-identificação e o teste de Wald para a significância conjunta dos
1282regressores. Note que neste modelo diferenciado a autocorrelação de
1283primeira ordem não é um risco para a validade do modelo, mas a
1284autocorrelação de segunda ordem viola as assunções estatísticas
1285presentes.
1286
1287No caso da estimação em dois passos, os erros padrão são obtidos por
1288omissão usando a correção de amostra-finita sugerida por Windmeijer
1289(2005). Os erros padrão assimptóticos associados ao estimador de dois
1290passos, são em geral, considerados como um guia pouco fiável para
1291inferência, mas se por alguma razão você desejar observá-los você pode
1292usar a opção --asymptotic para desligar a correção de Windmeijer.
1293
1294Se tiver sido dada a opção --time-dummies, uma conjunto de variáveis
1295auxiliares tempo é acrescentado aos regressores especificados. O número de
1296auxiliares é menos um que o número máximo de períodos usados na
1297estimação, para assim se evitar a colinearidade exata com a constante. As
1298variáveis auxiliares entram na forma diferenciada, exceto se tiver sido
1299dada a opção --dpdstyle, entrando nesse caso por níveis.
1300
1301Para mais detalhes e exemplos, ver o guia de utilização do Gretl
1302(Capítulo 24).
1303
1304Caminho de Menu:    /Modelo/Painel/Modelo de painel dinâmico
1305
1306# dummify Transformations
1307
1308Argumento:  lista-de-variáveis
1309Opções:     --drop-first (omitir da codificação o menor valor)
1310            --drop-last (omitir da codificação o maior valor)
1311
1312Para cada uma das variáveis adequadas em lista-de-variáveis, cria um
1313conjunto de variáveis auxiliares codificando para os diferentes valores
1314dessa variável. É adequado para as variáveis que tenham sido
1315explícitamente marcadas como sendo discretas, ou aquelas que tomem uma
1316quantidade razoavelmente pequena de valores todos eles "quase redondos"
1317(múltiplos de 0,25).
1318
1319Por omissão é criada uma variável auxiliar para cada valor distinto na
1320variável em questão. Por exemplo se uma variável discreta x tiver 5
1321valores distintos, serão criadas 5 variáveis auxiliares e acrescentadas ao
1322conjunto de dados, com os nomes, Dx_1, Dx_2 e por aí adiante. A primeira
1323variável auxiliar terá o valor 1 para observações onde x toma o seu
1324valor mais pequeno, 0 caso contrário; a variável auxiliar seguinte terá o
1325valor 1 quando x toma o seu segundo valor mais pequeno, e por aí adiante.
1326Se uma das opções --drop-first ou --drop-last tiver sido acrescentada,
1327então o menor ou o maior valor de cada variável será omitido da
1328codificação (o que pode ser útil para evitar a "armadilha das variáveis
1329auxiliares").
1330
1331Este comando também pode ser introduzido no contexto da especificação de
1332uma regressão. Por exemplo, a linha seguinte especifica um modelo onde y é
1333regredido sobre o conjunto de variáveis auxiliares codificadas em x. (Neste
1334contexto, as opções não podem ser passadas a "dummify".)
1335
1336	ols y dummify(x)
1337
1338Acesso alternativo: Main window pop-up menu (single selection)
1339
1340# duration Estimation
1341
1342Argumentos: variável-dependente variáveis-independentes [ ; variável-censora ]
1343Opções:     --exponential (usar a distribuição exponencial)
1344            --loglogistic (usar a distribuição log-logística)
1345            --lognormal (usar a distribuição log-normal)
1346            --medians (os valores ajustados são medianas)
1347            --robust (erros padrão robustos (QML))
1348            --cluster=variável-agrupada (ver a explicação em "logit")
1349            --vcv (mostrar a matriz de covariância)
1350            --verbose (mostrar detalhes das iterações)
1351Exemplos:   duration y 0 x1 x2
1352            duration y 0 x1 x2 ; cens
1353
1354Estima um modelo de duração: a variável dependente (que tem que ser
1355positiva) representa a duração de algum tipo de estado num certo assunto,
1356por exemplo a duração de episódios de desemprego para uma seção-cruzada
1357de inquiridos. Por omissão é utilizada a distribuição de Weibull, mas é
1358possível usar as distribuições exponencial, log-logística e a
1359log-normal.
1360
1361Se alguma das medições de durações estiver censurada ('right-censored')
1362(por exemplo, para um certo índividuo um episódio de desemprego não
1363chegou ao fim dentro do período de observação) então você pode
1364acrescentar como último argumento a variável-censora, que é uma série na
1365qual valores diferentes de zero indicam caso censurados.
1366
1367Por omissão os valores ajustados obtidos por intermédio do acessor $yhat
1368são as médias condicionadas das durações, mas se tiver sido dada a
1369opção --medians, então $yhat devolve as medianas condicionadas.
1370
1371Para mais detalhes ver guia de utilização do Gretl (Capítulo 38).
1372
1373Caminho de Menu:    /Modelo/Modeloso-lineares/Dados de durações...
1374
1375# elif Programming
1376
1377Ver "if".
1378
1379# else Programming
1380
1381Ver "if". Note que "else" requer uma linha para ele mesmo, antes do comando
1382condicional seguinte. Você pode juntar um comentário, como em
1383
1384	else # Certo, fazer algo diferente
1385
1386Mas não pode juntar a um comando, como em
1387
1388	else x = 5 # Errado!
1389
1390# end Programming
1391
1392Termina diversos tipos de bloco de comandos. Por exemplo, "end system"
1393termina uma equação "system".
1394
1395# endif Programming
1396
1397Ver "if".
1398
1399# endloop Programming
1400
1401Marca o fim de um ciclo de comandos. Ver "loop".
1402
1403# eqnprint Printing
1404
1405Opções:     --complete (Cria um documento completo)
1406            --output=nome-de-ficheiro (envia a saída para o ficheiro especificado)
1407
1408Tem que ser invocado a seguir à estimação de um modelo. Mostra o modelo
1409estimado na forma de uma equação LaTeX. Se o nome-de-ficheiro tiver sido
1410especificado usando a opção -f a saída é redirecionada para esse
1411ficheiro, caso contrário vai para um ficheiro com o nome no formato
1412equation_N.tex, onde N é o número de modelos estimados até ao momento na
1413sessão corrente. Ver também "tabprint".
1414
1415Se a opção --complete tiver sido dada, o ficheiro LaTeX é um documento
1416completo, pronto para ser processado; de outro modo ele terá que ser
1417incluído num documento.
1418
1419Caminho de Menu:    Janela do Modelo, /LaTeX
1420
1421# equation Estimation
1422
1423Argumentos: variável-dependente variáveis-independentes
1424Exemplo:    equation y x1 x2 x3 const
1425
1426Especifica uma equação dentro de um sistema de equações (ver "system").
1427A sintaxe para especificar uma equação dentro de um sistema SUR é o mesmo
1428que em, por exemplo, "ols". Para uma equação dentro de um sistema de
1429Mínimos Quadrados de Três-Fases você tanto pode (a) fornecer uma
1430especificação de equação tipo OLS e dar uma lista comum de instrumentos
1431usando o comando "instr" (mais uma vez, ver "system"), ou (b) usar a mesma
1432sintaxe de equação como para "tsls".
1433
1434# estimate Estimation
1435
1436Argumentos: [ nome-do-sistema ] [ estimador ]
1437Opções:     --iterate (iterar até à convergência)
1438            --no-df-corr (não usar correção de graus de liberdade)
1439            --geomean (ver abaixo)
1440            --quiet (não mostrar resultados)
1441            --verbose (mostrar detalhes das iterações)
1442Exemplos:   estimate "Klein Model 1" method=fiml
1443            estimate Sys1 method=sur
1444            estimate Sys1 method=sur --iterate
1445
1446Chama a estimação de um sistema de equações, que foi previamente
1447definido usando o comando "system". O nome do sistema deve ser dado em
1448primeiro lugar, dentro de aspas caso contenha espaços. O estimador, que tem
1449que ser um de "ols", "tsls", "sur", "3sls", "fiml" ou "liml", é precedido
1450pelo texto method=. Estes argumentos são opcionais se o sistema em questão
1451já foi estimado e ocupa a posição do "último modelo"; nesse caso o
1452estimador é o mesmo definido anteriormente.
1453
1454Se o sistema em questão tinha aplicado um conjunto de restrições (ver o
1455comando "restrict"), a estimação estará sujeita às restrições
1456especificadas.
1457
1458Se o método de estimação é "sur" ou "3sls" e a opção --iterate tiver
1459sido dada, o estimador será iterado. No caso do SUR, se o procedimento
1460convergir os resultados são estimativas de máxima vesrosimilhança. No
1461entanto, a iteração de Mínimos Quadrados de Três-Fases, geralmente não
1462converge para resultados de informação-completa de máxima
1463verosimilhança. A opção --iterate é ignorada nos outros métodos de
1464estimação.
1465
1466Se tiverem sido escolhidos os estimadores equação-a-equação "ols" ou
1467"tsls", por omissão é aplicada uma correção dos graus de liberdade
1468quando se calcula os erros padrão. Isto pode ser suprimido usando a opção
1469--no-df-corr. Esta opção não tem efeito nos outros estimadores; de
1470qualquer modo não seria aplicada a correção de graus de liberdade.
1471
1472Por omissão, a equação usada no cálculo dos elementos da matriz de
1473covariância das equações cruzadas é
1474
1475  sigma(i,j) = u(i)' * u(j) / T
1476
1477Se tiver sido dada a opção --geomean, a correção de graus de liberdade
1478será aplicada: a equação é
1479
1480  sigma(i,j) = u(i)' * u(j) / sqrt((T - ki) * (T - kj))
1481
1482onde os ks são o número de parâmetros independentes em cada equação.
1483
1484Se tiver sido dada a opção --verbose e ter sido especificado um método
1485iterativo, serão mostrados os detalhes das iterações.
1486
1487# eval Utilities
1488
1489Argumento:  expression
1490Exemplos:   eval x
1491            eval inv(X'X)
1492            eval sqrt($pi)
1493
1494This command makes gretl act like a glorified calculator. The program
1495evaluates expression and prints its value. The argument may be the name of a
1496variable, or something more complicated. In any case, it should be an
1497expression which could stand as the right-hand side of an assignment
1498statement.
1499
1500# fcast Prediction
1501
1502Argumentos: [ observações-iniciais observações-finais ] [ passos-à-frente ] [ nome-de-variável ]
1503Opções:     --dynamic (criar predição dinâmica)
1504            --static (criar predição estática)
1505            --out-of-sample (gerar predição fora-da-amostra)
1506            --no-stats (não mostrar estatísticas de predição)
1507            --quiet (não mostrar nada)
1508            --rolling (ver abaixo)
1509            --plot[=nome-de-ficheiro] (ver abaixo)
1510Exemplos:   fcast 1997:1 2001:4 f1
1511            fcast fit2
1512            fcast 2004:1 2008:3 4 rfcast --rolling
1513
1514Tem que se seguir a um comando de estimação. A predições são geradas
1515para um certo intervalo de observações: se tiverem sido dados
1516observações-iniciais e observações-finais, para esse intervalo (se
1517possível); caso contrário se a opção --out-of-sample tiver sido dada,
1518para observações a seguir ao intervalo onde o modelo foi estimado; caso
1519contrário pelo intervalo de amostragem corrente. Se uma predição
1520fora-da-amostra for pedida mas não haja observações relevantes, será
1521assinalado um erro. Dependendo da natureza do modelo, poderão ser gerados
1522erros padrão; ver abaixo. Ver também abaixo o efeito especial da opção
1523--rolling.
1524
1525Se o último modelo estimado é de uma única equação, então o argumento
1526opcional nome-de-variável tem o seguinte efeito: o valores preditos não
1527são mostrado, mas guardados dentro do conjunto de dados no nome fornecido.
1528Se o último modelo estimado é um sistema de equações, nome-de-variável
1529tem um efeito diverente, nomeadamente a seleção de uma variável endógena
1530específica para a predição (por omissão são produzidas predições para
1531todas as variáveis endógenas). No caso do sistema, ou se não tiver sido
1532dado o nome-de-variável, os valores de predição podem ser obtidos usando
1533o acessor $fcast, e os erros padrão, se disponíveis, pelo $fcse.
1534
1535A escolha entre predições estáticas ou dinâmicas aplica-se apenas no
1536caso de modelos dinâmicos, com processamento autoregressivo de erros ou que
1537incluam um ou mais valores desfasados da variável dependente como
1538regressores. As predições estáticas são um passo à frente, baseadas em
1539valores concretizados no período anterior, enquanto que as predições
1540dinâmicas usam a regra de encadeamento de predição. Por exemplo, se uma
1541predição de y em 2008 requer como entrada um valor de y em 2007, uma
1542predição estática é impossível sem dados reais para 2007. Uma
1543predição dinâmica para 2008 é possível se uma predição anterior poder
1544ser substítuida no y em 2007.
1545
1546Por omissão o normal é produzir uma predição estática para alguma parte
1547do intervalo de predição que abrange o intervalo da amostra onde o modelo
1548foi estimado, e uma predição dinâmica (se relevante) para
1549fora-da-amostra. A opção dynamic chama uma predição dinâmica a partir
1550da date mais cedo possível, e a opção --static chama uma predição
1551estática até para fora-da-amosta.
1552
1553A opção --rolling está atualmente apenas disponível para modelos de um
1554única equação estimados por Mínimos Quadrados (OLS). Quando esta opção
1555é dada as predições são recursivas. Isto é, cada predição é gerada a
1556partir de uma estimativa do modelo dado usando dados de uma ponto de partida
1557fixo (nomeadamente, a partir do início do intervalo da amostra da
1558estimação original) até à data de predição menos k, onde k é o
1559número de passos à frente que têm que ser dados no argumento
1560passos-à-frente. As predições serão sempre dinâmicas se isso for
1561aplicável. Note que o argumento passos-à-frente deve ser dado apenas em
1562conjunto com a opção --rolling.
1563
1564A opção --plot (disponível apenas no caso de estimação de equação
1565única) invoca a produção de um ficheiro de gráfico, que contém a
1566representação gráfica da predição. Quando não é dado o parâmetro
1567nome-de-ficheiro, gretl escreve os comandos gnuplot para um ficheiro com
1568nomes do tipo gpttmp01.plt na diretoria de trabalho de gretl do utilizador
1569(com o número incrementado em gráficos sucessivos). Se o nome-de-ficheiro
1570é acrescentado, a sua extensão é usada para determinar o tipo de ficheiro
1571a ser escrito (.eps para EPS, .pdf para PDF, ou .png para PNG; qualquer
1572outra extensão resulta num ficheiro de script gnuplot). Por exemplo,
1573
1574	fcast --plot=fc.pdf
1575
1576produzirá um gráfico em formato PDF. Serão respeitados caminhos completos
1577para ficheiros, senão os ficheiros são escritos na diretoria de trabalho
1578do gretl.
1579
1580A natureza dos erros padrão de predição (se disponíveis) depende da
1581natureza do modelo e da predição. Para modelos lineares estáticos os
1582erros padrão são determinados usando o método traçado por Davidson e
1583MacKinnon (2004); eles incorporam tanto a incerteza devida aos processos de
1584erro como a incerteza dos parâmetros ( resumidos na matriz de covariância
1585das estimativas dos parâmetros). Para modelos dinâmicos, os erros padrão
1586de predição são apenas calculados no caso de uma predição dinâmica, e
1587eles não incorporam incerteza de parâmetros. Para modelos não-lineares,
1588os erros padrão de predição não estão disponíveis atualmente.
1589
1590Caminho de Menu:    Janela de Modelo, /Análise/Predições...
1591
1592# flush Programming
1593
1594This simple command (no arguments, no options) is intended for use in
1595time-consuming scripts that may be executed via the gretl GUI (it is ignored
1596by the command-line program), to give the user a visual indication that
1597things are moving along and gretl is not "frozen".
1598
1599Ordinarily if you launch a script in the GUI no output is shown until its
1600execution is completed, but the effect of invoking flush is as follows:
1601
1602  On the first invocation, gretl opens a window, displays the output so far,
1603  and appends the message "Processing...".
1604
1605  On subsequent invocations the text shown in the output window is updated,
1606  and a new "processing" message is appended.
1607
1608When execution of the script is completed any remaining output is
1609automatically flushed to the text window.
1610
1611Please note, there is no point in using flush in scripts that take less than
1612(say) 5 seconds to execute. Also note that this command should not be used
1613at a point in the script where there is no further output to be printed, as
1614the "processing" message will then be misleading to the user.
1615
1616The following illustrates the intended use of flush:
1617
1618       set echo off
1619       scalar n = 10
1620       loop i=1..n
1621           # do some time-consuming operation
1622           loop 100 --quiet
1623               a = mnormal(200,200)
1624               b = inv(a)
1625           endloop
1626           # print some results
1627           printf "Iteration %2d done\n", i
1628           if i < n
1629               flush
1630           endif
1631       endloop
1632
1633# foreign Programming
1634
1635Sintaxe:    foreign language=linguagem
1636Opções:     --send-data (pré-carregar o conjunto de dados corrente; ver abaixo)
1637            --quiet (suprimir a saída do programa estrangeiro)
1638
1639Este comando inicia um modo especial no qual se aceita os comandos a serem
1640executados por outro programa. Você sai deste modo com end foreign; onde
1641neste ponto são executados os comandos acumulados.
1642
1643Presentemente são suportados três programas "estrangeiros", GNU R
1644(language=R), Ox de Jurgen Doornik (language=Ox) e GNU Octave
1645(language=Octave). Os nomes de linguagem são reconhecidos sem considerar
1646capitalização.
1647
1648A opção --send-data é válida apenas quando em ligação com R e Octave;
1649tem o efeito de tornar o corrente conjunto de dados de gretl disponível
1650dentro do programa alvo, usando o nome gretldata.
1651
1652	list Rlist = x1 x2 x3
1653	foreign language=R --send-data=Rlist
1654
1655Para detalhes e exemplos ver guia de utilização do Gretl (Capítulo 44).
1656
1657# fractint Statistics
1658
1659Argumentos: série [ ordem ]
1660Opções:     --gph (fazer o teste de Geweke e Porter-Hudak)
1661            --all (fazer ambos os testes)
1662            --quiet (não mostrar resultados)
1663
1664Testa a integração fracional sobre a série especificada ("memória
1665longa"). A hipótese nula é de que a ordem de integração da série é
1666zero. Por omissão é usado o estimador local de Whittle (Robinson, 1995)
1667mas se tiver sido dada a opção --gph será usado o teste GPH (Geweke e
1668Porter-Hudak, 1983). Se a opção --all for dada então serão mostrados os
1669resultados dos dois testes.
1670
1671Para mais detalhes sobre este tipo de testes, ver Phillips e Shimotsu
1672(2004).
1673
1674Se não tiver sido dado o argumento opcional ordem, a ordem para os teste(s)
1675é automaticamente definida como sendo o menor de T/2 e T^0.6.
1676
1677Os resultados podem ser obtidos usando os acessores $test e $pvalue. Estes
1678valores baseiam-se no estimador local de Whittle exceto quando dada a
1679opção --gph.
1680
1681Caminho de Menu:    /Variável/Testes de raiz unitária/Integração fracional
1682
1683# freq Statistics
1684
1685Argumento:  variável
1686Opções:     --nbins=n (especificar o número de classes)
1687            --min=valor-mínimo (especificar o mínimo, ver abaixo)
1688            --binwidth=amplitude (especificar a amplitude das classes, ver abaixo)
1689            --quiet (não mostrar o gráfico)
1690            --normal (testar a distribuição normal)
1691            --gamma (testar a distribuição gama)
1692            --silent (não mostrar nada)
1693            --show-plot (ver abaixo)
1694            --matrix=nome (usar coluna da matriz indicada)
1695Exemplos:   freq x
1696            freq x --normal
1697            freq x --nbins=5
1698            freq x --min=0 --binwidth=0.10
1699
1700Se não forem dadas opções, mostra a distribuição de frequência da
1701série variável (dada por nome ou por número), com o número de classes e
1702respetivo tamanho escolhidos automaticamente.
1703
1704Se tiver sido dada a opção --matrix, a variável (que tem que ser um
1705inteiro) será interpretada com um índice de base 1 que selecciona a coluna
1706da matriz designada.
1707
1708Para controlar a apresentação da distribuição você pode especificar
1709tanto o número de classes ou o valor mínimo e ainda a amplitude das
1710classes, tal como mostrado nos dois últimos exemplos acima. A opção --min
1711define o limite inferior da classe mais à esquerda.
1712
1713Se a opção --normal tiver sido dada, será calculado o teste qui-quadrado
1714para a normalidade de Doornik-Hansen. Se a opção --gamma tiver sido dada,
1715o teste de normalidade será substituído pelo teste não paramétrico de
1716Locke para a hipótese nula de que a variável segue uma distribuição
1717gama; ver Locke (1976), Shapiro e Chen (2001). Note que a parametrização
1718da distribuição gama utilizadada em gretl é (forma, escala).
1719
1720Em modo interactivo, por omissão é apresentado o gráfico da
1721distribuição. A opção --quiet pode ser usada para suprimir isto. Pelo
1722contrário, normalmente não é mostrado o gráfico quando se usa a opção
1723"freq" dentro de uma sequência-de-comandos, mas você pode forçar que seja
1724apresentado usando a opção --show-plot. (Isto não se aplica quando se usa
1725o programa em modo de linha-de-comandos, gretlcli.)
1726
1727A opção --silent suprime toda a saída do programa. Isto apenas faz
1728sentido quando em conjunto com uma das opções de teste de distribuição:
1729a estatística de teste e o seu valor p ficam guardados e podem ser obtidos
1730usando os acessores $test e $pvalue.
1731
1732Caminho de Menu:    /Variável/Distribuição de frequência
1733
1734# function Programming
1735
1736Argumento:  nome-da-função
1737
1738Abre um bloco de declarações no qual é definida a função. Este bloco
1739tem que ser finalizado com end function. Para mais detalhes ver guia de
1740utilização do Gretl (Capítulo 14).
1741
1742# garch Estimation
1743
1744Argumentos: p q ; variável-dependente [ variáveis-independentes ]
1745Opções:     --robust (erros padrão robustos)
1746            --verbose (mostrar detalhes das iterações)
1747            --vcv (mostrar a matriz de covariância)
1748            --nc (não incluir uma constante)
1749            --stdresid (normalizar os resíduos)
1750            --fcp (usar o algoritmo Fiorentini, Calzolari, Panattoni)
1751            --arma-init (parâmetros iniciais da variância a partir de ARMA)
1752Exemplos:   garch 1 1 ; y
1753            garch 1 1 ; y 0 x1 x2 --robust
1754
1755Estima um modelo GARCH (GARCH = Autoregressivo Generalizado de
1756Heterocedastidade Condicional, "Generalized Autoregressive Conditional
1757Heteroskedasticity"), que pode ser um modelo univariado, ou multivariado se
1758especificadas as variáveis-independentes, incluindo as variáveis
1759exógenas. Os valores inteiros p e q (que podem ser dados na forma numérica
1760ou como nomes de variáveis escalares pré-existentes) representam as ordens
1761de desfasamento na equação de variância condicional:
1762
1763  h(t) = a(0) + sum(i=1 to q) a(i)*u(t-i)^2 + sum(j=1 to p) b(j)*h(t-j)
1764
1765Portanto, o parâmetro p representa a ordem Generalizada (ou "AR"), enquanto
1766q representa a ordem normal ARCH (ou "MA"). Se p for não-nulo, q tem
1767também que ser não-nulo senão o modelo fica não-identificado. No
1768entanto, você pode estimar um modelo ARCH normal ao definir q para um valor
1769positivo e p para zero. A soma de p e q não pode ser maior que 5. Note que
1770é automaticamente incluida uma constante na equação da média, exceto se
1771tiver sido dada a opção --nc.
1772
1773Por omissão a estimação de modelos GARCH é feita usando código nativo
1774gretl, mas você também tem a possibilidade de usar o algoritmo de
1775Fiorentini, Calzolari e Panattoni (1996). O primeiro usa o maximizador BFGS
1776enquanto o segundo usa a matriz de informação para maximizar a
1777verosimilhança, com aperfeiçoamento por via da Hessiana.
1778
1779Para este comando estão disponíveis diferentes estimadores da matriz de
1780covariância. Por omissão, usa-se a Hessiana, ou se a opção --robust
1781tiver sido dada, será usada a matriz de covariança QML (White). Outras
1782possibilidades podem ser especificadas usando o comando "set" (por exemplo a
1783matriz de informação, ou o estimador Bollerslev-Wooldridge ).
1784
1785Por omissão, as estimativas dos parâmetros da variância são
1786inicializados usando a variância do erro incondicional da estimação OLS
1787inicial para a constante, e pequenos valores positivos para os coeficientes
1788dos valores anteriores do quadrado do erro e da variância do erro. A
1789opção --arma-init faz com que os valores iniciais destes parâmetros sejam
1790definidos usando inicialmente um modelo ARMA, explorando a relação entre
1791GARCH e ARMA demosntrado no Capítulo 21 do livro de Hamilton, Time Series
1792Analysis. Em alguns casos isto pode melhorar as possibilidades de
1793converência.
1794
1795Os resíduos GARCH e a variância condicional estimada podem ser obtidos
1796como $uhat e $h respectivamente. Por exemplo, para obter a variância
1797condicional:
1798
1799	genr ht = $h
1800
1801Se a opção --stdresid tiver sido dada, os valores $uhat são divididos
1802pela raiz quadrada de h_t.
1803
1804Caminho de Menu:    /Modelo/Série temporal/GARCH
1805
1806# genr Dataset
1807
1808Argumentos: nova-variável = expressão
1809
1810NOTE: this command has undergone numerous changes and enhancements since the
1811following help text was written, so for comprehensive and updated info on
1812this command you'll want to refer to guia de utilização do Gretl
1813(Capítulo 10). On the other hand, this help does not contain anything
1814actually erroneous, so take the following as "you have this, plus more".
1815
1816No contexto apropriado, o nomes; series, scalar e matrix são sinónimos
1817para este comando.
1818
1819Cria novas variáveis, frequentemente a partir de transformações de
1820variáveis já existentes. Ver também os atalhos, "diff", "logs", "lags",
1821"ldiff", "sdiff" e "square". No contexto de uma expressão genr, as
1822variáveis existentes têm que ser referenciadas por nome e não por número
1823ID. A expressão deve ser uma combinação bem construída de nomes de
1824variáveis, constantes, operadores e funções (descrito adiante). Note que
1825detalhes adicionais sobre alguns aspetos deste comando podem ser encontrados
1826em guia de utilização do Gretl (Capítulo 10).
1827
1828Um comando genr pode resultar tanto num escalar como numa série. Por
1829exemplo, a expressão x2 = x * 2 naturalmente resulta numa série se a
1830variável x for uma série e num escalar se x for um escalar. As expressões
1831x = 0 e mx = mean(x) naturalmente retornam escalares. Em alguma
1832circusntâncias você poderá querer ter um resultado escalar expandido numa
1833série ou num vetor. Você pode fazer isso usando series como um "aliás"
1834para o comando genr. Por exemplo, series x = 0 produz uma série em que
1835todos os valores são 0. Você também pode usar scalar como sendo um aliás
1836para genr. Não é possível forçar um resultado do tipo vetor para um
1837escalar mas o uso desta palavra reservada indica que o resultado deve ser um
1838escalar: se não for ocorrerá um erro.
1839
1840Quando uma expressão resulta numa série, o intervalo que será escrito na
1841variável destino depende do actual intervalo de amostragem. É assim
1842possível, definir uma série por troços usando o comando smpl conjugado
1843com genr.
1844
1845Os operadores aritméticos suportados são, por ordem de precedência: ^
1846(potenciação); *, / e % (resto da divisão inteira); + e -.
1847
1848Os operadores Booleanos são (mais uma vez, por ordem de precedência): !
1849(negação), && (E lógico), || (OU lógico), >, <, =, >= (maior ou igual),
1850<= (menor ou igual) e != (diferente). Os operadores Booleanos podem ser
1851usados na construção de variáveis auxiliares ('dummy'): por exemplo (x >
185210) retorna 1 se x > 10, 0 caso contrário.
1853
1854As constantes pré-definidas são pi e NA. Esta última representa um valor
1855omisso: você pode inicializar uma variável como tendo um valor omisso com
1856scalar x = NA.
1857
1858O comando genr suporta uma larga gama de funções matemáticas e
1859estatísticas, incluindo, para além das usuais, várias que são
1860especialmente dedicadas à econometria. Adicionalmente oferece acesso a
1861numerosas variáveis internas que são definidas no decorrer das
1862regressões, testes de hipóteses e outros. Para uma lista de acessores,
1863escrever "help functions".
1864
1865Para além dos operadores e funções mencionados acima, existem alguns usos
1866especiais de "genr":
1867
1868  "genr time" cria uma variável de tendência temporal (1,2,3,...) com o
1869  nome "time". "genr index" faz a mesma coisa exceto em que o nome da
1870  variável é index.
1871
1872  "genr dummy" cria variáveis auxiliares ('dummy') até à periodicidade
1873  dos dados. No caso de dados trimestrais (periodicidade 4), o programa cria
1874  dq1 = 1 para o primeiro trimestre 0 nos outros timestres, dq2 = 1 para o
1875  segundo trimestre e 0 para os outros trimestres, e por aí adiante. No
1876  caso de dados mensais as variáveis auxiliares têm os nomes dm1, dm2, e
1877  por aí adiante. No caso de outras frequências os nomes são dummy_1,
1878  dummy_2, etc.
1879
1880  "genr unitdum" e "genr timedum" criam conjuntos de variáveis auxiliares
1881  especiais para usar com dados de painel. O primeiro codifica para as
1882  seções-cruzadas e o segundo para os períodos temporais das
1883  observações.
1884
1885Nota: No programa de linha-de-comandos, os comandos "genr" que obtenham
1886dados de modelo referem-se sempre ao modelo que foi estimado mais
1887recentemente. Isto também é válido para o programa em ambiente gráfico
1888(GUI), ao se usar "genr" na "consola gretl" ou ao introduzir uma expressão
1889usando "Definir nova variável" no menu Acrescentar na janela principal. No
1890entanto, no GUI, você tem a possibilidade de obter dados a partir de
1891qualquer modelo que esteja disponível numa janela (independentemente se é
1892ou não o modelo mais recente). Isso é feito no menu "Gravar" na janela do
1893modelo.
1894
1895A variável especial obs serve como um índice das observações. Por
1896exemplo genr dum = (obs=15) irá gerar uma variável auxiliar que tem valor
18971 para a observação 15 e 0 para as outras. Você também pode usar esta
1898variável para escolher certas observações por data ou nome. Por exemplo,
1899genr d = (obs>1986:4), genr d = (obs>"2008/04/01"), ou genr d = (obs="CA").
1900Se se usarem datas diárias ou etiquetas neste contexto, elas devem ser
1901indicadas dentro de aspas. Datas trimestrais ou mensais (com um dois-pontos)
1902podem ser usadas sem aspas. Note que no caso de dados de séries temporais
1903anuais, o ano não se distingue sintáticamente de um simples inteiro; como
1904tal, se você quiser comparar observações com obs por ano, você tem que
1905usar a função obsnum para converter o ano para um valor de índice
1906iniciado em 1, tal como em genr d = (obs>obsnum(1986)).
1907
1908Valores escalares podem ser extraídos de uma série no contexto de uma
1909expressão genr, usando a sintaxe varname[obs]. O valor obs pode ser dado
1910por núnmero ou data. Exemplos: x[5], CPI[1996:01]. Para dados diários,
1911deve se usar a forma YYYY/MM/DD, por exemplo, ibm[1970/01/23].
1912
1913Uma observação individual numa série pode ser modificado usando genr.
1914Para fazer isto, uma observação válida numérica ou de data, tem que ser
1915acrescentada dentro de parentesis rectos, ao nome da variável no lado
1916esquerdo da expressão. Por exemplo, genr x[3] = 30 ou genr x[1950:04] =
1917303.7.
1918
1919  Expressão             Comentário
1920  -------                -------
1921  y = x1^3               x1 ao cubo
1922  y = ln((x1+x2)/x3)
1923  z = x>y                z(t) = 1 if x(t) > y(t), caso contrário 0
1924  y = x(-2)              x desfasado 2 períodos
1925  y = x(+2)              x adiantado 2 períodos
1926  y = diff(x)            y(t) = x(t) - x(t-1)
1927  y = ldiff(x)           y(t) = log x(t) - log x(t-1), o rácio de crescimento
1928                         instantâneo de x
1929  y = sort(x)            ordena x por ordem crescente e guarda em y
1930  y = dsort(x)           ordena x por ordem decrescente
1931  y = int(x)             guarda a parte inteira de x em y
1932  y = abs(x)             guarda os valores absolutos de x
1933  y = sum(x)             soma os valores de x excluíndo entradas NA de
1934                         valores omissos
1935  y = cum(x)             acumulado: y(t) = a soma de s=1 a s=t de x(s)
1936  aa = $ess              define aa igual ao Erro da Soma de Quadrados da
1937                         última regressão
1938  x = $coeff(sqft)       obtém o coeficiente estimado da variável sqft da
1939                         última regressão
1940  rho4 = $rho(4)         obtém o coeficiente autoregressivo de quarta-ordem
1941                         do último modelo (assume um modelo ar)
1942  cvx1x2 = $vcv(x1, x2)  obtém a covariância estimada dos coeficientes das
1943                         variáveis x1 e x2 do último modelo
1944  foo = uniform()        variável pseudo-aleatória uniforme no intervalo 0-1
1945  bar = 3 * normal()     variável pseudo-aleatória normal, mu = 0, sigma = 3
1946  samp = ok(x)           = 1 para observações onde x não está ausente.
1947
1948Caminho de Menu:    /Acrescentar/Definir nova variável
1949Acesso alternativo: Menu de contexto da janela principal
1950
1951# gmm Estimation
1952
1953Opções:     --two-step (estimação em duas fases)
1954            --iterate (GMM iterado)
1955            --vcv (mostrar a matriz de covariância)
1956            --verbose (mostrar detalhes das iterações)
1957            --lbfgs (usar L-BFGS-B em vez do normal BFGS)
1958
1959Faz estimação usando o Método dos Momentos Generalizado, 'Generalized
1960Method of Moments' (GMM) com o algoritmo BFGS (Broyden, Fletcher, Goldfarb,
1961Shanno). Você tem que especificar um ou mais comandos para a atualização
1962das quantidades relevantes (tipicamente os resíduos GMM), um ou mais
1963conjuntos das condições, uma matriz inicial dos pesos, e uma listagem dos
1964parâmetros a serem estimados, tudo entre os marcadores gmm e end gmm.
1965Quaisquer opções devem ser acrescentadas à linha end gmm .
1966
1967Por favor veja mais detalhes sobre este comando em guia de utilização do
1968Gretl (Capítulo 27). Aqui apenas ilustramos com um exemplo simples.
1969
1970	gmm e = y - X*b
1971	  orthog e ; W
1972	  weights V
1973	  params b
1974	end gmm
1975
1976No exemplo acima nós assumimos que y e X são matrizes, b é um vetor de
1977tamanho apropriado dos valores dos parâmetros, W é a matriz dos
1978instrumentos, e V é uma matriz adequada de pesos. A declaração
1979
1980	orthog e ; W
1981
1982indica que o vetor dos resíduos e é em princípio ortognal a cada um dos
1983instromentos que compõem as colunas de W.
1984
1985Caminho de Menu:    /Modelo/GMM
1986
1987# gnuplot Graphs
1988
1989Argumentos: variáveis-y variável-x [ variável-auxiliar ]
1990Opções:     --with-lines[=especificação-de-variáveis] (usar linhas, e não pontos)
1991            --with-lp[=especificação-de-variáveis] (usar linhas e pontos)
1992            --with-impulses[=especificação-de-variáveis] (usar linhas verticais)
1993            --time-series (gráfico temporal)
1994            --suppress-fitted (não mostrar a linha ajustada)
1995            --single-yaxis (forçar o uso de apenas um eixo y)
1996            --linear-fit (mostrar o ajustamento por mínimos quadrados)
1997            --inverse-fit (mostrar o ajustamento inverso)
1998            --quadratic-fit (mostrar o ajustamento quadrático)
1999            --cubic-fit (mostrar o ajustamento cúbico)
2000            --loess-fit (mostrar o ajustamento loess)
2001            --semilog-fit (mostrar o ajustamento semilog)
2002            --dummy (ver abaixo)
2003            --matrix=nome (representar as colunas da matriz indicada)
2004            --output=nome-de-ficheiro (enviar a saída para o ficheiro especificado)
2005            --input=nome-de-ficheiro (obter entrada a partir do ficheiro especificado)
2006Exemplos:   gnuplot y1 y2 x
2007            gnuplot x --time-series --with-lines
2008            gnuplot wages educ gender --dummy
2009            gnuplot y x --fit=quadratic
2010            gnuplot y1 y2 x --with-lines=y2
2011
2012As variáveis na lista variáveis-y são representadas contra a variável-x.
2013Para um gráfico de série temporal você pode indicar tempo como sendo a
2014variável-x ou usar a opção --time-series.
2015
2016Por omissão os dados são representados como pontos; isto pode ser alterado
2017com o uso de uma das opções --with-lines, --with-lp ou --with-impulses. Se
2018for representada mais que uma variável no eixo dos y, o efeito destas
2019opções pode ficar confinada a uma subconjunto de variáveis usando o
2020parâmetro especificação-de-variáveis. Isto deve tomar a forma de uma
2021lista separada por vírgulas dos nomes ou números das variáveis a serem
2022representadas por linhas ou impulsos respetivamente. O último exemplo
2023mostrado acima, mostra como fazer um gráfico de y1 e y2 contra x, de modo a
2024que y2 é representada por uma linha, mas y1 é por pontos.
2025
2026Se a opção --dummy tiver sido indicada, terão que ser dadas exatamente
2027três variáveis: uma única variável y, uma variável x, e uma variável
2028variável-auxiliar, uma variável discreta. O efeito é o de representar as
2029variáveis-y contra variável-x com os pontos mostrados com diferentes cores
2030dependendo do valor da variável-auxiliar na respectiva observação.
2031
2032Geralmente, as variáveis-y e variável-x referem-se a séries no conjunto
2033de dados corrente (tanto referenciadas por nome como por número ID). Mas se
2034o nome de uma matriz for indicado com a opção --matrix estes argumentos
2035(que têm que ser dados como valores numéricos) indicam indices de colunas
2036(iniciados em 1) para a matriz fornecida. Assim, por exemplo, se você
2037quiser um gráfico X-Y da coluna 2 da matriz M contra a coluna 1, você deve
2038usar:
2039
2040	gnuplot 2 1 --matrix=M
2041
2042Mostrar a linha de melhor ajuste
2043
2044Em modo interativo o gráfico é apresentado imediatamente. Em modo de
2045sequência de comandos o comportamento por omissão é o de criar um
2046ficheiro de script gnuplot na directoria de trabalho do utilizador, com um
2047nome seguindo o padrão gpttmpN.plt, iniciando com N = 01. Os gráficos
2048podem ser depois gerados usando o programa gnuplot (em MS Windows,
2049wgnuplot). Este comportamento pode ser modificado com o uso da opção
2050--output=nome-de-ficheiro. Esta opção controla o nome do ficheiro usado, e
2051ao mesmo tempo permite-lhe especificar um formato de saída de acordo com a
2052extensão de três letras no nome do ficheiro, sendo: .eps resultante na
2053produção de um ficheiro 'Encapsulated PostScript' (EPS); .pdf produz PDF;
2054.png produz no formato PNG, .emf em formato EMF ('Enhanced MetaFile'), .fig
2055no formato Xfig, e .svg para o formato SVG ('Scalable Vector Graphics'). Se
2056usado o nome de ficheiro "display" o gráfico é apresentado no écran tal
2057como em modo interativo. Se o nome de ficheiro tiver outra qualquer
2058extensão que não as mencionadas, será escrito um ficheiro de script
2059gnuplot.
2060
2061  linear: show the OLS fit regardless of its level of statistical
2062  significance.
2063
2064  none: don't show any fitted line.
2065
2066  inverse, quadratic, cubic, semilog or linlog: show a fitted line based on
2067  a regression of the specified type. By semilog, we mean a regression of
2068  log y on x; the fitted line represents the conditional expectation of y,
2069  obtained by exponentiation. By linlog we mean a regression of y on the log
2070  of x.
2071
2072  loess: show the fit from a robust locally weighted regression (also is
2073  sometimes known as "lowess").
2074
2075Representando uma banda
2076
2077As várias opções de "ajustamento" são aplicáveis apenas nos caso de
2078gráficos de dispersão bivariados e nos de uma única série-temporal. O
2079comportamento por omissão para um gráfico de dispersão é o de mostrar a
2080linha de ajustamento de mínimos quadrados se e só se o coeficiente do
2081declive fôr significativo num nível de 10 porcento. Se a opção
2082--suppress tiver sido dada, não será mostrada a linha ajustada. O
2083comportamento por omissão para um gráfico de série-temporal é o de não
2084mostrar a linha de ajustamento. Se a opção --linear fôr dada, a linha
2085mínimos quadrados será mostrada independentemente de ser significativa ou
2086não. As outras opções de ajustamento (--inverse, --quadratic, --cubic,
2087--loess e --semilog) produzem respetivamente um ajustamento inverso
2088(regressão de y sobre 1/x), um ajustamento quadrático, um ajustamento
2089cúbico, um ajustamento loess e um ajustamento semilog. Loess (também por
2090vezes chamado "lowess") é uma regressão robusta com pesos locais. Por
2091semilog, nós designamos uma regressão do logaritmo de y sobre x (ou
2092tempo); a linha ajustada representa o y esperado condicionalmente, obtido
2093por exponenciação.
2094
2095	        gnuplot y --time-series --band=y,se_y,1.96 --with-lines
2096
2097Uma outra opção está disponível para este comando: a seguir às
2098especificações das variáveis a serem representadas e das opções (caso
2099hajam), você pode acrescentar comandos gnuplot para controlar a aparência
2100do gráfico (por exemplo, para definir o título e/ou as escalas dos eixos).
2101Estes comandos devem ser colocados dentro de chavetas, e cada comando
2102gnuplot tem que ser terminado com um ponto-e-vírgula. Um '\' pode ser usado
2103para continuar uma conjunto de comandos gnuplot por mais que uma linha. Aqui
2104está um exemplo da sintaxe:
2105
2106{ set title 'O Meu Título'; set yrange [0:1000]; }
2107
2108	eval readfile("@gretldir/data/gnuplot/gpcolors.txt")
2109
2110Controlando o resultado
2111
2112??????
2113
2114Especificando unha fonte
2115
2116Podes utilizar a opção --font para especificar uma fonte concreta para o
2117gráfico. O parámetro espfonte deve ter a forma do nome duma fonte, seguida
2118opcionalmente por um número que indique o tamanho em pontos, separado do
2119nome por uma vírgula ou espaço, tudo dentro de aspas, como em
2120
2121	--font="serif,12"
2122
2123Tem em conta que as fontes disponíveis para Gnuplot variam dependendo da
2124plataforma, e se estás escrevendo uma instrução de gráfico que pretendes
2125que seja portável, é melhor restringir o nome da fonte às genéricas sans
2126ou serif.
2127
2128Agregando instruções Gnuplot
2129
2130Depois de escrita uma instrução Gnuplot, ela pode ser seguida da
2131especificação de variáveis a desenhar e do indicador de opção (caso
2132exista), podes agregar instruções literais de Gnuplot para controlar a
2133aparência do gráfico (por exemplo, definindo o título da gráfico e/ou
2134intervalos dos eixos). Estas instruções devem de estar dentro de chavetas,
2135e deves terminar cada instrução Gnuplot com ponto e vírgula. Podes
2136utilizar uma barra invertida para continuar um conjunto de instruções
2137Gnuplot ao longo de mais do que uma linha. Aqui está um exemplo da sintaxe:
2138
2139	{ set title 'O meu Título'; set yrange [0:1000]; }
2140
2141Caminho de Menu:    /Ver/Gráfico das variáveis
2142Acesso alternativo: Menu de contexto na janela principal, botão de gráfico na barra de ferramentas
2143
2144# graphpg Graphs
2145
2146Variantes:  graphpg add
2147            graphpg fontscale value
2148            graphpg show
2149            graphpg free
2150            graphpg --output=filename
2151
2152A "página dos gráficos" de sessão apenas funcionará se você tiver
2153instalado o sistema de produção de texto LaTeX, e puder gerar e visionar
2154documentos PDF ou PostScript.
2155
2156Na janela de sessão por ícones, você pode arrastar até oito gráficos
2157para dentro de um ícone de página de gráficos. Quando você fizer
2158duplo-clique na página de gráficos (ou com o botão direito e selecionar
2159"Mostrar"), será produzida uma página com os gráficos selecionados e
2160apresentada no visionador adequado. A partir deste você poderá imprimir a
2161página.
2162
2163Para limpar a página de gráficos, clicar com o botão direito no seu
2164ícone e selecionar "Limpar".
2165
2166Note que em sistemas diferentes do MS Windows, você pode ter que ajustar as
2167definições dos programas usados para visionar documentos PDF ou
2168PostScript. Isso encontra-se dentro do separador "Programas" na janela de
2169diálogo das Preferências do gretl (a partir do menu Ferramentas da janela
2170principal).
2171
2172Também é possível trabalhar com a página de gráficos a partir se
2173sequência de comandos, ou usando a consola (dentro do programa em ambiente
2174gráfico). São suportados os seguintes comandos e opções:
2175
2176Para acrescentar um gráfico à página de gráficos, dê o comando graphpg
2177add depois de o ter gravado como um gráfico com nome, tal como
2178
2179	grf1 <- gnuplot Y X
2180	graphpg add
2181
2182Para ver a página de gráficos: graphpg show.
2183
2184Para limpar a página de gráficos: graphpg free.
2185
2186Para ajustar a escala da fonte usada na página de gráficos, use graphpg
2187fontscale escala, onde escala é um multiplicador (com o valor 1,0 por
2188omissão). Assim, para tornar a o fonte 50 porcento maior que a por inicial
2189você pode
2190
2191	graphpg fontscale 1.5
2192
2193Para chamar a impressão da página de gráficos para um ficheiro, use a
2194opção --output= mais um nome de ficheiro; o nome do ficheiro deverá ter o
2195sufixo ".pdf", ".ps" ou ".eps". Por exemplo:
2196
2197	graphpg --output="meu_ficheiro.pdf"
2198
2199Neste contexto, por omissão o resultado usa linhas coloridas; para usar
2200padrões ponto/traço em vez de cores, você pode acrescentar a opção
2201--monochrome.
2202
2203# hausman Tests
2204
2205Este teste apenas está disponível após e estimar um modelo de mínimos
2206quadrados (OLS) usando dados de painel (ver também "setobs"). Ele testa o
2207modelo de amostragem simples ("pooled") contra as alternativas principais,
2208os modelos de efeitos fixos e efeitos aleatórios.
2209
2210O modelo de efeitos fixos permite variar a interseção da regressão ao
2211longo das unidades de seção cruzada. Uma estatística teste-F é
2212apresentada segundo a hipótese nula de que as interseções não diferem. O
2213modelo de efeitos aleatórios decompõe a variância dos resíduos em duas
2214partes, uma parte específica à unidade de seção cruzada e outra
2215específica para a observação em particular. (Este estimador pode ser
2216calculado apenas se o número de unidades de seção cruzada nos dados
2217exceder o número de parâmetros a serem estimados.) A estatística de teste
2218Breusch-Pagan LM, testa a hipótese nula de que o estimador mínimos
2219quadrados de amostragem ("pooled") é adequado em oposição ao da
2220alternativa de efeitos aleatórios.
2221
2222O modelo mínimos quadrados de amostragem ("pooled") pode ser rejeitado
2223contra ambas as alternativas, efeitos fixos e efeitos aleatórios. Desde que
2224o erro específico por unidade ou por grupo seja não correlacionado com as
2225variáveis independentes, o estimador de efeitos aleatórios é mais
2226eficiente do que o estimador de efeitos fixos; caso contrário o estimador
2227de efeitos aleatórios é inconsistente e o estimador de efeitos fixos será
2228preferido. A hipótese nula para o teste de Hausman é de que o erro
2229específico de grupo não é tão correlacionado (e como tal o modelo de
2230efeitos aleatórios é preferível). Um valor p baixo para este teste conta
2231contra o modelo de efeitos aleatórios e a favor do modelo de efeitos fixos.
2232
2233Caminho de Menu:    Janela do modelo, /Testes/Diagnósticos de Painel
2234
2235# heckit Estimation
2236
2237Argumentos: variável-dependente variáveis-independentes ; equação de seleção
2238Opções:     --quiet (suprimir a escrita de resultados)
2239            --robust (erros padrão QML)
2240            --two-step (efetuar estimação de dois passos)
2241            --vcv (mostrar a matriz de covariância)
2242            --verbose (mostrar saídas adicionais)
2243Exemplos:   heckit y 0 x1 x2 ; ys 0 x3 x4
2244            Ver tambémheckit.inp
2245
2246Seleção do modelo de tipo Heckman. Na especificação, a lista antes do
2247ponto-e-vírgula representa a equação do resultado. A variável dependente
2248na equação de seleção (ys no exemplo acima) tem que ser uma variável
2249binária.
2250
2251Por omissão, os parâmetros são estimados por máxima verosimilhança. A
2252matriz de covariância dos parâmetros é calculada usando a inversão
2253negativa da Hessiana. Se for desejável a estimação, de dois passos, use a
2254opção --two-step. Neste caso, a matriz de covariância dos parâmetros da
2255equação resultante é adequadamente ajustada de acordo com Heckman (1979).
2256
2257Repare que na estimação de Máxima Verosimilhança (ML) é usada uma
2258aproximação numérica da Hessiana; isto pode levar a inexatidões na
2259matriz de covariância estimada se a escala das variáveis explanatórias
2260for para alguns dos coeficientes estimados muito pequena em valor absoluto.
2261Este problema pode ser abordado em versões futuras; por agora, como
2262solução temporária, pode-se re-escalar a variável ou variáveis
2263explanatórias que estão a causar problemas.
2264
2265Caminho de Menu:    /Modelo/Variável dependente limitada/Heckit...
2266
2267# help Utilities
2268
2269Variantes:  help
2270            help functions
2271            help command
2272            help function
2273Opção:      --func (select functions help)
2274
2275If no arguments are given, prints a list of available commands. If the
2276single argument "functions" is given, prints a list of available functions
2277(see "genr").
2278
2279help command describes command (e.g. help smpl). help function describes
2280function (e.g. help ldet). Some functions have the same names as related
2281commands (e.g. diff): in that case the default is to print help for the
2282command, but you can get help on the function by using the --func option.
2283
2284Caminho de Menu:    /Help
2285
2286# hsk Estimation
2287
2288Argumentos: depvar indepvars
2289Opções:     --no-squares (see below)
2290            --vcv (print covariance matrix)
2291
2292This command is applicable where heteroskedasticity is present in the form
2293of an unknown function of the regressors which can be approximated by a
2294quadratic relationship. In that context it offers the possibility of
2295consistent standard errors and more efficient parameter estimates as
2296compared with OLS.
2297
2298The procedure involves (a) OLS estimation of the model of interest, followed
2299by (b) an auxiliary regression to generate an estimate of the error
2300variance, then finally (c) weighted least squares, using as weight the
2301reciprocal of the estimated variance.
2302
2303In the auxiliary regression (b) we regress the log of the squared residuals
2304from the first OLS on the original regressors and their squares (by
2305default), or just on the original regressors (if the --no-squares option is
2306given). The log transformation is performed to ensure that the estimated
2307variances are all non-negative. Call the fitted values from this regression
2308u^*. The weight series for the final WLS is then formed as 1/exp(u^*).
2309
2310Caminho de Menu:    /Model/Other linear models/Heteroskedasticity corrected
2311
2312# hurst Statistics
2313
2314Argumento:  series
2315
2316Calculates the Hurst exponent (a measure of persistence or long memory) for
2317a time-series variable having at least 128 observations.
2318
2319The Hurst exponent is discussed by Mandelbrot. In theoretical terms it is
2320the exponent, H, in the relationship
2321
2322  RS(x) = an^H
2323
2324where RS is the "rescaled range" of the variable x in samples of size n and
2325a is a constant. The rescaled range is the range (maximum minus minimum) of
2326the cumulated value or partial sum of x over the sample period (after
2327subtraction of the sample mean), divided by the sample standard deviation.
2328
2329As a reference point, if x is white noise (zero mean, zero persistence) then
2330the range of its cumulated "wandering" (which forms a random walk), scaled
2331by the standard deviation, grows as the square root of the sample size,
2332giving an expected Hurst exponent of 0.5. Values of the exponent
2333significantly in excess of 0.5 indicate persistence, and values less than
23340.5 indicate anti-persistence (negative autocorrelation). In principle the
2335exponent is bounded by 0 and 1, although in finite samples it is possible to
2336get an estimated exponent greater than 1.
2337
2338In gretl, the exponent is estimated using binary sub-sampling: we start with
2339the entire data range, then the two halves of the range, then the four
2340quarters, and so on. For sample sizes smaller than the data range, the RS
2341value is the mean across the available samples. The exponent is then
2342estimated as the slope coefficient in a regression of the log of RS on the
2343log of sample size.
2344
2345Caminho de Menu:    /Variable/Hurst exponent
2346
2347# if Programming
2348
2349Flow control for command execution. Three sorts of construction are
2350supported, as follows.
2351
2352	# simple form
2353	if condition
2354	    commands
2355	endif
2356
2357	# two branches
2358	if condition
2359	    commands1
2360	else
2361	    commands2
2362        endif
2363
2364	# three or more branches
2365	if condition1
2366	    commands1
2367	elif condition2
2368	    commands2
2369	else
2370	    commands3
2371	endif
2372
2373"condition" must be a Boolean expression, for the syntax of which see
2374"genr". More than one "elif" block may be included. In addition, if ...
2375endif blocks may be nested.
2376
2377# include Programming
2378
2379Argumento:  filename
2380Exemplos:   include myfile.inp
2381            include sols.gfn
2382
2383Intended for use in a command script, primarily for including definitions of
2384functions. Executes the commands in filename then returns control to the
2385main script. To include a packaged function, be sure to include the filename
2386extension.
2387
2388See also "run".
2389
2390# info Dataset
2391
2392Prints out any supplementary information stored with the current datafile.
2393
2394Caminho de Menu:    /Data/Dataset info
2395Acesso alternativo: Data browser windows
2396
2397# install Utilities
2398
2399Argumento:  pkgname
2400Opções:     --local (install from local file)
2401            --remove (see below)
2402            --purge (see below)
2403Exemplos:   install armax
2404            install felogit.gfn
2405            install /path/to/myfile.gfn --local
2406            install http://foo.bar.net/gretl/myfile.gfn
2407
2408Installer for gretl function packages (gfn or zip files).
2409
2410If this command is given the "plain" name of a gretl function package (as in
2411the first two examples) the action is to download the specified package from
2412the gretl server and install it on the local machine. In this case it is not
2413necessary to supply a filename extension.
2414
2415If the --local option is given, the pkgname argument should be the path to
2416an uninstalled package file on the local machine, with the correct
2417extension. The action is to copy the file into place (gfn), or unzip it into
2418place (zip), "into place" meaning where the "include" command will find it.
2419
2420When no option is given, if pkgname begins with http://, the effect is to
2421download a package file from a specified server and install it locally.
2422
2423With the --remove or --purge option the inverse operation is performed; that
2424is, an installed package is uninstalled. If just --remove is given, the
2425specified package is unloaded from memory and is removed from the GUI menu
2426to which it is attached, if any. If the --purge option is given then in
2427addition to the actions just mentioned the package file is deleted. (If the
2428package is installed in its own subdirectory, the whole subdirectory is
2429deleted.)
2430
2431Caminho de Menu:    /Tools/Function packages/On server
2432
2433# intreg Estimation
2434
2435Argumentos: minvar maxvar indepvars
2436Opções:     --quiet (suppress printing of results)
2437            --verbose (print details of iterations)
2438            --robust (robust standard errors)
2439            --cluster=clustvar (see "logit" for explanation)
2440Exemplos:   intreg lo hi const x1 x2
2441            Ver tambémwtp.inp
2442
2443Estimates an interval regression model. This model arises when the dependent
2444variable is imperfectly observed for some (possibly all) observations. In
2445other words, the data generating process is assumed to be
2446
2447  y* = x b + u
2448
2449but we only observe m <= y* <= M (the interval may be left- or
2450right-unbounded). Note that for some observations m may equal M. The
2451variables minvar and maxvar must contain NAs for left- and right-unbounded
2452observations, respectively.
2453
2454The model is estimated by maximum likelihood, assuming normality of the
2455disturbance term.
2456
2457By default, standard errors are computed using the negative inverse of the
2458Hessian. If the --robust flag is given, then QML or Huber-White standard
2459errors are calculated instead. In this case the estimated covariance matrix
2460is a "sandwich" of the inverse of the estimated Hessian and the outer
2461product of the gradient.
2462
2463Caminho de Menu:    /Model/Limited dependent variable/Interval regression
2464
2465# join Dataset
2466
2467Argumentos: filename varname
2468Opções:     --data=column-name (see below)
2469            --filter=expression (see below)
2470            --ikey=inner-key (see below)
2471            --okey=outer-key (see below)
2472            --aggr=method (see below)
2473            --tkey=column-name,format-string (see below)
2474            --verbose (report on progress)
2475
2476This command imports a data series from the source filename (which must be
2477either a delimited text data file or a "native" gretl data file) under the
2478name varname. For details please see guia de utilização do Gretl
2479(Capítulo 7); here we just give a brief summary of the available options.
2480
2481The --data option can be used to specify the column heading of the data in
2482the source file, if this differs from the name by which the data should be
2483known in gretl.
2484
2485The --filter option can be used to specify a criterion for filtering the
2486source data (that is, selecting a subset of observations).
2487
2488The --ikey and --okey options can be used to specify a mapping between
2489observations in the current dataset and observations in the source data (for
2490example, individuals can be matched against the household to which they
2491belong).
2492
2493The --aggr option is used when the mapping between observations in the
2494current dataset and the source is not one-to-one.
2495
2496The --tkey option is applicable only when the current dataset has a
2497time-series structure. It can be used to specify the name of a column
2498containing dates to be matched to the dataset and/or the format in which
2499dates are represented in that column.
2500
2501See also "append" for simpler joining operations.
2502
2503# kpss Tests
2504
2505Argumentos: order varlist
2506Opções:     --trend (include a trend)
2507            --seasonals (include seasonal dummies)
2508            --verbose (print regression results)
2509            --quiet (suppress printing of results)
2510            --difference (use first difference of variable)
2511Exemplos:   kpss 8 y
2512            kpss 4 x1 --trend
2513
2514For use of this command with panel data please see the final section in this
2515entry.
2516
2517Computes the KPSS test (Kwiatkowski et al, Journal of Econometrics, 1992)
2518for stationarity, for each of the specified variables (or their first
2519difference, if the --difference option is selected). The null hypothesis is
2520that the variable in question is stationary, either around a level or, if
2521the --trend option is given, around a deterministic linear trend.
2522
2523The order argument determines the size of the window used for Bartlett
2524smoothing. If a negative value is given this is taken as a signal to use an
2525automatic window size of 4(T/100)^0.25, where T is the sample size.
2526
2527If the --verbose option is chosen the results of the auxiliary regression
2528are printed, along with the estimated variance of the random walk component
2529of the variable.
2530
2531The critical values shown for the test statistic are based on response
2532surfaces estimated in the manner set out by Sephton (Economics Letters,
25331995), which are more accurate for small samples than the values given in
2534the original KPSS article. When the test statistic lies between the 10
2535percent and 1 percent critical values a p-value is shown; this is obtained
2536by linear interpolation and should not be taken too literally. See the
2537"kpsscrit" function for a means of obtaining these critical values
2538programmatically.
2539
2540Panel data
2541
2542When the kpss command is used with panel data, to produce a panel unit root
2543test, the applicable options and the results shown are somewhat different.
2544While you may give a list of variables for testing in the regular
2545time-series case, with panel data only one variable may be tested per
2546command. And the --verbose option has a different meaning: it produces a
2547brief account of the test for each individual time series (the default being
2548to show only the overall result).
2549
2550When possible, the overall test (null hypothesis: the series in question is
2551stationary for all the panel units) is calculated using the method of Choi
2552(Journal of International Money and Finance, 2001). This is not always
2553straightforward, the difficulty being that while the Choi test is based on
2554the p-values of the tests on the individual series, we do not currently have
2555a means of calculating p-values for the KPSS test statistic; we must rely on
2556a few critical values.
2557
2558If the test statistic for a given series falls between the 10 percent and 1
2559percent critical values, we are able to interpolate a p-value. But if the
2560test falls short of the 10 percent value, or exceeds the 1 percent value, we
2561cannot interpolate and can at best place a bound on the global Choi test. If
2562the individual test statistic falls short of the 10 percent value for some
2563units but exceeds the 1 percent value for others, we cannot even compute a
2564bound for the global test.
2565
2566Caminho de Menu:    /Variable/Unit root tests/KPSS test
2567
2568# labels Dataset
2569
2570Variantes:  labels [ varlist ]
2571            labels --to-file=filename
2572            labels --from-file=filename
2573            labels --delete
2574
2575In the first form, prints out the informative labels (if present) for the
2576series in varlist, or for all series in the dataset if varlist is not
2577specified.
2578
2579With the option --to-file, writes to the named file the labels for all
2580series in the dataset, one per line. If no labels are present an error is
2581flagged; if some series have labels and others do not, a blank line is
2582printed for series with no label.
2583
2584With the option --from-file, reads the specified file (which should be plain
2585text) and assigns labels to the series in the dataset, reading one label per
2586line and taking blank lines to indicate blank labels.
2587
2588The --delete option does what you'd expect: it removes all the series labels
2589from the dataset.
2590
2591Caminho de Menu:    /Data/Variable labels
2592
2593# lad Estimation
2594
2595Argumentos: depvar indepvars
2596Opção:      --vcv (print covariance matrix)
2597
2598Calculates a regression that minimizes the sum of the absolute deviations of
2599the observed from the fitted values of the dependent variable. Coefficient
2600estimates are derived using the Barrodale-Roberts simplex algorithm; a
2601warning is printed if the solution is not unique.
2602
2603Standard errors are derived using the bootstrap procedure with 500 drawings.
2604The covariance matrix for the parameter estimates, printed when the --vcv
2605flag is given, is based on the same bootstrap.
2606
2607Caminho de Menu:    /Model/Robust estimation/Least Absolute Deviation
2608
2609# lags Transformations
2610
2611Argumentos: [ order ; ] laglist
2612Exemplos:   lags x y
2613            lags 12 ; x y
2614
2615Creates new series which are lagged values of each of the series in varlist.
2616By default the number of lags created equals the periodicity of the data.
2617For example, if the periodicity is 4 (quarterly), the command "lags x"
2618creates
2619
2620	x_1 = x(t-1)
2621	x_2 = x(t-2)
2622	x_3 = x(t-3)
2623	x_4 = x(t-4)
2624
2625The number of lags created can be controlled by the optional first parameter
2626(which, if present, must be followed by a semicolon).
2627
2628Caminho de Menu:    /Add/Lags of selected variables
2629
2630# ldiff Transformations
2631
2632Argumento:  varlist
2633
2634The first difference of the natural log of each series in varlist is
2635obtained and the result stored in a new series with the prefix ld_. Thus
2636"ldiff x y" creates the new variables
2637
2638	ld_x = log(x) - log(x(-1))
2639	ld_y = log(y) - log(y(-1))
2640
2641Caminho de Menu:    /Add/Log differences of selected variables
2642
2643# leverage Tests
2644
2645Opções:     --save (save variables)
2646            --quiet (don't print results)
2647
2648Must follow an "ols" command. Calculates the leverage (h, which must lie in
2649the range 0 to 1) for each data point in the sample on which the previous
2650model was estimated. Displays the residual (u) for each observation along
2651with its leverage and a measure of its influence on the estimates, uh/(1 -
2652h). "Leverage points" for which the value of h exceeds 2k/n (where k is the
2653number of parameters being estimated and n is the sample size) are flagged
2654with an asterisk. For details on the concepts of leverage and influence see
2655Davidson and MacKinnon (1993), Chapter 2.
2656
2657DFFITS values are also computed: these are "studentized residuals"
2658(predicted residuals divided by their standard errors) multiplied by
2659sqrt[h/(1 - h)]. For discussions of studentized residuals and DFFITS see
2660chapter 12 of Maddala's Introduction to Econometrics or Belsley, Kuh and
2661Welsch (1980).
2662
2663Briefly, a "predicted residual" is the difference between the observed value
2664of the dependent variable at observation t, and the fitted value for
2665observation t obtained from a regression in which that observation is
2666omitted (or a dummy variable with value 1 for observation t alone has been
2667added); the studentized residual is obtained by dividing the predicted
2668residual by its standard error.
2669
2670If the --save flag is given with this command, then the leverage, influence
2671and DFFITS values are added to the current data set. In that context the
2672--quiet flag may be used to suppress the printing of results.
2673
2674After execution, the $test accessor returns the cross-validation criterion,
2675which is defined as the sum of squared deviations of the dependent variable
2676from its forecast value, the forecast for each observation being based on a
2677sample from which that observation is excluded. (This is known as the
2678leave-one-out estimator). For a broader discussion of the cross-validation
2679criterion, see Davidson and MacKinnon's Econometric Theory and Methods,
2680pages 685-686, and the references therein.
2681
2682Caminho de Menu:    Model window, /Tests/Influential observations
2683
2684# levinlin Tests
2685
2686Argumentos: order series
2687Opções:     --nc (test without a constant)
2688            --ct (with constant and trend)
2689            --quiet (suppress printing of results)
2690Exemplos:   levinlin 0 y
2691            levinlin 2 y --ct
2692            levinlin {2,2,3,3,4,4} y
2693
2694Carries out the panel unit-root test described by Levin, Lin and Chu (2002).
2695The null hypothesis is that all of the individual time series exhibit a unit
2696root, and the alternative is that none of the series has a unit root. (That
2697is, a common AR(1) coefficient is assumed, although in other respects the
2698statistical properties of the series are allowed to vary across
2699individuals.)
2700
2701By default the test ADF regressions include a constant; to suppress the
2702constant use the --nc option, or to add a linear trend use the --ct option.
2703(See the "adf" command for explanation of ADF regressions.)
2704
2705The (non-negative) order for the test (governing the number of lags of the
2706dependent variable to include in the ADF regressions) may be given in either
2707of two forms. If a scalar value is given, this is applied to all the
2708individuals in the panel. The alternative is to provide a matrix containing
2709a specific lag order for each individual; this must be a vector with as many
2710elements as there are individuals in the current sample range. Such a matrix
2711can be specified by name, or constructed using braces as illustrated in the
2712last example above.
2713
2714Caminho de Menu:    /Variable/Unit root tests/Levin-Lin-Chu test
2715
2716# logistic Estimation
2717
2718Argumentos: depvar indepvars
2719Opções:     --ymax=value (specify maximum of dependent variable)
2720            --vcv (print covariance matrix)
2721Exemplos:   logistic y const x
2722            logistic y const x --ymax=50
2723
2724Logistic regression: carries out an OLS regression using the logistic
2725transformation of the dependent variable,
2726
2727  log(y/(y* - y))
2728
2729The dependent variable must be strictly positive. If all its values lie
2730between 0 and 1, the default is to use a y^* value (the asymptotic maximum
2731of the dependent variable) of 1; if its values lie between 0 and 100, the
2732default y^* is 100.
2733
2734If you wish to set a different maximum, use the --ymax option. Note that the
2735supplied value must be greater than all of the observed values of the
2736dependent variable.
2737
2738The fitted values and residuals from the regression are automatically
2739transformed using
2740
2741  y = y* / (1 + exp(-x))
2742
2743where x represents either a fitted value or a residual from the OLS
2744regression using the transformed dependent variable. The reported values are
2745therefore comparable with the original dependent variable.
2746
2747Note that if the dependent variable is binary, you should use the "logit"
2748command instead.
2749
2750Caminho de Menu:    /Model/Limited dependent variable/Logistic
2751
2752# logit Estimation
2753
2754Argumentos: depvar indepvars
2755Opções:     --robust (robust standard errors)
2756            --cluster=clustvar (clustered standard errors)
2757            --multinomial (estimate multinomial logit)
2758            --vcv (print covariance matrix)
2759            --verbose (print details of iterations)
2760            --p-values (show p-values instead of slopes)
2761
2762If the dependent variable is a binary variable (all values are 0 or 1)
2763maximum likelihood estimates of the coefficients on indepvars are obtained
2764via the Newton-Raphson method. As the model is nonlinear the slopes depend
2765on the values of the independent variables. By default the slopes with
2766respect to each of the independent variables are calculated (at the means of
2767those variables) and these slopes replace the usual p-values in the
2768regression output. This behavior can be suppressed my giving the --p-values
2769option. The chi-square statistic tests the null hypothesis that all
2770coefficients are zero apart from the constant.
2771
2772By default, standard errors are computed using the negative inverse of the
2773Hessian. If the --robust flag is given, then QML or Huber-White standard
2774errors are calculated instead. In this case the estimated covariance matrix
2775is a "sandwich" of the inverse of the estimated Hessian and the outer
2776product of the gradient; see chapter 10 of Davidson and MacKinnon (2004).
2777But if the --cluster option is given, then "cluster-robust" standard errors
2778are produced; see guia de utilização do Gretl (Capítulo 22) for details.
2779
2780If the dependent variable is not binary but is discrete, then by default it
2781is interpreted as an ordinal response, and Ordered Logit estimates are
2782obtained. However, if the --multinomial option is given, the dependent
2783variable is interpreted as an unordered response, and Multinomial Logit
2784estimates are produced. (In either case, if the variable selected as
2785dependent is not discrete an error is flagged.) In the multinomial case, the
2786accessor $mnlprobs is available after estimation, to get a matrix containing
2787the estimated probabilities of the outcomes at each observation
2788(observations in rows, outcomes in columns).
2789
2790If you want to use logit for analysis of proportions (where the dependent
2791variable is the proportion of cases having a certain characteristic, at each
2792observation, rather than a 1 or 0 variable indicating whether the
2793characteristic is present or not) you should not use the "logit" command,
2794but rather construct the logit variable, as in
2795
2796	series lgt_p = log(p/(1 - p))
2797
2798and use this as the dependent variable in an OLS regression. See chapter 12
2799of Ramanathan (2002).
2800
2801Caminho de Menu:    /Model/Limited dependent variable/Logit
2802
2803# logs Transformations
2804
2805Argumento:  varlist
2806
2807The natural log of each of the series in varlist is obtained and the result
2808stored in a new series with the prefix l_ ("el" underscore). For example,
2809"logs x y" creates the new variables l_x = ln(x) and l_y = ln(y).
2810
2811Caminho de Menu:    /Add/Logs of selected variables
2812
2813# loop Programming
2814
2815Argumento:  control
2816Opções:     --progressive (enable special forms of certain commands)
2817            --verbose (report details of genr commands)
2818            --quiet (do not report number of iterations performed)
2819Exemplos:   loop 1000
2820            loop 1000 --progressive
2821            loop while essdiff > .00001
2822            loop i=1991..2000
2823            loop for (r=-.99; r<=.99; r+=.01)
2824            loop foreach i xlist
2825
2826This command opens a special mode in which the program accepts commands to
2827be executed repeatedly. You exit the mode of entering loop commands with
2828"endloop": at this point the stacked commands are executed.
2829
2830The parameter "control" may take any of five forms, as shown in the
2831examples: an integer number of times to repeat the commands within the loop;
2832"while" plus a boolean condition; a range of integer values for index
2833variable; "for" plus three expressions in parentheses, separated by
2834semicolons (which emulates the for statement in the C programming language);
2835or "foreach" plus an index variable and a list.
2836
2837See guia de utilização do Gretl (Capítulo 13) for further details and
2838examples. The effect of the --progressive option (which is designed for use
2839in Monte Carlo simulations) is explained there. Not all gretl commands may
2840be used within a loop; the commands available in this context are also set
2841out there.
2842
2843# mahal Statistics
2844
2845Argumento:  varlist
2846Opções:     --quiet (don't print anything)
2847            --save (add distances to the dataset)
2848            --vcv (print covariance matrix)
2849
2850Computes the Mahalanobis distances between the series in varlist. The
2851Mahalanobis distance is the distance between two points in a k-dimensional
2852space, scaled by the statistical variation in each dimension of the space.
2853For example, if p and q are two observations on a set of k variables with
2854covariance matrix C, then the Mahalanobis distance between the observations
2855is given by
2856
2857  sqrt((p - q)' * C-inverse * (p - q))
2858
2859where (p - q) is a k-vector. This reduces to Euclidean distance if the
2860covariance matrix is the identity matrix.
2861
2862The space for which distances are computed is defined by the selected
2863variables. For each observation in the current sample range, the distance is
2864computed between the observation and the centroid of the selected variables.
2865This distance is the multidimensional counterpart of a standard z-score, and
2866can be used to judge whether a given observation "belongs" with a group of
2867other observations.
2868
2869If the --vcv option is given, the covariance matrix and its inverse are
2870printed. If the --save option is given, the distances are saved to the
2871dataset under the name mdist (or mdist1, mdist2 and so on if there is
2872already a variable of that name).
2873
2874Caminho de Menu:    /View/Mahalanobis distances
2875
2876# makepkg Programming
2877
2878Argumento:  filename
2879Opções:     --index (write auxiliary index file)
2880            --translations (write auxiliary strings file)
2881
2882Supports creation of a gretl function package via the command line. The mode
2883of operation of this command depends on the extension of filename, which
2884must be either .gfn or .zip.
2885
2886Gfn mode
2887
2888Writes a gfn file. It is assumed that a package specification file, with the
2889same basename as filename but with the extension .spec, is accessible, along
2890with any auxiliary files that it references. It is also assumed that all the
2891functions to be packaged have been read into memory.
2892
2893Zip mode
2894
2895Writes a zip package file (gfn plus other materials). If a gfn file of the
2896same basename as filename is found, it forms the basis of the zip package.
2897If no gfn file is found, the program first attempts to build the gfn, as
2898described above.
2899
2900Gfn options
2901
2902The option flags support the writing of auxiliary files, intended for use
2903with gretl "addons". The index file is a short XML document containing basic
2904information about the package; it has the same basename as the package and
2905the extension .xml. The translations file contains strings from the package
2906that may be suitable for translation, in C format; for package foo this file
2907is named foo-i18n.c. These files are not produced if the command is
2908operating in zip mode and a pre-existing gfn file is used.
2909
2910For details on all of this, see the the Gretl Function Package Guide.
2911
2912Caminho de Menu:    /Tools/Function packages/New package
2913
2914# markers Dataset
2915
2916Variantes:  markers --to-file=filename
2917            markers --from-file=filename
2918            markers --delete
2919
2920With the option --to-file, writes to the named file the observation marker
2921strings from the current dataset, one per line. If no such strings are
2922present an error is flagged.
2923
2924With the option --from-file, reads the specified file (which should be plain
2925text) and assigns observation markers to the rows in the dataset, reading
2926one marker per line. In general there should be at least as many markers in
2927the file as observations in the dataset, but if the dataset is a panel it is
2928also acceptable if the number of markers in the file matches the number of
2929cross-sectional units (in which case the markers are repeated for each time
2930period.)
2931
2932The --delete option does what you'd expect: it removes the observation
2933marker strings from the dataset.
2934
2935Caminho de Menu:    /Data/Observation markers
2936
2937# meantest Tests
2938
2939Argumentos: series1 series2
2940Opção:      --unequal-vars (assume variances are unequal)
2941
2942Calculates the t statistic for the null hypothesis that the population means
2943are equal for the variables series1 and series2, and shows its p-value.
2944
2945By default the test statistic is calculated on the assumption that the
2946variances are equal for the two variables. With the --unequal-vars option
2947the variances are assumed to be different; in this case the degrees of
2948freedom for the test statistic are approximated as per Satterthwaite (1946).
2949
2950Caminho de Menu:    /Tools/Test statistic calculator
2951
2952# mle Estimation
2953
2954Argumentos: log-likelihood function [ derivatives ]
2955Opções:     --quiet (don't show estimated model)
2956            --vcv (print covariance matrix)
2957            --hessian (base covariance matrix on the Hessian)
2958            --robust (QML covariance matrix)
2959            --verbose (print details of iterations)
2960            --no-gradient-check (see below)
2961            --lbfgs (use L-BFGS-B instead of regular BFGS)
2962Exemplos:   weibull.inp
2963
2964Performs Maximum Likelihood (ML) estimation using either the BFGS (Broyden,
2965Fletcher, Goldfarb, Shanno) algorithm or Newton's method. The user must
2966specify the log-likelihood function. The parameters of this function must be
2967declared and given starting values (using the "genr" command) prior to
2968estimation. Optionally, the user may specify the derivatives of the
2969log-likelihood function with respect to each of the parameters; if
2970analytical derivatives are not supplied, a numerical approximation is
2971computed.
2972
2973Simple example: Suppose we have a series X with values 0 or 1 and we wish to
2974obtain the maximum likelihood estimate of the probability, p, that X = 1.
2975(In this simple case we can guess in advance that the ML estimate of p will
2976simply equal the proportion of Xs equal to 1 in the sample.)
2977
2978The parameter p must first be added to the dataset and given an initial
2979value. For example, scalar p = 0.5.
2980
2981We then construct the MLE command block:
2982
2983	mle loglik = X*log(p) + (1-X)*log(1-p)
2984	  deriv p = X/p - (1-X)/(1-p)
2985	end mle
2986
2987The first line above specifies the log-likelihood function. It starts with
2988the keyword mle, then a dependent variable is specified and an expression
2989for the log-likelihood is given (using the same syntax as in the "genr"
2990command). The next line (which is optional) starts with the keyword deriv
2991and supplies the derivative of the log-likelihood function with respect to
2992the parameter p. If no derivatives are given, you should include a statement
2993using the keyword params which identifies the free parameters: these are
2994listed on one line, separated by spaces and can be either scalars, or
2995vectors, or any combination of the two. For example, the above could be
2996changed to:
2997
2998	mle loglik = X*log(p) + (1-X)*log(1-p)
2999	  params p
3000	end mle
3001
3002in which case numerical derivatives would be used.
3003
3004Note that any option flags should be appended to the ending line of the MLE
3005block.
3006
3007By default, estimated standard errors are based on the Outer Product of the
3008Gradient. If the --hessian option is given, they are instead based on the
3009negative inverse of the Hessian (which is approximated numerically). If the
3010--robust option is given, a QML estimator is used (namely, a sandwich of the
3011negative inverse of the Hessian and the covariance matrix of the gradient).
3012
3013If you supply analytical derivatives, by default gretl runs a numerical
3014check on their plausibility. Occasionally this may produce false positives,
3015instances where correct derivatives appear to be wrong and estimation is
3016refused. To counter this, or to achieve a little extra speed, you can give
3017the option --no-gradient-check. Obviously, you should do this only if you
3018are quite confident that the gradient you have specified is right.
3019
3020For a much more in-depth description of "mle", please refer to guia de
3021utilização do Gretl (Capítulo 26).
3022
3023Caminho de Menu:    /Model/Maximum likelihood
3024
3025# modeltab Utilities
3026
3027Variantes:  modeltab add
3028            modeltab show
3029            modeltab free
3030            modeltab --output=filename
3031
3032Manipulates the gretl "model table". See guia de utilização do Gretl
3033(Capítulo 3) for details. The sub-commands have the following effects:
3034"add" adds the last model estimated to the model table, if possible; "show"
3035displays the model table in a window; and "free" clears the table.
3036
3037To call for printing of the model table, use the flag --output= plus a
3038filename. If the filename has the suffix ".tex", the output will be in TeX
3039format; if the suffix is ".rtf" the output will be RTF; otherwise it will be
3040plain text. In the case of TeX output the default is to produce a
3041"fragment", suitable for inclusion in a document; if you want a stand-alone
3042document instead, use the --complete option, for example
3043
3044	modeltab --output="myfile.tex" --complete
3045
3046Caminho de Menu:    Session icon window, Model table icon
3047
3048# modprint Printing
3049
3050Argumentos: coeffmat names [ addstats ]
3051
3052Prints the coefficient table and optional additional statistics for a model
3053estimated "by hand". Mainly useful for user-written functions.
3054
3055The argument coeffmat should be a k by 2 matrix containing k coefficients
3056and k associated standard errors, and names should be a string containing at
3057least k names for the coefficients, separated by commas or spaces. (The
3058names argument may be either the name of a string variable or a literal
3059string, enclosed in double quotes.)
3060
3061The optional argument addstats is a vector containing p additional
3062statistics to be printed under the coefficient table. If this argument is
3063given, then names should contain k + p comma-separated strings, the
3064additional p strings to be associated with the additional statistics.
3065
3066# modtest Tests
3067
3068Argumento:  [ order ]
3069Opções:     --normality (normality of residual)
3070            --logs (non-linearity, logs)
3071            --autocorr (serial correlation)
3072            --arch (ARCH)
3073            --squares (non-linearity, squares)
3074            --white (heteroskedasticity, White's test)
3075            --white-nocross (White's test, squares only)
3076            --breusch-pagan (heteroskedasticity, Breusch-Pagan)
3077            --robust (robust variance estimate for Breusch-Pagan)
3078            --panel (heteroskedasticity, groupwise)
3079            --comfac (common factor restriction, AR1 models only)
3080            --quiet (don't print details)
3081            --silent (don't print anything)
3082
3083Must immediately follow an estimation command. Depending on the option
3084given, this command carries out one of the following: the Doornik-Hansen
3085test for the normality of the error term; a Lagrange Multiplier test for
3086nonlinearity (logs or squares); White's test (with or without
3087cross-products) or the Breusch-Pagan test (Breusch and Pagan, 1979) for
3088heteroskedasticity; the LMF test for serial correlation (Kiviet, 1986); a
3089test for ARCH (Autoregressive Conditional Heteroskedasticity; see also the
3090"arch" command); or a test of the common factor restriction implied by AR(1)
3091estimation. With the exception of the normality and common factor test most
3092of the options are only available for models estimated via OLS, but see
3093below for details regarding two-stage least squares.
3094
3095The optional order argument is relevant only in case the --autocorr or
3096--arch options are selected. The default is to run these tests using a lag
3097order equal to the periodicity of the data, but this can be adjusted by
3098supplying a specific lag order.
3099
3100The --robust option applies only when the Breusch-Pagan test is selected;
3101its effect is to use the robust variance estimator proposed by Koenker
3102(1981), making the test less sensitive to the assumption of normality.
3103
3104The --panel option is available only when the model is estimated on panel
3105data: in this case a test for groupwise heteroskedasticity is performed
3106(that is, for a differing error variance across the cross-sectional units).
3107
3108The --comfac option is available only when the model is estimated via an
3109AR(1) method such as Hildreth-Lu. The auxiliary regression takes the form of
3110a relatively unrestricted dynamic model, which is used to test the common
3111factor restriction implicit in the AR(1) specification.
3112
3113By default, the program prints the auxiliary regression on which the test
3114statistic is based, where applicable. This may be suppressed by using the
3115--quiet flag (minimal printed output) or the --silent flag (no printed
3116output). The test statistic and its p-value may be retrieved using the
3117accessors $test and $pvalue respectively.
3118
3119When a model has been estimated by two-stage least squares (see "tsls"), the
3120LM principle breaks down and gretl offers some equivalents: the --autocorr
3121option computes Godfrey's test for autocorrelation (Godfrey, 1994) while the
3122--white option yields the HET1 heteroskedasticity test (Pesaran and Taylor,
31231999).
3124
3125Caminho de Menu:    Model window, /Tests
3126
3127# mpols Estimation
3128
3129Argumentos: depvar indepvars
3130Opções:     --vcv (print covariance matrix)
3131            --simple-print (do not print auxiliary statistics)
3132            --quiet (suppress printing of results)
3133
3134Computes OLS estimates for the specified model using multiple precision
3135floating-point arithmetic, with the help of the Gnu Multiple Precision (GMP)
3136library. By default 256 bits of precision are used for the calculations, but
3137this can be increased via the environment variable GRETL_MP_BITS. For
3138example, when using the bash shell one could issue the following command,
3139before starting gretl, to set a precision of 1024 bits.
3140
3141	export GRETL_MP_BITS=1024
3142
3143A rather arcane option is available for this command (primarily for testing
3144purposes): if the indepvars list is followed by a semicolon and a further
3145list of numbers, those numbers are taken as powers of x to be added to the
3146regression, where x is the last variable in indepvars. These additional
3147terms are computed and stored in multiple precision. In the following
3148example y is regressed on x and the second, third and fourth powers of x:
3149
3150	mpols y 0 x ; 2 3 4
3151
3152Caminho de Menu:    /Model/Other linear models/High precision OLS
3153
3154# negbin Estimation
3155
3156Argumentos: depvar indepvars [ ; offset ]
3157Opções:     --model1 (use NegBin 1 model)
3158            --robust (QML covariance matrix)
3159            --cluster=clustvar (see "logit" for explanation)
3160            --opg (see below)
3161            --vcv (print covariance matrix)
3162            --verbose (print details of iterations)
3163
3164Estimates a Negative Binomial model. The dependent variable is taken to
3165represent a count of the occurrence of events of some sort, and must have
3166only non-negative integer values. By default the model NegBin 2 is used, in
3167which the conditional variance of the count is given by mu(1 + αmu), where
3168mu denotes the conditional mean. But if the --model1 option is given the
3169conditional variance is mu(1 + α).
3170
3171The optional offset series works in the same way as for the "poisson"
3172command. The Poisson model is a restricted form of the Negative Binomial in
3173which α = 0 by construction.
3174
3175By default, standard errors are computed using a numerical approximation to
3176the Hessian at convergence. But if the --opg option is given the covariance
3177matrix is based on the Outer Product of the Gradient (OPG), or if the
3178--robust option is given QML standard errors are calculated, using a
3179"sandwich" of the inverse of the Hessian and the OPG.
3180
3181Caminho de Menu:    /Model/Limited dependent variable/Count data...
3182
3183# nls Estimation
3184
3185Argumentos: function [ derivatives ]
3186Opções:     --quiet (don't show estimated model)
3187            --robust (robust standard errors)
3188            --vcv (print covariance matrix)
3189            --verbose (print details of iterations)
3190Exemplos:   wg_nls.inp
3191
3192Performs Nonlinear Least Squares (NLS) estimation using a modified version
3193of the Levenberg-Marquardt algorithm. You must supply a function
3194specification. The parameters of this function must be declared and given
3195starting values (using the "genr" command) prior to estimation. Optionally,
3196you may specify the derivatives of the regression function with respect to
3197each of the parameters. If you do not supply derivatives you should instead
3198give a list of the parameters to be estimated (separated by spaces or
3199commas), preceded by the keyword params. In the latter case a numerical
3200approximation to the Jacobian is computed.
3201
3202It is easiest to show what is required by example. The following is a
3203complete script to estimate the nonlinear consumption function set out in
3204William Greene's Econometric Analysis (Chapter 11 of the 4th edition, or
3205Chapter 9 of the 5th). The numbers to the left of the lines are for
3206reference and are not part of the commands. Note that any option flags, such
3207as --vcv for printing the covariance matrix of the parameter estimates,
3208should be appended to the final command, end nls.
3209
3210	1   open greene11_3.gdt
3211	2   ols C 0 Y
3212	3   scalar a = $coeff(0)
3213	4   scalar b = $coeff(Y)
3214	5   scalar g = 1.0
3215	6   nls C = a + b * Y^g
3216	7    deriv a = 1
3217	8    deriv b = Y^g
3218	9    deriv g = b * Y^g * log(Y)
3219	10  end nls --vcv
3220
3221It is often convenient to initialize the parameters by reference to a
3222related linear model; that is accomplished here on lines 2 to 5. The
3223parameters alpha, beta and gamma could be set to any initial values (not
3224necessarily based on a model estimated with OLS), although convergence of
3225the NLS procedure is not guaranteed for an arbitrary starting point.
3226
3227The actual NLS commands occupy lines 6 to 10. On line 6 the "nls" command is
3228given: a dependent variable is specified, followed by an equals sign,
3229followed by a function specification. The syntax for the expression on the
3230right is the same as that for the "genr" command. The next three lines
3231specify the derivatives of the regression function with respect to each of
3232the parameters in turn. Each line begins with the keyword "deriv", gives the
3233name of a parameter, an equals sign, and an expression whereby the
3234derivative can be calculated (again, the syntax here is the same as for
3235"genr"). As an alternative to supplying numerical derivatives, you could
3236substitute the following for lines 7 to 9:
3237
3238	params a b g
3239
3240Line 10, "end nls", completes the command and calls for estimation. Any
3241options should be appended to this line.
3242
3243For further details on NLS estimation please see guia de utilização do
3244Gretl (Capítulo 25).
3245
3246Caminho de Menu:    /Model/Nonlinear Least Squares
3247
3248# normtest Tests
3249
3250Argumento:  series
3251Opções:     --dhansen (Doornik-Hansen test, the default)
3252            --swilk (Shapiro-Wilk test)
3253            --lillie (Lilliefors test)
3254            --jbera (Jarque-Bera test)
3255            --all (do all tests)
3256            --quiet (suppress printed output)
3257
3258Carries out a test for normality for the given series. The specific test is
3259controlled by the option flags (but if no flag is given, the Doornik-Hansen
3260test is performed). Note: the Doornik-Hansen and Shapiro-Wilk tests are
3261recommended over the others, on account of their superior small-sample
3262properties.
3263
3264The test statistic and its p-value may be retrieved using the accessors
3265$test and $pvalue. Please note that if the --all option is given, the result
3266recorded is that from the Doornik-Hansen test.
3267
3268Caminho de Menu:    /Variable/Normality test
3269
3270# nulldata Dataset
3271
3272Argumento:  series_length
3273Opção:      --preserve (preserve matrices)
3274Exemplo:    nulldata 500
3275
3276Establishes a "blank" data set, containing only a constant and an index
3277variable, with periodicity 1 and the specified number of observations. This
3278may be used for simulation purposes: some of the "genr" commands (e.g. "genr
3279uniform()", "genr normal()") will generate dummy data from scratch to fill
3280out the data set. This command may be useful in conjunction with "loop". See
3281also the "seed" option to the "set" command.
3282
3283By default, this command cleans out all data in gretl's current workspace.
3284If you give the --preserve option, however, any currently defined matrices
3285are retained.
3286
3287Caminho de Menu:    /File/New data set
3288
3289# ols Estimation
3290
3291Argumentos: depvar indepvars
3292Opções:     --vcv (print covariance matrix)
3293            --robust (robust standard errors)
3294            --cluster=clustvar (clustered standard errors)
3295            --jackknife (see below)
3296            --simple-print (do not print auxiliary statistics)
3297            --quiet (suppress printing of results)
3298            --anova (print an ANOVA table)
3299            --no-df-corr (suppress degrees of freedom correction)
3300            --print-final (see below)
3301Exemplos:   ols 1 0 2 4 6 7
3302            ols y 0 x1 x2 x3 --vcv
3303            ols y 0 x1 x2 x3 --quiet
3304
3305Computes ordinary least squares (OLS) estimates with depvar as the dependent
3306variable and indepvars as the list of independent variables. Variables may
3307be specified by name or number; use the number zero for a constant term.
3308
3309Besides coefficient estimates and standard errors, the program also prints
3310p-values for t (two-tailed) and F-statistics. A p-value below 0.01 indicates
3311statistical significance at the 1 percent level and is marked with ***. **
3312indicates significance between 1 and 5 percent and * indicates significance
3313between the 5 and 10 percent levels. Model selection statistics (the Akaike
3314Information Criterion or AIC and Schwarz's Bayesian Information Criterion)
3315are also printed. The formula used for the AIC is that given by Akaike
3316(1974), namely minus two times the maximized log-likelihood plus two times
3317the number of parameters estimated.
3318
3319If the option --no-df-corr is given, the usual degrees of freedom correction
3320is not applied when calculating the estimated error variance (and hence also
3321the standard errors of the parameter estimates).
3322
3323The option --print-final is applicable only in the context of a "loop". It
3324arranges for the regression to be run silently on all but the final
3325iteration of the loop. See guia de utilização do Gretl (Capítulo 13) for
3326details.
3327
3328Various internal variables may be retrieved following estimation. For
3329example
3330
3331	series uh = $uhat
3332
3333saves the residuals under the name uh. See the "accessors" section of the
3334gretl function reference for details.
3335
3336The specific formula ("HC" version) used for generating robust standard
3337errors when the --robust option is given can be adjusted via the "set"
3338command. The --jackknife option has the effect of selecting an hc_version of
33393a. The --cluster overrides the selection of HC version, and produces robust
3340standard errors by grouping the observations by the distinct values of
3341clustvar; see guia de utilização do Gretl (Capítulo 22) for details.
3342
3343Caminho de Menu:    /Model/Ordinary Least Squares
3344Acesso alternativo: Beta-hat button on toolbar
3345
3346# omit Tests
3347
3348Argumento:  varlist
3349Opções:     --test-only (don't replace the current model)
3350            --chi-square (give chi-square form of Wald test)
3351            --quiet (print only the basic test result)
3352            --silent (don't print anything)
3353            --vcv (print covariance matrix for reduced model)
3354            --auto[=alpha] (sequential elimination, see below)
3355Exemplos:   omit 5 7 9
3356            omit seasonals --quiet
3357            omit --auto
3358            omit --auto=0.05
3359
3360This command must follow an estimation command. It calculates a Wald test
3361for the joint significance of the variables in varlist, which should be a
3362subset of the independent variables in the model last estimated. The results
3363of the test may be retrieved using the accessors $test and $pvalue.
3364
3365By default the restricted model is estimated and it replaces the original as
3366the "current model" for the purposes of, for example, retrieving the
3367residuals as $uhat or doing further tests. This behavior may be suppressed
3368via the --test-only option.
3369
3370By default the F-form of the Wald test is recorded; the --chi-square option
3371may be used to record the chi-square form instead.
3372
3373If the restricted model is both estimated and printed, the --vcv option has
3374the effect of printing its covariance matrix, otherwise this option is
3375ignored.
3376
3377Alternatively, if the --auto flag is given, sequential elimination is
3378performed: at each step the variable with the highest p-value is omitted,
3379until all remaining variables have a p-value no greater than some cutoff.
3380The default cutoff is 10 percent (two-sided); this can be adjusted by
3381appending "=" and a value between 0 and 1 (with no spaces), as in the fourth
3382example above. If varlist is given this process is confined to the listed
3383variables, otherwise all variables are treated as candidates for omission.
3384Note that the --auto and --test-only options cannot be combined.
3385
3386Caminho de Menu:    Model window, /Tests/Omit variables
3387
3388# open Dataset
3389
3390Argumento:  filename
3391Opções:     --quiet (don't print list of series)
3392            --preserve (preserve variables other than series)
3393            --frompkg=pkgname (see below)
3394            --www (use a database on the gretl server)
3395            See below for additional specialized options
3396Exemplos:   open data4-1
3397            open voter.dta
3398            open fedbog --www
3399
3400Opens a data file or database. If a data file is already open, it is
3401replaced by the newly opened one. To add data to the current dataset, see
3402"append" and (for greater flexibility) "join".
3403
3404If a full path is not given, the program will search some relevant paths to
3405try to find the file. If no filename suffix is given (as in the first
3406example above), gretl assumes a native datafile with suffix .gdt. Based on
3407the name of the file and various heuristics, gretl will try to detect the
3408format of the data file (native, plain text, CSV, MS Excel, Stata, SPSS,
3409etc.).
3410
3411If the --frompkg option is used, gretl will look for the specified data file
3412in the subdirectory associated with the function package specified by
3413pkgname.
3414
3415If the filename argument takes the form of a URI starting with http://, then
3416gretl will attempt to download the indicated data file before opening it.
3417
3418By default, opening a new data file clears the current gretl session, which
3419includes deletion of all named variables, including matrices, scalars and
3420strings. If you wish to keep your currently defined variables (other than
3421series, which are necessarily cleared out), use the --preserve option.
3422
3423The open command can also be used to open a database (gretl, RATS 4.0 or
3424PcGive) for reading. In that case it should be followed by the "data"
3425command to extract particular series from the database. If the www option is
3426given, the program will try to access a database of the given name on the
3427gretl server -- for instance the Federal Reserve interest rates database in
3428the third example above.
3429
3430When opening a spreadsheet file (Gnumeric, Open Document or MS Excel), you
3431may give up to three additional parameters following the filename. First,
3432you can select a particular worksheet within the file. This is done either
3433by giving its (1-based) number, using the syntax, e.g., --sheet=2, or, if
3434you know the name of the sheet, by giving the name in double quotes, as in
3435--sheet="MacroData". The default is to read the first worksheet. You can
3436also specify a column and/or row offset into the worksheet via, e.g.,
3437
3438	--coloffset=3 --rowoffset=2
3439
3440which would cause gretl to ignore the first 3 columns and the first 2 rows.
3441The default is an offset of 0 in both dimensions, that is, to start reading
3442at the top-left cell.
3443
3444With plain text files, gretl generally expects to find the data columns
3445delimited in some standard manner. But there is also a special facility for
3446reading "fixed format" files, in which there are no delimiters but there is
3447a known specification of the form, e.g., "variable k occupies 8 columns
3448starting at column 24". To read such files, you should append a string
3449--fixed-cols=colspec, where colspec is composed of comma-separated integers.
3450These integers are interpreted as a set of pairs. The first element of each
3451pair denotes a starting column, measured in bytes from the beginning of the
3452line with 1 indicating the first byte; and the second element indicates how
3453many bytes should be read for the given field. So, for example, if you say
3454
3455	open fixed.txt --fixed-cols=1,6,20,3
3456
3457then for variable 1 gretl will read 6 bytes starting at column 1; and for
3458variable 2, 3 bytes starting at column 20. Lines that are blank, or that
3459begin with #, are ignored, but otherwise the column-reading template is
3460applied, and if anything other than a valid numerical value is found an
3461error is flagged. If the data are read successfully, the variables will be
3462named v1, v2, etc. It's up to the user to provide meaningful names and/or
3463descriptions using the commands "rename" and/or "setinfo".
3464
3465Caminho de Menu:    /File/Open data
3466Acesso alternativo: Drag a data file onto gretl's main window
3467
3468# orthdev Transformations
3469
3470Argumento:  varlist
3471
3472Applicable with panel data only. A series of forward orthogonal deviations
3473is obtained for each variable in varlist and stored in a new variable with
3474the prefix o_. Thus "orthdev x y" creates the new variables o_x and o_y.
3475
3476The values are stored one step ahead of their true temporal location (that
3477is, o_x at observation t holds the deviation that, strictly speaking,
3478belongs at t - 1). This is for compatibility with first differences: one
3479loses the first observation in each time series, not the last.
3480
3481# outfile Printing
3482
3483Variantes:  outfile filename option
3484            outfile --close
3485Opções:     --append (append to file)
3486            --write (overwrite file)
3487            --quiet (see below)
3488Exemplos:   outfile regress.txt --write
3489            outfile --close
3490
3491Diverts output to filename, until further notice. Use the flag --append to
3492append output to an existing file or --write to start a new file (or
3493overwrite an existing one). Only one file can be opened in this way at any
3494given time.
3495
3496The --close flag is used to close an output file that was previously opened
3497as above. Output will then revert to the default stream. Note that since
3498only one file can be opened via outfile at any given time, no filename
3499argument need (nor should) be supplied with this variant of the command.
3500
3501In the first example command above, the file regress.txt is opened for
3502writing, and in the second it is closed. This would make sense as a sequence
3503only if some commands were issued before the --close. For example if an
3504"ols" command intervened, its output would go to regress.txt rather than the
3505screen.
3506
3507Three special variants on the above are available. If you give the keyword
3508null in place of a real filename along with the --write option, the effect
3509is to suppress all printed output until redirection is ended. If either of
3510the keywords stdout or stderr are given in place of a regular filename the
3511effect is to redirect output to standard output or standard error output
3512respectively.
3513
3514The --quiet option is for use with --write or --append: its effect is to
3515turn off the echoing of commands and the printing of auxiliary messages
3516while output is redirected. It is equivalent to doing
3517
3518	set echo off
3519	set messages off
3520
3521except that when redirection is ended the original values of the echo and
3522messages variables are restored.
3523
3524# panel Estimation
3525
3526Argumentos: depvar indepvars
3527Opções:     --vcv (print covariance matrix)
3528            --fixed-effects (estimate with group fixed effects)
3529            --random-effects (random effects or GLS model)
3530            --nerlove (use the Nerlove transformation)
3531            --between (estimate the between-groups model)
3532            --robust (robust standard errors; see below)
3533            --time-dummies (include time dummy variables)
3534            --unit-weights (weighted least squares)
3535            --iterate (iterative estimation)
3536            --matrix-diff (use matrix-difference method for Hausman test)
3537            --quiet (less verbose output)
3538            --verbose (more verbose output)
3539
3540Estimates a panel model. By default the fixed effects estimator is used;
3541this is implemented by subtracting the group or unit means from the original
3542data.
3543
3544If the --random-effects flag is given, random effects estimates are
3545computed, by default using the method of Swamy and Arora (1972). In this
3546case (only) the option --matrix-diff forces use of the matrix-difference
3547method (as opposed to the regression method) for carrying out the Hausman
3548test for the consistency of the random effects estimator. Also specific to
3549the random effects estimator is the --nerlove flag, which selects the method
3550of Nerlove (1971) as opposed to Swamy and Arora.
3551
3552Alternatively, if the --unit-weights flag is given, the model is estimated
3553via weighted least squares, with the weights based on the residual variance
3554for the respective cross-sectional units in the sample. In this case (only)
3555the --iterate flag may be added to produce iterative estimates: if the
3556iteration converges, the resulting estimates are Maximum Likelihood.
3557
3558As a further alternative, if the --between flag is given, the between-groups
3559model is estimated (that is, an OLS regression using the group means).
3560
3561The --robust option is available only for fixed effects models. The default
3562variant is the Arellano HAC estimator, but Beck-Katz "Panel Corrected
3563Standard Errors" can be selected via the command set pcse on. When the
3564robust option is specified the joint F test on the fixed effects is
3565performed using the robust method of Welch (1951).
3566
3567For more details on panel estimation, please see guia de utilização do
3568Gretl (Capítulo 23).
3569
3570Caminho de Menu:    /Model/Panel
3571
3572# pca Statistics
3573
3574Argumento:  varlist
3575Opções:     --covariance (use the covariance matrix)
3576            --save[=n] (save major components)
3577            --save-all (save all components)
3578            --quiet (don't print results)
3579
3580Principal Components Analysis. Unless the --quiet option is given, prints
3581the eigenvalues of the correlation matrix (or the covariance matrix if the
3582--covariance option is given) for the variables in varlist, along with the
3583proportion of the joint variance accounted for by each component. Also
3584prints the corresponding eigenvectors (or "component loadings").
3585
3586If you give the --save-all option then all components are saved to the
3587dataset as series, with names PC1, PC2 and so on. These artificial variables
3588are formed as the sum of (component loading) times (standardized X_i), where
3589X_i denotes the ith variable in varlist.
3590
3591If you give the --save option without a parameter value, components with
3592eigenvalues greater than the mean (which means greater than 1.0 if the
3593analysis is based on the correlation matrix) are saved to the dataset as
3594described above. If you provide a value for n with this option then the most
3595important n components are saved.
3596
3597See also the "princomp" function.
3598
3599Caminho de Menu:    /View/Principal components
3600Acesso alternativo: Main window pop-up (multiple selection)
3601
3602# pergm Statistics
3603
3604Argumentos: series [ bandwidth ]
3605Opções:     --bartlett (use Bartlett lag window)
3606            --log (use log scale)
3607            --radians (show frequency in radians)
3608            --degrees (show frequency in degrees)
3609            --plot=mode-or-filename (see below)
3610
3611Computes and displays the spectrum of the specified series. By default the
3612sample periodogram is given, but optionally a Bartlett lag window is used in
3613estimating the spectrum (see, for example, Greene's Econometric Analysis for
3614a discussion of this). The default width of the Bartlett window is twice the
3615square root of the sample size but this can be set manually using the
3616bandwidth parameter, up to a maximum of half the sample size.
3617
3618If the --log option is given the spectrum is represented on a logarithmic
3619scale.
3620
3621The (mutually exclusive) options --radians and --degrees influence the
3622appearance of the frequency axis when the periodogram is graphed. By default
3623the frequency is scaled by the number of periods in the sample, but these
3624options cause the axis to be labeled from 0 to pi radians or from 0 to
3625180degrees, respectively.
3626
3627By default, if the program is not in batch mode a plot of the periodogram is
3628shown. This can be adjusted via the --plot option. The acceptable parameters
3629to this option are none (to suppress the plot); display (to display a plot
3630even when in batch mode); or a file name. The effect of providing a file
3631name is as described for the --output option of the "gnuplot" command.
3632
3633Caminho de Menu:    /Variable/Periodogram
3634Acesso alternativo: Main window pop-up menu (single selection)
3635
3636# plot Graphs
3637
3638Argumento:  data
3639Opções:     --with-lines[=varspec] (use lines, not points)
3640            --with-lp[=varspec] (use lines and points)
3641            --with-impulses[=varspec] (use vertical lines)
3642            --time-series (plot against time)
3643            --single-yaxis (force use of just one y-axis)
3644            --dummy (see below)
3645            --fit=fitspec (see below)
3646            --output=filename (send output to specified file)
3647
3648The plot block provides an alternative to the "gnuplot" command which may be
3649more convenient when you are producing an elaborate plot (with several
3650options and/or gnuplot commands to be inserted into the plot file).
3651
3652A plot block starts with the command-word plot followed by the required
3653argument, data, which specifies the data to be plotted: this should be the
3654name of a list, a matrix, or a single series.
3655
3656If a list or matrix is given, the last element (list) or column (matrix) is
3657assumed to be the x-axis variable and the other(s) the y-axis variable(s),
3658unless the --time-series option is given in which case all the specified
3659data go on the y axis.
3660
3661The option of supplying a single series name is restricted to time-series
3662data, in which case it is assumed that a time-series plot is wanted;
3663otherwise an error is flagged.
3664
3665The starting line may be prefixed with the "savename <-" apparatus to save a
3666plot as an icon in the GUI program. The block ends with end plot.
3667
3668Inside the block you have zero or more lines of these types, identified by
3669an initial keyword:
3670
3671  option: specify a single option.
3672
3673  options: specify multiple options on a single line, separated by spaces.
3674
3675  literal: a command to be passed to gnuplot literally.
3676
3677  printf: a printf statement whose result will be passed to gnuplot
3678  literally.
3679
3680Note that when you specify an option using the option or options keywords,
3681it is not necessary to supply the customary double-dash before the option
3682specifier. For details on the effects of the various options please see
3683"gnuplot".
3684
3685The intended use of the plot block is best illustrated by example:
3686
3687	string title = "My title"
3688	string xname = "My x-variable"
3689	plot plotmat
3690	    options with-lines fit=none
3691	    literal set linetype 3 lc rgb "#0000ff"
3692	    literal set nokey
3693	    printf "set title \"%s\"", title
3694	    printf "set xlabel \"%s\"", xname
3695	end plot --output=display
3696
3697This example assumes that plotmat is the name of a matrix with at least 2
3698columns (or a list with at least two members). Note that it is considered
3699good practice to place the --output option (only) on the last line of the
3700block.
3701
3702# poisson Estimation
3703
3704Argumentos: depvar indepvars [ ; offset ]
3705Opções:     --robust (robust standard errors)
3706            --cluster=clustvar (see "logit" for explanation)
3707            --vcv (print covariance matrix)
3708            --verbose (print details of iterations)
3709Exemplos:   poisson y 0 x1 x2
3710            poisson y 0 x1 x2 ; S
3711
3712Estimates a poisson regression. The dependent variable is taken to represent
3713the occurrence of events of some sort, and must take on only non-negative
3714integer values.
3715
3716If a discrete random variable Y follows the Poisson distribution, then
3717
3718  Pr(Y = y) = exp(-v) * v^y / y!
3719
3720for y = 0, 1, 2,.... The mean and variance of the distribution are both
3721equal to v. In the Poisson regression model, the parameter v is represented
3722as a function of one or more independent variables. The most common version
3723(and the only one supported by gretl) has
3724
3725  v = exp(b0 + b1*x1 + b2*x2 + ...)
3726
3727or in other words the log of v is a linear function of the independent
3728variables.
3729
3730Optionally, you may add an "offset" variable to the specification. This is a
3731scale variable, the log of which is added to the linear regression function
3732(implicitly, with a coefficient of 1.0). This makes sense if you expect the
3733number of occurrences of the event in question to be proportional, other
3734things equal, to some known factor. For example, the number of traffic
3735accidents might be supposed to be proportional to traffic volume, other
3736things equal, and in that case traffic volume could be specified as an
3737"offset" in a Poisson model of the accident rate. The offset variable must
3738be strictly positive.
3739
3740By default, standard errors are computed using the negative inverse of the
3741Hessian. If the --robust flag is given, then QML or Huber-White standard
3742errors are calculated instead. In this case the estimated covariance matrix
3743is a "sandwich" of the inverse of the estimated Hessian and the outer
3744product of the gradient.
3745
3746See also "negbin".
3747
3748Caminho de Menu:    /Model/Limited dependent variable/Count data...
3749
3750# print Printing
3751
3752Variantes:  print varlist
3753            print
3754            print object_name
3755            print string_literal
3756Opções:     --byobs (by observations)
3757            --no-dates (use simple observation numbers)
3758Exemplos:   print x1 x2 --byobs
3759            print my_matrix
3760            print "This is a string"
3761
3762If varlist is given, prints the values of the specified series, or if no
3763argument is given, prints the values of all series in the current dataset.
3764If the --byobs flag is added the data are printed by observation, otherwise
3765they are printed by variable. When printing by observation, the default is
3766to show the date (with time-series data) or the observation marker string
3767(if any) at the start of each line. The --no-dates option suppresses the
3768printing of dates or markers; a simple observation number is shown instead.
3769
3770Besides printing series, you may give the name of a (single) matrix or
3771scalar variable for printing. Or you may give a literal string argument,
3772enclosed in double quotes, to be printed as is. In these case the option
3773flags are not applicable.
3774
3775Note that you can gain greater control over the printing format (and so, for
3776example, expose a greater number of digits than are shown by default) by
3777using "printf".
3778
3779Caminho de Menu:    /Data/Display values
3780
3781# printf Printing
3782
3783Argumentos: format , args
3784
3785Prints scalar values, series, matrices, or strings under the control of a
3786format string (providing a subset of the printf() statement in the C
3787programming language). Recognized numeric formats are %e, %E, %f, %g, %G and
3788%d, in each case with the various modifiers available in C. Examples: the
3789format %.10g prints a value to 10 significant figures; %12.6f prints a value
3790to 6 decimal places, with a width of 12 characters. The format %s should be
3791used for strings.
3792
3793The format string itself must be enclosed in double quotes. The values to be
3794printed must follow the format string, separated by commas. These values
3795should take the form of either (a) the names of variables, (b) expressions
3796that are valid for the "genr" command, or (c) the special functions
3797varname() or date(). The following example prints the values of two
3798variables plus that of a calculated expression:
3799
3800	ols 1 0 2 3
3801	scalar b = $coeff[2]
3802	scalar se_b = $stderr[2]
3803	printf "b = %.8g, standard error %.8g, t = %.4f\n",
3804          b, se_b, b/se_b
3805
3806The next lines illustrate the use of the varname and date functions, which
3807respectively print the name of a variable, given its ID number, and a date
3808string, given a 1-based observation number.
3809
3810	printf "The name of variable %d is %s\n", i, varname(i)
3811	printf "The date of observation %d is %s\n", j, date(j)
3812
3813If a matrix argument is given in association with a numeric format, the
3814entire matrix is printed using the specified format for each element. The
3815same applies to series, except that the range of values printed is governed
3816by the current sample setting.
3817
3818The maximum length of a format string is 127 characters. The escape
3819sequences \n (newline), \t (tab), \v (vertical tab) and \\ (literal
3820backslash) are recognized. To print a literal percent sign, use %%.
3821
3822As in C, numerical values that form part of the format (width and or
3823precision) may be given directly as numbers, as in %10.4f, or they may be
3824given as variables. In the latter case, one puts asterisks into the format
3825string and supplies corresponding arguments in order. For example,
3826
3827	scalar width = 12
3828	scalar precision = 6
3829	printf "x = %*.*f\n", width, precision, x
3830
3831# probit Estimation
3832
3833Argumentos: depvar indepvars
3834Opções:     --robust (robust standard errors)
3835            --cluster=clustvar (see "logit" for explanation)
3836            --vcv (print covariance matrix)
3837            --verbose (print details of iterations)
3838            --p-values (show p-values instead of slopes)
3839            --random-effects (estimates a random effects panel probit model)
3840            --quadpoints=k (number of quadrature points for RE estimation)
3841Exemplos:   ooballot.inp, oprobit.inp, reprobit.inp
3842
3843If the dependent variable is a binary variable (all values are 0 or 1)
3844maximum likelihood estimates of the coefficients on indepvars are obtained
3845via the Newton-Raphson method. As the model is nonlinear the slopes depend
3846on the values of the independent variables. By default the slopes with
3847respect to each of the independent variables are calculated (at the means of
3848those variables) and these slopes replace the usual p-values in the
3849regression output. This behavior can be suppressed my giving the --p-values
3850option. The chi-square statistic tests the null hypothesis that all
3851coefficients are zero apart from the constant.
3852
3853By default, standard errors are computed using the negative inverse of the
3854Hessian. If the --robust flag is given, then QML or Huber-White standard
3855errors are calculated instead. In this case the estimated covariance matrix
3856is a "sandwich" of the inverse of the estimated Hessian and the outer
3857product of the gradient. See chapter 10 of Davidson and MacKinnon for
3858details.
3859
3860If the dependent variable is not binary but is discrete, then Ordered Probit
3861estimates are obtained. (If the variable selected as dependent is not
3862discrete, an error is flagged.)
3863
3864Probit for panel data
3865
3866With the --random-effects option, the error term is assumed to be composed
3867of two normally distributed components: one time-invariant term that is
3868specific to the cross-sectional unit or "individual" (and is known as the
3869individual effect); and one term that is specific to the particular
3870observation.
3871
3872Evaluation of the likelihood for this model involves the use of
3873Gauss-Hermite quadrature for approximating the value of expectations of
3874functions of normal variates. The number of quadrature points used can be
3875chosen through the --quadpoints option (the default is 32). Using more
3876points will increase the accuracy of the results, but at the cost of longer
3877compute time; with many quadrature points and a large dataset estimation may
3878be quite time consuming.
3879
3880Besides the usual parameter estimates (and associated statistics) relating
3881to the included regressors, certain additional information is presented on
3882estimation of this sort of model:
3883
3884  lnsigma2: the maximum likelihood estimate of the log of the variance of
3885  the individual effect;
3886
3887  sigma_u: the estimated standard deviation of the individual effect; and
3888
3889  rho: the estimated share of the individual effect in the composite error
3890  variance (also known as the intra-class correlation).
3891
3892The Likelihood Ratio test of the null hypothesis that rho equals zero
3893provides a means of assessing whether the random effects specification is
3894needed. If the null is not rejected that suggests that a simple pooled
3895probit specification is adequate.
3896
3897Caminho de Menu:    /Model/Limited dependent variable/Probit
3898
3899# pvalue Utilities
3900
3901Argumentos: dist [ params ] xval
3902Exemplos:   pvalue z zscore
3903            pvalue t 25 3.0
3904            pvalue X 3 5.6
3905            pvalue F 4 58 fval
3906            pvalue G shape scale x
3907            pvalue B bprob 10 6
3908            pvalue P lambda x
3909            pvalue W shape scale x
3910
3911Computes the area to the right of xval in the specified distribution (z for
3912Gaussian, t for Student's t, X for chi-square, F for F, G for gamma, B for
3913binomial, P for Poisson, or W for Weibull).
3914
3915Depending on the distribution, the following information must be given,
3916before the xval: for the t and chi-square distributions, the degrees of
3917freedom; for F, the numerator and denominator degrees of freedom; for gamma,
3918the shape and scale parameters; for the binomial distribution, the "success"
3919probability and the number of trials; for the Poisson distribution, the
3920parameter lambda (which is both the mean and the variance); and for the
3921Weibull distribution, shape and scale parameters. As shown in the examples
3922above, the numerical parameters may be given in numeric form or as the names
3923of variables.
3924
3925The parameters for the gamma distribution are sometimes given as mean and
3926variance rather than shape and scale. The mean is the product of the shape
3927and the scale; the variance is the product of the shape and the square of
3928the scale. So the scale may be found as the variance divided by the mean,
3929and the shape as the mean divided by the scale.
3930
3931Caminho de Menu:    /Tools/P-value finder
3932
3933# qlrtest Tests
3934
3935Opções:     --limit-to=list (limit test to subset of regressors)
3936            --plot=mode-or-filename (see below)
3937
3938For a model estimated on time-series data via OLS, performs the Quandt
3939likelihood ratio (QLR) test for a structural break at an unknown point in
3940time, with 15 percent trimming at the beginning and end of the sample
3941period.
3942
3943For each potential break point within the central 70 percent of the
3944observations, a Chow test is performed. See "chow" for details; as with the
3945regular Chow test, this is a robust Wald test if the original model was
3946estimated with the --robust option, an F-test otherwise. The QLR statistic
3947is then the maximum of the individual test statistics.
3948
3949An asymptotic p-value is obtained using the method of Bruce Hansen (1997).
3950
3951Besides the standard hypothesis test accessors "$test" and "$pvalue",
3952"$qlrbreak" can be used to retrieve the index of the observation at which
3953the test statistic is maximized.
3954
3955The --limit-to option can be used to limit the set of interactions with the
3956split dummy variable in the Chow tests to a subset of the original
3957regressors. The parameter for this option must be a named list, all of whose
3958members are among the original regressors. The list should not include the
3959constant.
3960
3961When this command is run interactively (only), a plot of the Chow test
3962statistic is displayed by default. This can be adjusted via the --plot
3963option. The acceptable parameters to this option are none (to suppress the
3964plot); display (to display a plot even when not in interactive mode); or a
3965file name. The effect of providing a file name is as described for the
3966--output option of the "gnuplot" command.
3967
3968Caminho de Menu:    Model window, /Tests/QLR test
3969
3970# qqplot Graphs
3971
3972Variantes:  qqplot y
3973            qqplot y x
3974Opções:     --z-scores (see below)
3975            --raw (see below)
3976            --output=filename (send output to specified file)
3977
3978Given just one series argument, displays a plot of the empirical quantiles
3979of the selected series (given by name or ID number) against the quantiles of
3980the normal distribution. The series must include at least 20 valid
3981observations in the current sample range. By default the empirical quantiles
3982are plotted against quantiles of the normal distribution having the same
3983mean and variance as the sample data, but two alternatives are available: if
3984the --z-scores option is given the data are standardized, while if the --raw
3985option is given the "raw" empirical quantiles are plotted against the
3986quantiles of the standard normal distribution.
3987
3988The option --output has the effect to send the output to the desiderd
3989filename; use "display" to force output to the screen, for example during a
3990loop.
3991
3992Given two series arguments, y and x, displays a plot of the empirical
3993quantiles of y against those of x. The data values are not standardized.
3994
3995Caminho de Menu:    /Variable/Normal Q-Q plot
3996Caminho de Menu:    /View/Graph specified vars/Q-Q plot
3997
3998# quantreg Estimation
3999
4000Argumentos: tau depvar indepvars
4001Opções:     --robust (robust standard errors)
4002            --intervals[=level] (compute confidence intervals)
4003            --vcv (print covariance matrix)
4004            --quiet (suppress printing of results)
4005Exemplos:   quantreg 0.25 y 0 xlist
4006            quantreg 0.5 y 0 xlist --intervals
4007            quantreg 0.5 y 0 xlist --intervals=.95
4008            quantreg tauvec y 0 xlist --robust
4009            Ver tambémmrw_qr.inp
4010
4011Quantile regression. The first argument, tau, is the conditional quantile
4012for which estimates are wanted. It may be given either as a numerical value
4013or as the name of a pre-defined scalar variable; the value must be in the
4014range 0.01 to 0.99. (Alternatively, a vector of values may be given for tau;
4015see below for details.) The second and subsequent arguments compose a
4016regression list on the same pattern as "ols".
4017
4018Without the --intervals option, standard errors are printed for the quantile
4019estimates. By default, these are computed according to the asymptotic
4020formula given by Koenker and Bassett (1978), but if the --robust option is
4021given, standard errors that are robust with respect to heteroskedasticity
4022are calculated using the method of Koenker and Zhao (1994).
4023
4024When the --intervals option is chosen, confidence intervals are given for
4025the parameter estimates instead of standard errors. These intervals are
4026computed using the rank inversion method, and in general they are
4027asymmetrical about the point estimates. The specifics of the calculation are
4028inflected by the --robust option: without this, the intervals are computed
4029on the assumption of IID errors (Koenker, 1994); with it, they use the
4030robust estimator developed by Koenker and Machado (1999).
4031
4032By default, 90 percent confidence intervals are produced. You can change
4033this by appending a confidence level (expressed as a decimal fraction) to
4034the intervals option, as in --intervals=0.95.
4035
4036Vector-valued tau: instead of supplying a scalar, you may give the name of a
4037pre-defined matrix. In this case estimates are computed for all the given
4038tau values and the results are printed in a special format, showing the
4039sequence of quantile estimates for each regressor in turn.
4040
4041Caminho de Menu:    /Model/Robust estimation/Quantile regression
4042
4043# quit Utilities
4044
4045Exits from the program, giving you the option of saving the output from the
4046session on the way out.
4047
4048Caminho de Menu:    /File/Exit
4049
4050# rename Dataset
4051
4052Argumentos: series newname
4053
4054Changes the name of series (identified by name or ID number) to newname. The
4055new name must be of 31 characters maximum, must start with a letter, and
4056must be composed of only letters, digits, and the underscore character.
4057
4058Caminho de Menu:    /Variable/Edit attributes
4059Acesso alternativo: Main window pop-up menu (single selection)
4060
4061# reset Tests
4062
4063Opções:     --quiet (don't print the auxiliary regression)
4064            --squares-only (compute the test using only the squares)
4065            --cubes-only (compute the test using only the cubes)
4066
4067Must follow the estimation of a model via OLS. Carries out Ramsey's RESET
4068test for model specification (non-linearity) by adding the square and/or the
4069cube of the fitted values to the regression and calculating the F statistic
4070for the null hypothesis that the parameters on the added terms are zero.
4071
4072Both the square and the cube are added, unless one of the options
4073--squares-only or --cubes-only is given.
4074
4075Caminho de Menu:    Model window, /Tests/Ramsey's RESET
4076
4077# restrict Tests
4078
4079Opções:     --quiet (don't print restricted estimates)
4080            --silent (don't print anything)
4081            --wald (system estimators only - see below)
4082            --bootstrap (bootstrap the test if possible)
4083            --full (OLS and VECMs only, see below)
4084
4085Imposes a set of (usually linear) restrictions on either (a) the model last
4086estimated or (b) a system of equations previously defined and named. In all
4087cases the set of restrictions should be started with the keyword "restrict"
4088and terminated with "end restrict".
4089
4090In the single equation case the restrictions are always implicitly to be
4091applied to the last model, and they are evaluated as soon as the restrict
4092block is closed.
4093
4094In the case of a system of equations (defined via the "system" command), the
4095initial "restrict" may be followed by the name of a previously defined
4096system of equations. If this is omitted and the last model was a system then
4097the restrictions are applied to the last model. By default the restrictions
4098are evaluated when the system is next estimated, using the "estimate"
4099command. But if the --wald option is given the restriction is tested right
4100away, via a Wald chi-square test on the covariance matrix. Note that this
4101option will produce an error if a system has been defined but not yet
4102estimated.
4103
4104Depending on the context, the restrictions to be tested may be expressed in
4105various ways. The simplest form is as follows: each restriction is given as
4106an equation, with a linear combination of parameters on the left and a
4107scalar value to the right of the equals sign (either a numerical constant or
4108the name of a scalar variable).
4109
4110In the single-equation case, parameters may be referenced in the form b[i],
4111where i represents the position in the list of regressors (starting at 1),
4112or b[varname], where varname is the name of the regressor in question. In
4113the system case, parameters are referenced using b plus two numbers in
4114square brackets. The leading number represents the position of the equation
4115within the system and the second number indicates position in the list of
4116regressors. For example b[2,1] denotes the first parameter in the second
4117equation, and b[3,2] the second parameter in the third equation. The b terms
4118in the equation representing a restriction may be prefixed with a numeric
4119multiplier, for example 3.5*b[4].
4120
4121Here is an example of a set of restrictions for a previously estimated
4122model:
4123
4124	restrict
4125	 b[1] = 0
4126	 b[2] - b[3] = 0
4127	 b[4] + 2*b[5] = 1
4128	end restrict
4129
4130And here is an example of a set of restrictions to be applied to a named
4131system. (If the name of the system does not contain spaces, the surrounding
4132quotes are not required.)
4133
4134	restrict "System 1"
4135	 b[1,1] = 0
4136	 b[1,2] - b[2,2] = 0
4137	 b[3,4] + 2*b[3,5] = 1
4138	end restrict
4139
4140In the single-equation case the restrictions are by default evaluated via a
4141Wald test, using the covariance matrix of the model in question. If the
4142original model was estimated via OLS then the restricted coefficient
4143estimates are printed; to suppress this, append the --quiet option flag to
4144the initial restrict command. As an alternative to the Wald test, for models
4145estimated via OLS or WLS only, you can give the --bootstrap option to
4146perform a bootstrapped test of the restriction.
4147
4148In the system case, the test statistic depends on the estimator chosen: a
4149Likelihood Ratio test if the system is estimated using a Maximum Likelihood
4150method, or an asymptotic F-test otherwise.
4151
4152There are two alternatives to the method of expressing restrictions
4153discussed above. First, a set of g linear restrictions on a k-vector of
4154parameters, beta, may be written compactly as Rbeta - q = 0, where R is an g
4155x k matrix and q is a g-vector. You can specify a restriction by giving the
4156names of pre-defined, conformable matrices to be used as R and q, as in
4157
4158	restrict
4159	  R = Rmat
4160	  q = qvec
4161	end restrict
4162
4163Secondly, if you wish to test a nonlinear restriction (this is currently
4164available for single-equation models only) you should give the restriction
4165as the name of a function, preceded by "rfunc = ", as in
4166
4167	restrict
4168	  rfunc = myfunction
4169	end restrict
4170
4171The constraint function should take a single const matrix argument; this
4172will be automatically filled out with the parameter vector. And it should
4173return a vector which is zero under the null hypothesis, non-zero otherwise.
4174The length of the vector is the number of restrictions. This function is
4175used as a "callback" by gretl's numerical Jacobian routine, which calculates
4176a Wald test statistic via the delta method.
4177
4178Here is a simple example of a function suitable for testing one nonlinear
4179restriction, namely that two pairs of parameter values have a common ratio.
4180
4181	function matrix restr (const matrix b)
4182	  matrix v = b[1]/b[2] - b[4]/b[5]
4183	  return v
4184	end function
4185
4186On successful completion of the restrict command the accessors $test and
4187$pvalue give the test statistic and its p-value.
4188
4189When testing restrictions on a single-equation model estimated via OLS, or
4190on a VECM, the --full option can be used to set the restricted estimates as
4191the "last model" for the purposes of further testing or the use of accessors
4192such as $coeff and $vcv. Note that some special considerations apply in the
4193case of testing restrictions on Vector Error Correction Models. Please see
4194guia de utilização do Gretl (Capítulo 33) for details.
4195
4196Caminho de Menu:    Model window, /Tests/Linear restrictions
4197
4198# rmplot Graphs
4199
4200Argumento:  series
4201Opções:     --trim (see below)
4202            --quiet (suppress printed output)
4203
4204Range-mean plot: this command creates a simple graph to help in deciding
4205whether a time series, y(t), has constant variance or not. We take the full
4206sample t=1,...,T and divide it into small subsamples of arbitrary size k.
4207The first subsample is formed by y(1),...,y(k), the second is y(k+1), ...,
4208y(2k), and so on. For each subsample we calculate the sample mean and range
4209(= maximum minus minimum), and we construct a graph with the means on the
4210horizontal axis and the ranges on the vertical. So each subsample is
4211represented by a point in this plane. If the variance of the series is
4212constant we would expect the subsample range to be independent of the
4213subsample mean; if we see the points approximate an upward-sloping line this
4214suggests the variance of the series is increasing in its mean; and if the
4215points approximate a downward sloping line this suggests the variance is
4216decreasing in the mean.
4217
4218Besides the graph, gretl displays the means and ranges for each subsample,
4219along with the slope coefficient for an OLS regression of the range on the
4220mean and the p-value for the null hypothesis that this slope is zero. If the
4221slope coefficient is significant at the 10 percent significance level then
4222the fitted line from the regression of range on mean is shown on the graph.
4223The t-statistic for the null, and the corresponding p-value, are recorded
4224and may be retrieved using the accessors $test and $pvalue respectively.
4225
4226If the --trim option is given, the minimum and maximum values in each
4227sub-sample are discarded before calculating the mean and range. This makes
4228it less likely that outliers will distort the analysis.
4229
4230If the --quiet option is given, no graph is shown and no output is printed;
4231only the t-statistic and p-value are recorded.
4232
4233Caminho de Menu:    /Variable/Range-mean graph
4234
4235# run Programming
4236
4237Argumento:  filename
4238
4239Executes the commands in filename then returns control to the interactive
4240prompt. This command is intended for use with the command-line program
4241gretlcli, or at the "gretl console" in the GUI program.
4242
4243See also "include".
4244
4245Caminho de Menu:    Run icon in script window
4246
4247# runs Tests
4248
4249Argumento:  series
4250Opções:     --difference (use first difference of variable)
4251            --equal (positive and negative values are equiprobable)
4252
4253Carries out the nonparametric "runs" test for randomness of the specified
4254series, where runs are defined as sequences of consecutive positive or
4255negative values. If you want to test for randomness of deviations from the
4256median, for a variable named x1 with a non-zero median, you can do the
4257following:
4258
4259	series signx1 = x1 - median(x1)
4260	runs signx1
4261
4262If the --difference option is given, the variable is differenced prior to
4263the analysis, hence the runs are interpreted as sequences of consecutive
4264increases or decreases in the value of the variable.
4265
4266If the --equal option is given, the null hypothesis incorporates the
4267assumption that positive and negative values are equiprobable, otherwise the
4268test statistic is invariant with respect to the "fairness" of the process
4269generating the sequence, and the test focuses on independence alone.
4270
4271Caminho de Menu:    /Tools/Nonparametric tests
4272
4273# scatters Graphs
4274
4275Argumentos: yvar ; xvars  ou yvars ; xvar
4276Opções:     --with-lines (create line graphs)
4277            --matrix=name (plot columns of named matrix)
4278            --output=filename (send output to specified file)
4279            --output=filename (send output to specified file)
4280Exemplos:   scatters 1 ; 2 3 4 5
4281            scatters 1 2 3 4 5 6 ; 7
4282            scatters y1 y2 y3 ; x --with-lines
4283
4284Generates pairwise graphs of yvar against all the variables in xvars, or of
4285all the variables in yvars against xvar. The first example above puts
4286variable 1 on the y-axis and draws four graphs, the first having variable 2
4287on the x-axis, the second variable 3 on the x-axis, and so on. The second
4288example plots each of variables 1 through 6 against variable 7 on the
4289x-axis. Scanning a set of such plots can be a useful step in exploratory
4290data analysis. The maximum number of plots is 16; any extra variable in the
4291list will be ignored.
4292
4293By default the graphs are scatterplots, but if you give the --with-lines
4294flag they will be line graphs.
4295
4296For details on usage of the --output option, please see the "gnuplot"
4297command.
4298
4299If a named matrix is specified as the data source the x and y lists should
4300be given as 1-based column numbers; or alternatively, if no such numbers are
4301given, all the columns are plotted against time or an index variable.
4302
4303If the dataset is time-series, then the second sub-list can be omitted, in
4304which case it will implicitly be taken as "time", so you can plot multiple
4305time series in separated sub-graphs.
4306
4307Caminho de Menu:    /View/Multiple graphs
4308
4309# sdiff Transformations
4310
4311Argumento:  varlist
4312
4313The seasonal difference of each variable in varlist is obtained and the
4314result stored in a new variable with the prefix sd_. This command is
4315available only for seasonal time series.
4316
4317Caminho de Menu:    /Add/Seasonal differences of selected variables
4318
4319# set Programming
4320
4321Variantes:  set variable value
4322            set --to-file=filename
4323            set --from-file=filename
4324            set stopwatch
4325            set
4326Exemplos:   set svd on
4327            set csv_delim tab
4328            set horizon 10
4329            set --to-file=mysettings.inp
4330
4331The most common use of this command is the first variant shown above, where
4332it is used to set the value of a selected program parameter. This is
4333discussed in detail below. The other uses are: with --to-file, to write a
4334script file containing all the current parameter settings; with --from-file
4335to read a script file containing parameter settings and apply them to the
4336current session; with stopwatch to zero the gretl "stopwatch" which can be
4337used to measure CPU time (see the entry for the $stopwatch accessor in the
4338gretl function reference); or, if the word set is given alone, to print the
4339current settings.
4340
4341Values set via this comand remain in force for the duration of the gretl
4342session unless they are changed by a further call to "set". The parameters
4343that can be set in this way are enumerated below. Note that the settings of
4344hc_version, hac_lag and hac_kernel are used when the --robust option is
4345given to an estimation command.
4346
4347The available settings are grouped under the following categories: program
4348interaction and behavior, numerical methods, random number generation,
4349robust estimation, filtering, time series estimation, and interaction with
4350GNU R.
4351
4352Program interaction and behavior
4353
4354These settings are used for controlling various aspects of the way gretl
4355interacts with the user.
4356
4357  csv_delim: either comma (the default), space, tab or semicolon. Sets the
4358  column delimiter used when saving data to file in CSV format.
4359
4360  csv_write_na: the string used to represent missing values when writing
4361  data to file in CSV format. Maximum 7 characters; the default is NA.
4362
4363  csv_read_na: the string taken to represent missing values (NAs) when
4364  reading data in CSV format. Maximum 7 characters. The default depends on
4365  whether a data column is found to contain numerical data (mostly) or
4366  string values. For numerical data the following are taken as indicating
4367  NAs: an empty cell, or any of the strings NA, N.A., na, n.a., N/A, #N/A,
4368  NaN, .NaN, ., .., -999, and -9999. For string-valued data only a blank
4369  cell, or a cell containing an empty string, is counted as NA. These
4370  defaults can be reimposed by giving default as the value for csv_read_na.
4371  To specify that only empty cells are read as NAs, give a value of "". Note
4372  that empty cells are always read as NAs regardless of the setting of this
4373  variable.
4374
4375  csv_digits: a positive integer specifying the number of significant digits
4376  to use when writing data in CSV format. By default up to 15 digits are
4377  used depending on the precision of the original data. Note that CSV output
4378  employs the C library's fprintf function with "%g" conversion, which means
4379  that trailing zeros are dropped.
4380
4381  mwrite_g: on or off (the default). When writing a matrix to file as text,
4382  gretl by default uses scientific notation with 18-digit precision, hence
4383  ensuring that the stored values are a faithful representation of the
4384  numbers in memory. When writing primary data with no more than 6 digits of
4385  precision it may be preferable to use %g format for a more compact and
4386  human-readable file; you can make this switch via set mwrite_g on.
4387
4388  echo: off or on (the default). Suppress or resume the echoing of commands
4389  in gretl's output.
4390
4391  force_decpoint: on or off (the default). Force gretl to use the decimal
4392  point character, in a locale where another character (most likely the
4393  comma) is the standard decimal separator.
4394
4395  loop_maxiter: one non-negative integer value (default 100000). Sets the
4396  maximum number of iterations that a while loop is allowed before halting
4397  (see "loop"). Note that this setting only affects the while variant; its
4398  purpose is to guard against inadvertently infinite loops. Setting this
4399  value to 0 has the effect of disabling the limit; use with caution.
4400
4401  max_verbose: on or off (the default). Toggles verbose output for the
4402  BFGSmax and NRmax functions (see the User's Guide for details).
4403
4404  messages: off or on (the default). Suppress or resume the printing of
4405  non-error messages associated with various commands, for example when a
4406  new variable is generated or when the sample range is changed.
4407
4408  warnings: off or on (the default). Suppress or resume the printing of
4409  warning messages issued when arithmetical operations produce non-finite
4410  values.
4411
4412  debug: 1, 2 or 0 (the default). This is for use with user-defined
4413  functions. Setting debug to 1 is equivalent to turning messages on within
4414  all such functions; setting this variable to 2 has the additional effect
4415  of turning on max_verbose within all functions.
4416
4417  shell_ok: on or off (the default). Enable launching external programs from
4418  gretl via the system shell. This is disabled by default for security
4419  reasons, and can only be enabled via the graphical user interface
4420  (Tools/Preferences/General). However, once set to on, this setting will
4421  remain active for future sessions until explicitly disabled.
4422
4423  use_cwd: on or off (the default). This setting affects the behavior of the
4424  "outfile" and "store" commands, which write external files. Normally, the
4425  file will be written in the user's default data directory; if use_cwd is
4426  on, on the contrary, the file will be created in the working directory
4427  when gretl was started.
4428
4429  bfgs_verbskip: one integer. This setting affects the behavior of the
4430  --verbose option to those commands that use BFGS as an optimization
4431  algorithm and is used to compact output. if bfgs_verbskip is set to, say,
4432  3, then the --verbose switch will only print iterations 3, 6, 9 and so on.
4433
4434  skip_missing: on (the default) or off. Controls gretl's behavior when
4435  contructing a matrix from data series: the default is to skip data rows
4436  that contain one or more missing values but if skip_missing is set off
4437  missing values are converted to NaNs.
4438
4439  matrix_mask: the name of a series, or the keyword null. Offers greater
4440  control than skip_missing when constructing matrices from series: the data
4441  rows selected for matrices are those with non-zero (and non-missing)
4442  values in the specified series. The selected mask remains in force until
4443  it is replaced, or removed via the null keyword.
4444
4445  huge: a large positive number (by default, 1.0E100). This setting controls
4446  the value returned by the accessor "$huge".
4447
4448Numerical methods
4449
4450These settings are used for controlling the numerical algorithms that gretl
4451uses for estimation.
4452
4453  optimizer: either auto (the default), BFGS or newton. Sets the
4454  optimization algorithm used for various ML estimators, in cases where both
4455  BFGS and Newton-Raphson are applicable. The default is to use
4456  Newton-Raphson where an analytical Hessian is available, otherwise BFGS.
4457
4458  bhhh_maxiter: one integer, the maximum number of iterations for gretl's
4459  internal BHHH routine, which is used in the "arma" command for conditional
4460  ML estimation. If convergence is not achieved after bhhh_maxiter, the
4461  program returns an error. The default is set at 500.
4462
4463  bhhh_toler: one floating point value, or the string default. This is used
4464  in gretl's internal BHHH routine to check if convergence has occurred. The
4465  algorithm stops iterating as soon as the increment in the log-likelihood
4466  between iterations is smaller than bhhh_toler. The default value is
4467  1.0E-06; this value may be re-established by typing default in place of a
4468  numeric value.
4469
4470  bfgs_maxiter: one integer, the maximum number of iterations for gretl's
4471  BFGS routine, which is used for "mle", "gmm" and several specific
4472  estimators. If convergence is not achieved in the specified number of
4473  iterations, the program returns an error. The default value depends on the
4474  context, but is typically of the order of 500.
4475
4476  bfgs_toler: one floating point value, or the string default. This is used
4477  in gretl's BFGS routine to check if convergence has occurred. The
4478  algorithm stops as soon as the relative improvement in the objective
4479  function between iterations is smaller than bfgs_toler. The default value
4480  is the machine precision to the power 3/4; this value may be
4481  re-established by typing default in place of a numeric value.
4482
4483  bfgs_maxgrad: one floating point value. This is used in gretl's BFGS
4484  routine to check if the norm of the gradient is reasonably close to zero
4485  when the bfgs_toler criterion is met. A warning is printed if the norm of
4486  the gradient exceeds 1; an error is flagged if the norm exceeds
4487  bfgs_maxgrad. At present the default is the permissive value of 5.0.
4488
4489  bfgs_richardson: on or off (the default). Use Richardson extrapolation
4490  when computing numerical derivatives in the context of BFGS maximization.
4491
4492  initvals: either auto (the default) or the name of a pre-specified matrix.
4493  Allows manual setting of the initial parameter estimates for numerical
4494  optimization problems (such as ARMA estimation). For details see guia de
4495  utilização do Gretl (Capítulo 31).
4496
4497  lbfgs: on or off (the default). Use the limited-memory version of BFGS
4498  (L-BFGS-B) instead of the ordinary algorithm. This may be advantageous
4499  when the function to be maximized is not globally concave.
4500
4501  lbfgs_mem: an integer value in the range 3 to 20 (with a default value of
4502  8). This determines the number of corrections used in the limited memory
4503  matrix when L-BFGS-B is employed.
4504
4505  nls_toler: a floating-point value (the default is the machine precision to
4506  the power 3/4). Sets the tolerance used in judging whether or not
4507  convergence has occurred in nonlinear least squares estimation using the
4508  "nls" command.
4509
4510  svd: on or off (the default). Use SVD rather than Cholesky or QR
4511  decomposition in least squares calculations. This option applies to the
4512  mols function as well as various internal calculations, but not to the
4513  regular "ols" command.
4514
4515  fcp: on or off (the default). Use the algorithm of Fiorentini, Calzolari
4516  and Panattoni rather than native gretl code when computing GARCH
4517  estimates.
4518
4519  gmm_maxiter: one integer, the maximum number of iterations for gretl's
4520  "gmm" command when in iterated mode (as opposed to one- or two-step). The
4521  default value is 250.
4522
4523  nadarwat_trim: one integer, the trim parameter used in the "nadarwat"
4524  function.
4525
4526  fdjac_quality: one integer between 0 and 2, the algorithm used by the
4527  "fdjac" function.
4528
4529Random number generation
4530
4531  seed: an unsigned integer. Sets the seed for the pseudo-random number
4532  generator. By default this is set from the system time; if you want to
4533  generate repeatable sequences of random numbers you must set the seed
4534  manually.
4535
4536  normal_rand: ziggurat (the default) or box-muller. Sets the method for
4537  generating random normal samples based on uniform input.
4538
4539Robust estimation
4540
4541  bootrep: an integer. Sets the number of replications for the "restrict"
4542  command with the --bootstrap option.
4543
4544  garch_vcv: unset, hessian, im (information matrix) , op (outer product
4545  matrix), qml (QML estimator), bw (Bollerslev-Wooldridge). Specifies the
4546  variant that will be used for estimating the coefficient covariance
4547  matrix, for GARCH models. If unset is given (the default) then the Hessian
4548  is used unless the "robust" option is given for the garch command, in
4549  which case QML is used.
4550
4551  arma_vcv: hessian (the default) or op (outer product matrix). Specifies
4552  the variant to be used when computing the covariance matrix for ARIMA
4553  models.
4554
4555  force_hc: off (the default) or on. By default, with time-series data and
4556  when the --robust option is given with ols, the HAC estimator is used. If
4557  you set force_hc to "on", this forces calculation of the regular
4558  Heteroskedasticity Consistent Covariance Matrix (HCCM), which does not
4559  take autocorrelation into account. Note that VARs are treated as a special
4560  case: when the --robust option is given the default method is regular
4561  HCCM, but the --robust-hac flag can be used to force the use of a HAC
4562  estimator.
4563
4564  robust_z: off (the default) or on. This controls the distribution used
4565  when calculating p-values based on robust standard errors in the context
4566  of least-squares estimators. By default gretl uses the Student t
4567  distribution but if robust_z is turned on the normal distribution is used.
4568
4569  hac_lag: nw1 (the default), nw2, nw3 or an integer. Sets the maximum lag
4570  value or bandwidth, p, used when calculating HAC (Heteroskedasticity and
4571  Autocorrelation Consistent) standard errors using the Newey-West approach,
4572  for time series data. nw1 and nw2 represent two variant automatic
4573  calculations based on the sample size, T: for nw1, p = 0.75 * T^(1/3), and
4574  for nw2, p = 4 * (T/100)^(2/9). nw3 calls for data-based bandwidth
4575  selection. See also qs_bandwidth and hac_prewhiten below.
4576
4577  hac_kernel: bartlett (the default), parzen, or qs (Quadratic Spectral).
4578  Sets the kernel, or pattern of weights, used when calculating HAC standard
4579  errors.
4580
4581  hac_prewhiten: on or off (the default). Use Andrews-Monahan prewhitening
4582  and re-coloring when computing HAC standard errors. This also implies use
4583  of data-based bandwidth selection.
4584
4585  hc_version: 0 (the default), 1, 2, 3 or 3a. Sets the variant used when
4586  calculating Heteroskedasticity Consistent standard errors with
4587  cross-sectional data. The first four options correspond to the HC0, HC1,
4588  HC2 and HC3 discussed by Davidson and MacKinnon in Econometric Theory and
4589  Methods, chapter 5. HC0 produces what are usually called "White's standard
4590  errors". Variant 3a is the MacKinnon-White "jackknife" procedure.
4591
4592  pcse: off (the default) or on. By default, when estimating a model using
4593  pooled OLS on panel data with the --robust option, the Arellano estimator
4594  is used for the covariance matrix. If you set pcse to "on", this forces
4595  use of the Beck and Katz Panel Corrected Standard Errors (which do not
4596  take autocorrelation into account).
4597
4598  qs_bandwidth: Bandwidth for HAC estimation in the case where the Quadratic
4599  Spectral kernel is selected. (Unlike the Bartlett and Parzen kernels, the
4600  QS bandwidth need not be an integer.)
4601
4602Time series
4603
4604  horizon: one integer (the default is based on the frequency of the data).
4605  Sets the horizon for impulse responses and forecast variance
4606  decompositions in the context of vector autoregressions.
4607
4608  vecm_norm: phillips (the default), diag, first or none. Used in the
4609  context of VECM estimation via the "vecm" command for identifying the
4610  cointegration vectors. See the guia de utilização do Gretl (Capítulo
4611  33) for details.
4612
4613Interaction with R
4614
4615  R_lib: on (the default) or off. When sending instructions to be executed
4616  by R, use the R shared library by preference to the R executable, if the
4617  library is available.
4618
4619  R_functions: off (the default) or on. Recognize functions defined in R as
4620  if they were native functions (the namespace prefix "R." is required). See
4621  guia de utilização do Gretl (Capítulo 44) for details on this and the
4622  previous item.
4623
4624# setinfo Dataset
4625
4626Argumento:  series
4627Opções:     --description=string (set description)
4628            --graph-name=string (set graph name)
4629            --discrete (mark series as discrete)
4630            --continuous (mark series as continuous)
4631Exemplos:   setinfo x1 --description="Description of x1"
4632            setinfo y --graph-name="Some string"
4633            setinfo z --discrete
4634
4635Sets up to three attributes of series, given by name or ID number, as
4636follows.
4637
4638If the --description flag is given followed by a string in double quotes,
4639that string is used to set the variable's descriptive label. This label is
4640shown in response to the "labels" command, and is also shown in the main
4641window of the GUI program.
4642
4643If the --graph-name flag is given followed by a quoted string, that string
4644will be used in place of the variable's name in graphs.
4645
4646If one or other of the --discrete or --continuous option flags is given, the
4647variable's numerical character is set accordingly. The default is to treat
4648all series as continuous; setting a series as discrete affects the way the
4649variable is handled in frequency plots.
4650
4651Caminho de Menu:    /Variable/Edit attributes
4652Acesso alternativo: Main window pop-up menu
4653
4654# setmiss Dataset
4655
4656Argumentos: value [ varlist ]
4657Exemplos:   setmiss -1
4658            setmiss 100 x2
4659
4660Get the program to interpret some specific numerical data value (the first
4661parameter to the command) as a code for "missing", in the case of imported
4662data. If this value is the only parameter, as in the first example above,
4663the interpretation will be applied to all series in the data set. If "value"
4664is followed by a list of variables, by name or number, the interpretation is
4665confined to the specified variable(s). Thus in the second example the data
4666value 100 is interpreted as a code for "missing", but only for the variable
4667x2.
4668
4669Caminho de Menu:    /Data/Set missing value code
4670
4671# setobs Dataset
4672
4673Variantes:  setobs periodicity startobs
4674            setobs unitvar timevar --panel-vars
4675Opções:     --cross-section (interpret as cross section)
4676            --time-series (interpret as time series)
4677            --stacked-cross-section (interpret as panel data)
4678            --stacked-time-series (interpret as panel data)
4679            --panel-vars (use index variables, see below)
4680            --panel-time (see below)
4681            --panel-groups (see below)
4682Exemplos:   setobs 4 1990:1 --time-series
4683            setobs 12 1978:03
4684            setobs 1 1 --cross-section
4685            setobs 20 1:1 --stacked-time-series
4686            setobs unit year --panel-vars
4687
4688This command forces the program to interpret the current data set as having
4689a specified structure.
4690
4691In the first form of the command the periodicity, which must be an integer,
4692represents frequency in the case of time-series data (1 = annual; 4 =
4693quarterly; 12 = monthly; 52 = weekly; 5, 6, or 7 = daily; 24 = hourly). In
4694the case of panel data the periodicity means the number of lines per data
4695block: this corresponds to the number of cross-sectional units in the case
4696of stacked cross-sections, or the number of time periods in the case of
4697stacked time series. In the case of simple cross-sectional data the
4698periodicity should be set to 1.
4699
4700The starting observation represents the starting date in the case of time
4701series data. Years may be given with two or four digits; subperiods (for
4702example, quarters or months) should be separated from the year with a colon.
4703In the case of panel data the starting observation should be given as 1:1;
4704and in the case of cross-sectional data, as 1. Starting observations for
4705daily or weekly data should be given in the form YYYY-MM-DD (or simply as 1
4706for undated data).
4707
4708If no explicit option flag is given to indicate the structure of the data
4709the program will attempt to guess the structure from the information given.
4710
4711The second form of the command (which requires the --panel-vars flag) may be
4712used to impose a panel interpretation when the data set contains variables
4713that uniquely identify the cross-sectional units and the time periods. The
4714data set will be sorted as stacked time series, by ascending values of the
4715units variable, unitvar.
4716
4717Panel-specific options
4718
4719The --panel-time and --panel-groups options can only be used with a dataset
4720which has already been defined as a panel.
4721
4722The purpose of --panel-time is to set extra information regarding the time
4723dimension of the panel. This should be given on the pattern of the first
4724form of setobs noted above. For example, the following may be used to
4725indicate that the time dimension of a panel is quarterly, starting in the
4726first quarter of 1990.
4727
4728	setobs 4 1990:1 --panel-time
4729
4730The purpose of --panel-groups is to create a string-valued series holding
4731names for the groups (individuals, cross-sectional units) in the panel.
4732(This will be used where appropriate in panel graphs.) With this option you
4733supply either one or two arguments as follows.
4734
4735First case: the (single) argument is the name of a string-valued series. If
4736the number of distinct values equals the number of groups in the panel this
4737series is used to define the group names. If necessary, the numerical
4738content of the series will be adjusted such that the values are all 1s for
4739the first group, all 2s for the second, and so on. If the number of string
4740values doesn't match the number of groups an error is flagged.
4741
4742Second case: the first argument is the name of a series and the second is a
4743string literal or variable holding a name for each group. The series will be
4744created if it does not already exist. If the second argument is a string
4745literal or string variable the group names should be separated by spaces; if
4746a name includes spaces it should be wrapped in backslash-escaped
4747double-quotes. Alternatively the second argument may be an array of strings.
4748
4749For example, the following will create a series named country in which the
4750names in cstrs are each repeated T times, T being the time-series length of
4751the panel.
4752
4753	string cstrs = sprintf("France Germany Italy \"United Kingdom\"")
4754	setobs country cstrs --panel-groups
4755
4756Caminho de Menu:    /Data/Dataset structure
4757
4758# setopt Programming
4759
4760Argumentos: command [ action ] options
4761Exemplos:   setopt mle --hessian
4762            setopt ols persist --quiet
4763            setopt ols clear
4764
4765This command enables the pre-setting of options for a specified command.
4766Ordinarily this is not required, but it may be useful for the writers of
4767hansl functions when they wish to make certain command options conditional
4768on the value of an argument supplied by the caller.
4769
4770For example, suppose a function offers a boolean "quiet" switch, whose
4771intended effect is to suppress the printing of results from a certain
4772regression executed within the function. In that case one might write:
4773
4774	if quiet
4775	  setopt ols --quiet
4776	endif
4777	ols ...
4778
4779The --quiet option will then be applied to the next ols command if and only
4780if the variable quiet has a non-zero value.
4781
4782By default, options set in this way apply only to the following instance of
4783command; they are not persistent. However if you give persist as the value
4784for action the options will continue to apply to the given command until
4785further notice. The antidote to the persist action is clear: this erases any
4786stored setting for the specified command.
4787
4788It should be noted that options set via setopt are compounded with any
4789options attached to the target command directly. So for example one might
4790append the --hessian option to an mle command unconditionally but use setopt
4791to add --quiet conditionally.
4792
4793# shell Utilities
4794
4795Argumento:  shellcommand
4796Exemplos:   ! ls -al
4797            ! notepad
4798            launch notepad
4799
4800An exclamation mark, "!", or the keyword "launch", at the beginning of a
4801command line is interpreted as an escape to the user's shell. Thus arbitrary
4802shell commands can be executed from within gretl. When "!" is used, the
4803external command is executed synchronously. That is, gretl waits for it to
4804complete before proceeding. If you want to start another program from within
4805gretl and not wait for its completion (asynchronous operation), use "launch"
4806instead.
4807
4808For reasons of security this facility is not enabled by default. To activate
4809it, check the box titled "Allow shell commands" under the File, Preferences
4810menu in the GUI program. This also makes shell commands available in the
4811command-line program (and is the only way to do so).
4812
4813# smpl Dataset
4814
4815Variantes:  smpl startobs endobs
4816            smpl +i -j
4817            smpl dumvar --dummy
4818            smpl condition --restrict
4819            smpl --no-missing [ varlist ]
4820            smpl --no-all-missing [ varlist ]
4821            smpl --contiguous [ varlist ]
4822            smpl n --random
4823            smpl full
4824Opções:     --dummy (argument is a dummy variable)
4825            --restrict (apply boolean restriction)
4826            --replace (replace any existing boolean restriction)
4827            --no-missing (restrict to valid observations)
4828            --no-all-missing (omit empty observations (see below))
4829            --contiguous (see below)
4830            --random (form random sub-sample)
4831            --permanent (see below)
4832            --balanced (panel data: try to retain balanced panel)
4833Exemplos:   smpl 3 10
4834            smpl 1960:2 1982:4
4835            smpl +1 -1
4836            smpl x > 3000 --restrict
4837            smpl y > 3000 --restrict --replace
4838            smpl 100 --random
4839
4840Resets the sample range. The new range can be defined in several ways. In
4841the first alternate form (and the first two examples) above, startobs and
4842endobs must be consistent with the periodicity of the data. Either one may
4843be replaced by a semicolon to leave the value unchanged. In the second form,
4844the integers i and j (which may be positive or negative, and should be
4845signed) are taken as offsets relative to the existing sample range. In the
4846third form dummyvar must be an indicator variable with values 0 or 1 at each
4847observation; the sample will be restricted to observations where the value
4848is 1. The fourth form, using --restrict, restricts the sample to
4849observations that satisfy the given Boolean condition (which is specified
4850according to the syntax of the "genr" command).
4851
4852The options --no-missing and --no-all-missing may be used to exclude from
4853the sample observations for which data are missing. The first variant
4854excludes those rows in the dataset for which at least one variable has a
4855missing value, while the second excludes just those rows on which all
4856variables have missing values. In each case the test is confined to the
4857variables in varlist if this argument is given, otherwise it is applied to
4858all series -- with the qualification that in the case of --no-all-missing
4859and no varlist, the generic variables index and time are ignored.
4860
4861The --contiguous form of smpl is intended for use with time series data. The
4862effect is to trim any observations at the start and end of the current
4863sample range that contain missing values (either for the variables in
4864varlist, or for all data series if no varlist is given). Then a check is
4865performed to see if there are any missing values in the remaining range; if
4866so, an error is flagged.
4867
4868With the --random flag, the specified number of cases are selected from the
4869current dataset at random (without replacement). If you wish to be able to
4870replicate this selection you should set the seed for the random number
4871generator first (see the "set" command).
4872
4873The final form, smpl full, restores the full data range.
4874
4875Note that sample restrictions are, by default, cumulative: the baseline for
4876any smpl command is the current sample. If you wish the command to act so as
4877to replace any existing restriction you can add the option flag --replace to
4878the end of the command. (But this option is not compatible with the
4879--contiguous option.)
4880
4881The internal variable obs may be used with the --restrict form of smpl to
4882exclude particular observations from the sample. For example
4883
4884	smpl obs!=4 --restrict
4885
4886will drop just the fourth observation. If the data points are identified by
4887labels,
4888
4889	smpl obs!="USA" --restrict
4890
4891will drop the observation with label "USA".
4892
4893One point should be noted about the --dummy, --restrict and --no-missing
4894forms of smpl: "structural" information in the data file (regarding the time
4895series or panel nature of the data) is likely to be lost when this command
4896is issued. You may reimpose structure with the "setobs" command. A related
4897option, for use with panel data, is the --balanced flag: this requests that
4898a balanced panel is reconstituted after sub-sampling, via the insertion of
4899"missing rows" if need be. But note that it is not always possible to comply
4900with this request.
4901
4902By default, restrictions on the current sample range are undoable: by doing
4903smpl full you can restore the unrestricted dataset. However, the --permanent
4904flag can be used to substitute the restricted dataset for the original. This
4905option is only available in conjunction with the --restrict, --dummy,
4906--no-missing, --no-all-missing or --random forms of smpl.
4907
4908Please see guia de utilização do Gretl (Capítulo 5) for further details.
4909
4910Caminho de Menu:    /Sample
4911
4912# spearman Statistics
4913
4914Argumentos: series1 series2
4915Opção:      --verbose (print ranked data)
4916
4917Prints Spearman's rank correlation coefficient for the series series1 and
4918series2. The variables do not have to be ranked manually in advance; the
4919function takes care of this.
4920
4921The automatic ranking is from largest to smallest (i.e. the largest data
4922value gets rank 1). If you need to invert this ranking, create a new
4923variable which is the negative of the original. For example:
4924
4925	series altx = -x
4926	spearman altx y
4927
4928Caminho de Menu:    /Model/Robust estimation/Rank correlation
4929
4930# sprintf Printing
4931
4932Argumentos: stringvar format , args
4933
4934This command works exactly like the "printf" command, printing the given
4935arguments under the control of the format string, except that the result is
4936written into the named string, stringvar.
4937
4938# square Transformations
4939
4940Argumento:  varlist
4941Opção:      --cross (generate cross-products as well as squares)
4942
4943Generates new series which are squares of the series in varlist (plus
4944cross-products if the --cross option is given). For example, "square x y"
4945will generate sq_x = x squared, sq_y = y squared and (optionally) x_y = x
4946times y. If a particular variable is a dummy variable it is not squared
4947because we will get the same variable.
4948
4949Caminho de Menu:    /Add/Squares of selected variables
4950
4951# store Dataset
4952
4953Argumentos: filename [ varlist ]
4954Opções:     --omit-obs (see below, on CSV format)
4955            --no-header (see below, on CSV format)
4956            --gnu-octave (use GNU Octave format)
4957            --gnu-R (use GNU R format)
4958            --gzipped[=level] (apply gzip compression)
4959            --jmulti (use JMulti ASCII format)
4960            --dat (use PcGive ASCII format)
4961            --decimal-comma (use comma as decimal character)
4962            --database (use gretl database format)
4963            --overwrite (see below, on database format)
4964            --comment=string (see below)
4965
4966Save data to filename. By default all currently defined series are saved but
4967the optional varlist argument can be used to select a subset of series. If
4968the dataset is sub-sampled, only the observations in the current sample
4969range are saved.
4970
4971The format in which the data are written may be controlled in the first
4972instance by the extension or suffix of filename, as follows:
4973
4974  .gdt, or no extension: gretl's native XML data format. (If no extension is
4975  provided, ".gdt" is added automatically.)
4976
4977  .gtdb: gretl's native binary data format.
4978
4979  .csv: comma-separated values (CSV).
4980
4981  .txt or .asc: space-separated values.
4982
4983  .R: GNU R format.
4984
4985  .m: GNU Octave format.
4986
4987The format-related option flags shown above can be used to force the issue
4988of the save format independently of the filename (or to get gretl to write
4989in the formats of PcGive or JMulTi). However, if filename has extension .gdt
4990or .gdtb this necessarily implies use of native format and the addition of a
4991conflicting option flag will generate an error.
4992
4993When data are saved in native format (only), the --gzipped option may be
4994used for data compression, which can be useful for large datasets. The
4995optional parameter for this flag controls the level of compression (from 0
4996to 9): higher levels produce a smaller file, but compression takes longer.
4997The default level is 1; a level of 0 means that no compression is applied.
4998
4999The option flags --omit-obs and --no-header are applicable only when saving
5000data in CSV format. By default, if the data are time series or panel, or if
5001the dataset includes specific observation markers, the CSV file includes a
5002first column identifying the observations (e.g. by date). If the --omit-obs
5003flag is given this column is omitted. The --no-header flag suppresses the
5004usual printing of the names of the variables at the top of the columns.
5005
5006The option flag --decimal-comma is also confined to the case of saving data
5007in CSV format. The effect of this option is to replace the decimal point
5008with the decimal comma; in addition the column separator is forced to be a
5009semicolon.
5010
5011The option of saving in gretl database format is intended to help with the
5012construction of large sets of series, possibly having mixed frequencies and
5013ranges of observations. At present this option is available only for annual,
5014quarterly or monthly time-series data. If you save to a file that already
5015exists, the default action is to append the newly saved series to the
5016existing content of the database. In this context it is an error if one or
5017more of the variables to be saved has the same name as a variable that is
5018already present in the database. The --overwrite flag has the effect that,
5019if there are variable names in common, the newly saved variable replaces the
5020variable of the same name in the original dataset.
5021
5022The --comment option is available when saving data as a database or in CSV
5023format. The required parameter is a double-quoted one-line string, attached
5024to the option flag with an equals sign. The string is inserted as a comment
5025into the database index file or at the top of the CSV output.
5026
5027The store command behaves in a special manner in the context of a
5028"progressive loop". See guia de utilização do Gretl (Capítulo 13) for
5029details.
5030
5031Caminho de Menu:    /File/Save data; /File/Export data
5032
5033# summary Statistics
5034
5035Variantes:  summary [ varlist ]
5036            summary --matrix=matname
5037Opções:     --simple (basic statistics only)
5038            --weight=wvar (weighting variable)
5039            --by=byvar (see below)
5040
5041In its first form, this command prints summary statistics for the variables
5042in varlist, or for all the variables in the data set if varlist is omitted.
5043By default, output consists of the mean, standard deviation (sd),
5044coefficient of variation (= sd/mean), median, minimum, maximum, skewness
5045coefficient, and excess kurtosis. If the --simple option is given, output is
5046restricted to the mean, minimum, maximum and standard deviation.
5047
5048If the --by option is given (in which case the parameter byvar should be the
5049name of a discrete variable), then statistics are printed for sub-samples
5050corresponding to the distinct values taken on by byvar. For example, if
5051byvar is a (binary) dummy variable, statistics are given for the cases byvar
5052= 0 and byvar = 1. Note: at present, this option is incompatible with the
5053--weight option.
5054
5055If the alternative form is given, using a named matrix, then summary
5056statistics are printed for each column of the matrix. The --by option is not
5057available in this case.
5058
5059Caminho de Menu:    /View/Summary statistics
5060Acesso alternativo: Main window pop-up menu
5061
5062# system Estimation
5063
5064Variantes:  system method=estimator
5065            sysname <- system
5066Exemplos:   "Klein Model 1" <- system
5067            system method=sur
5068            system method=3sls
5069            Ver tambémklein.inp, kmenta.inp, greene14_2.inp
5070
5071Starts a system of equations. Either of two forms of the command may be
5072given, depending on whether you wish to save the system for estimation in
5073more than one way or just estimate the system once.
5074
5075To save the system you should assign it a name, as in the first example (if
5076the name contains spaces it must be surrounded by double quotes). In this
5077case you estimate the system using the "estimate" command. With a saved
5078system of equations, you are able to impose restrictions (including
5079cross-equation restrictions) using the "restrict" command.
5080
5081Alternatively you can specify an estimator for the system using method=
5082followed by a string identifying one of the supported estimators: "ols"
5083(Ordinary Least Squares), "tsls" (Two-Stage Least Squares) "sur" (Seemingly
5084Unrelated Regressions), "3sls" (Three-Stage Least Squares), "fiml" (Full
5085Information Maximum Likelihood) or "liml" (Limited Information Maximum
5086Likelihood). In this case the system is estimated once its definition is
5087complete.
5088
5089An equation system is terminated by the line "end system". Within the system
5090four sorts of statement may be given, as follows.
5091
5092  "equation": specify an equation within the system. At least two such
5093  statements must be provided.
5094
5095  "instr": for a system to be estimated via Three-Stage Least Squares, a
5096  list of instruments (by variable name or number). Alternatively, you can
5097  put this information into the "equation" line using the same syntax as in
5098  the "tsls" command.
5099
5100  "endog": for a system of simultaneous equations, a list of endogenous
5101  variables. This is primarily intended for use with FIML estimation, but
5102  with Three-Stage Least Squares this approach may be used instead of giving
5103  an "instr" list; then all the variables not identified as endogenous will
5104  be used as instruments.
5105
5106  "identity": for use with FIML, an identity linking two or more of the
5107  variables in the system. This sort of statement is ignored when an
5108  estimator other than FIML is used.
5109
5110After estimation using the "system" or "estimate" commands the following
5111accessors can be used to retrieve additional information:
5112
5113  $uhat: the matrix of residuals, one column per equation.
5114
5115  $yhat: matrix of fitted values, one column per equation.
5116
5117  $coeff: column vector of coefficients (all the coefficients from the first
5118  equation, followed by those from the second equation, and so on).
5119
5120  $vcv: covariance matrix of the coefficients. If there are k elements in
5121  the $coeff vector, this matrix is k by k.
5122
5123  $sigma: cross-equation residual covariance matrix.
5124
5125  $sysGamma, $sysA and $sysB: structural-form coefficient matrices (see
5126  below).
5127
5128If you want to retrieve the residuals or fitted values for a specific
5129equation as a data series, select a column from the $uhat or $yhat matrix
5130and assign it to a series, as in
5131
5132	series uh1 = $uhat[,1]
5133
5134The structural-form matrices correspond to the following representation of a
5135simultaneous equations model:
5136
5137  Gamma y(t) = A y(t-1) + B x(t) + e(t)
5138
5139If there are n endogenous variables and k exogenous variables, Gamma is an n
5140x n matrix and B is n x k. If the system contains no lags of the endogenous
5141variables then the A matrix is not present. If the maximum lag of an
5142endogenous regressor is p, the A matrix is n x np.
5143
5144Caminho de Menu:    /Model/Simultaneous equations
5145
5146# tabprint Printing
5147
5148Opções:     --rtf (Produce RTF instead of LaTeX)
5149            --csv (Produce CSV instead of LaTeX)
5150            --complete (Create a complete document)
5151            --format="f1|f2|f3|f4" (Specify a custom format)
5152            --output=filename (send output to specified file)
5153
5154Must follow the estimation of a model. Prints the estimated model in tabular
5155form -- by default as LaTeX, but as RTF if the --rtf flag is given or as CSV
5156is the --csv flag is given. If a filename is specified using the --output
5157option output goes to that file, otherwise it goes to a file with a name of
5158the form model_N followed by the extension tex, rtf or csv, where N is the
5159number of models estimated to date in the current session.
5160
5161If CSV format is selected, values are comma-separated unless the decimal
5162comma is in force, in which case the separator is the semicolon. Note that
5163CSV output may be less complete than the other formats.
5164
5165The further options discussed below are available only when printing the
5166model as LaTeX.
5167
5168If the --complete flag is given the LaTeX file is a complete document, ready
5169for processing; otherwise it must be included in a document.
5170
5171If you wish alter the appearance of the tabular output, you can specify a
5172custom row format using the --format flag. The format string must be
5173enclosed in double quotes and must be tied to the flag with an equals sign.
5174The pattern for the format string is as follows. There are four fields,
5175representing the coefficient, standard error, t-ratio and p-value
5176respectively. These fields should be separated by vertical bars; they may
5177contain a printf-type specification for the formatting of the numeric value
5178in question, or may be left blank to suppress the printing of that column
5179(subject to the constraint that you can't leave all the columns blank). Here
5180are a few examples:
5181
5182	--format="%.4f|%.4f|%.4f|%.4f"
5183	--format="%.4f|%.4f|%.3f|"
5184	--format="%.5f|%.4f||%.4f"
5185	--format="%.8g|%.8g||%.4f"
5186
5187The first of these specifications prints the values in all columns using 4
5188decimal places. The second suppresses the p-value and prints the t-ratio to
51893 places. The third omits the t-ratio. The last one again omits the t, and
5190prints both coefficient and standard error to 8 significant figures.
5191
5192Once you set a custom format in this way, it is remembered and used for the
5193duration of the gretl session. To revert to the default format you can use
5194the special variant --format=default.
5195
5196Caminho de Menu:    Model window, /LaTeX
5197
5198# textplot Graphs
5199
5200Argumento:  varlist
5201Opções:     --time-series (plot by observation)
5202            --one-scale (force a single scale)
5203            --tall (use 40 rows)
5204
5205Quick and simple ASCII graphics. Without the --time-series flag, varlist
5206must contain at least two series, the last of which is taken as the variable
5207for the x axis, and a scatter plot is produced. In this case the --tall
5208option may be used to produce a graph in which the y axis is represented by
520940 rows of characters (the default is 20 rows).
5210
5211With the --time-series, a plot by observation is produced. In this case the
5212option --one-scale may be used to force the use of a single scale; otherwise
5213if varlist contains more than one series the data may be scaled. Each line
5214represents an observation, with the data values plotted horizontally.
5215
5216See also "gnuplot".
5217
5218# tobit Estimation
5219
5220Argumentos: depvar indepvars
5221Opções:     --llimit=lval (specify left bound)
5222            --rlimit=rval (specify right bound)
5223            --vcv (print covariance matrix)
5224            --robust (robust standard errors)
5225            --cluster=clustvar (see "logit" for explanation)
5226            --verbose (print details of iterations)
5227
5228Estimates a Tobit model, which may be appropriate when the dependent
5229variable is "censored". For example, positive and zero values of purchases
5230of durable goods on the part of individual households are observed, and no
5231negative values, yet decisions on such purchases may be thought of as
5232outcomes of an underlying, unobserved disposition to purchase that may be
5233negative in some cases.
5234
5235By default it is assumed that the dependent variable is censored at zero on
5236the left and is uncensored on the right. However you can use the options
5237--llimit and --rlimit to specify a different pattern of censoring. Note that
5238if you specify a right bound only, the assumption is then that the dependent
5239variable is uncensored on the left.
5240
5241The Tobit model is a special case of interval regression, which is supported
5242via the "intreg" command.
5243
5244Caminho de Menu:    /Model/Limited dependent variable/Tobit
5245
5246# tsls Estimation
5247
5248Argumentos: depvar indepvars ; instruments
5249Opções:     --no-tests (don't do diagnostic tests)
5250            --vcv (print covariance matrix)
5251            --robust (robust standard errors)
5252            --cluster=clustvar (clustered standard errors)
5253            --liml (use Limited Information Maximum Likelihood)
5254            --gmm (use the Generalized Method of Moments)
5255Exemplo:    tsls y1 0 y2 y3 x1 x2 ; 0 x1 x2 x3 x4 x5 x6
5256
5257Computes Instrumental Variables (IV) estimates, by default using two-stage
5258least squares (TSLS) but see below for further options. The dependent
5259variable is depvar, indepvars is the list of regressors (which is presumed
5260to include at least one endogenous variable); and instruments is the list of
5261instruments (exogenous and/or predetermined variables). If the instruments
5262list is not at least as long as indepvars, the model is not identified.
5263
5264In the above example, the ys are endogenous and the xs are the exogenous
5265variables. Note that exogenous regressors should appear in both lists.
5266
5267Output for two-stage least squares estimates includes the Hausman test and,
5268if the model is over-identified, the Sargan over-identification test. In the
5269Hausman test, the null hypothesis is that OLS estimates are consistent, or
5270in other words estimation by means of instrumental variables is not really
5271required. A model of this sort is over-identified if there are more
5272instruments than are strictly required. The Sargan test is based on an
5273auxiliary regression of the residuals from the two-stage least squares model
5274on the full list of instruments. The null hypothesis is that all the
5275instruments are valid, and suspicion is thrown on this hypothesis if the
5276auxiliary regression has a significant degree of explanatory power. For a
5277good explanation of both tests see chapter 8 of Davidson and MacKinnon
5278(2004).
5279
5280For both TSLS and LIML estimation, an additional test result is shown
5281provided that the model is estimated under the assumption of i.i.d. errors
5282(that is, the --robust option is not selected). This is a test for weakness
5283of the instruments. Weak instruments can lead to serious problems in IV
5284regression: biased estimates and/or incorrect size of hypothesis tests based
5285on the covariance matrix, with rejection rates well in excess of the nominal
5286significance level (Stock, Wright and Yogo, 2002). The test statistic is the
5287first-stage F-test if the model contains just one endogenous regressor,
5288otherwise it is the smallest eigenvalue of the matrix counterpart of the
5289first stage F. Critical values based on the Monte Carlo analysis of Stock
5290and Yogo (2003) are shown when available.
5291
5292The R-squared value printed for models estimated via two-stage least squares
5293is the square of the correlation between the dependent variable and the
5294fitted values.
5295
5296For details on the effects of the --robust and --cluster options, please see
5297the help for "ols".
5298
5299As alternatives to TSLS, the model may be estimated via Limited Information
5300Maximum Likelihood (the --liml option) or via the Generalized Method of
5301Moments (--gmm option). Note that if the model is just identified these
5302methods should produce the same results as TSLS, but if it is
5303over-identified the results will differ in general.
5304
5305If GMM estimation is selected, the following additional options become
5306available:
5307
5308  --two-step: perform two-step GMM rather than the default of one-step.
5309
5310  --iterate: Iterate GMM to convergence.
5311
5312  --weights=Wmat: specify a square matrix of weights to be used when
5313  computing the GMM criterion function. The dimension of this matrix must
5314  equal the number of instruments. The default is an appropriately sized
5315  identity matrix.
5316
5317Caminho de Menu:    /Model/Instrumental variables
5318
5319# var Estimation
5320
5321Argumentos: order ylist [ ; xlist ]
5322Opções:     --nc (do not include a constant)
5323            --trend (include a linear trend)
5324            --seasonals (include seasonal dummy variables)
5325            --robust (robust standard errors)
5326            --robust-hac (HAC standard errors)
5327            --quiet (skip output of individual equations)
5328            --silent (don't print anything)
5329            --impulse-responses (print impulse responses)
5330            --variance-decomp (print variance decompositions)
5331            --lagselect (show criteria for lag selection)
5332Exemplos:   var 4 x1 x2 x3 ; time mydum
5333            var 4 x1 x2 x3 --seasonals
5334            var 12 x1 x2 x3 --lagselect
5335
5336Sets up and estimates (using OLS) a vector autoregression (VAR). The first
5337argument specifies the lag order -- or the maximum lag order in case the
5338--lagselect option is given (see below). The order may be given numerically,
5339or as the name of a pre-existing scalar variable. Then follows the setup for
5340the first equation. Do not include lags among the elements of ylist -- they
5341will be added automatically. The semi-colon separates the stochastic
5342variables, for which order lags will be included, from any exogenous
5343variables in xlist. Note that a constant is included automatically unless
5344you give the --nc flag, a trend can be added with the --trend flag, and
5345seasonal dummy variables may be added using the --seasonals flag.
5346
5347While a VAR specification usually includes all lags from 1 to a given
5348maximum, it is possible to select a specific set of lags. To do this,
5349substitute for the regular (scalar) order argument either the name of a
5350predefined vector or a comma-separated list of lags, enclosed in braces. We
5351show below two ways of specifying that a VAR should include lags 1, 2 and 4
5352(but not lag 3):
5353
5354	var {1,2,4} ylist
5355	matrix p = {1,2,4}
5356	var p ylist
5357
5358A separate regression is reported for each variable in ylist. Output for
5359each equation includes F-tests for zero restrictions on all lags of each of
5360the variables, an F-test for the significance of the maximum lag, and, if
5361the --impulse-responses flag is given, forecast variance decompositions and
5362impulse responses.
5363
5364Forecast variance decompositions and impulse responses are based on the
5365Cholesky decomposition of the contemporaneous covariance matrix, and in this
5366context the order in which the (stochastic) variables are given matters. The
5367first variable in the list is assumed to be "most exogenous" within-period.
5368The horizon for variance decompositions and impulse responses can be set
5369using the "set" command. For retrieval of a specified impulse response
5370function in matrix form, see the "irf" function.
5371
5372If the --robust option is given, standard errors are corrected for
5373heteroskedasticity. Alternatively, the --robust-hac option can be given to
5374produce standard errors that are robust with respect to both
5375heteroskedasticity and autocorrelation (HAC). In general the latter
5376correction should not be needed if the VAR includes sufficient lags.
5377
5378If the --lagselect option is given, the first parameter to the var command
5379is taken as the maximum lag order. Output consists of a table showing the
5380values of the Akaike (AIC), Schwarz (BIC) and Hannan-Quinn (HQC) information
5381criteria computed from VARs of order 1 to the given maximum. This is
5382intended to help with the selection of the optimal lag order. The usual VAR
5383output is not presented. The table of information criteria may be retrieved
5384as a matrix via the $test accessor.
5385
5386Caminho de Menu:    /Model/Time series/Vector autoregression
5387
5388# varlist Dataset
5389
5390Opções:     --scalars (list scalars)
5391            --accessors (list accessor variables)
5392
5393By default, prints a listing of the (series) variables currently available;
5394"ls" may be used as an alias for this command.
5395
5396If the --scalars option is given, prints a listing of any currently defined
5397scalar variables and their values. Otherwise, if the --accessors option is
5398given, prints a list of the internal variables currently available via
5399accessors such as "$nobs" and "$uhat".
5400
5401# vartest Tests
5402
5403Argumentos: series1 series2
5404
5405Calculates the F statistic for the null hypothesis that the population
5406variances for the variables series1 and series2 are equal, and shows its
5407p-value.
5408
5409Caminho de Menu:    /Tools/Test statistic calculator
5410
5411# vecm Estimation
5412
5413Argumentos: order rank ylist [ ; xlist ] [ ; rxlist ]
5414Opções:     --nc (no constant)
5415            --rc (restricted constant)
5416            --uc (unrestricted constant)
5417            --crt (constant and restricted trend)
5418            --ct (constant and unrestricted trend)
5419            --seasonals (include centered seasonal dummies)
5420            --quiet (skip output of individual equations)
5421            --silent (don't print anything)
5422            --impulse-responses (print impulse responses)
5423            --variance-decomp (print variance decompositions)
5424Exemplos:   vecm 4 1 Y1 Y2 Y3
5425            vecm 3 2 Y1 Y2 Y3 --rc
5426            vecm 3 2 Y1 Y2 Y3 ; X1 --rc
5427            Ver tambémdenmark.inp, hamilton.inp
5428
5429A VECM is a form of vector autoregression or VAR (see "var"), applicable
5430where the variables in the model are individually integrated of order 1
5431(that is, are random walks, with or without drift), but exhibit
5432cointegration. This command is closely related to the Johansen test for
5433cointegration (see "coint2").
5434
5435The order parameter to this command represents the lag order of the VAR
5436system. The number of lags in the VECM itself (where the dependent variable
5437is given as a first difference) is one less than order.
5438
5439The rank parameter represents the cointegration rank, or in other words the
5440number of cointegrating vectors. This must be greater than zero and less
5441than or equal to (generally, less than) the number of endogenous variables
5442given in ylist.
5443
5444ylist supplies the list of endogenous variables, in levels. The inclusion of
5445deterministic terms in the model is controlled by the option flags. The
5446default if no option is specified is to include an "unrestricted constant",
5447which allows for the presence of a non-zero intercept in the cointegrating
5448relations as well as a trend in the levels of the endogenous variables. In
5449the literature stemming from the work of Johansen (see for example his 1995
5450book) this is often referred to as "case 3". The first four options given
5451above, which are mutually exclusive, produce cases 1, 2, 4 and 5
5452respectively. The meaning of these cases and the criteria for selecting a
5453case are explained in guia de utilização do Gretl (Capítulo 33).
5454
5455The optional lists xlist and rxlist allow you to specify sets of exogenous
5456variables which enter the model either unrestrictedly (xlist) or restricted
5457to the cointegration space (rxlist). These lists are separated from ylist
5458and from each other by semicolons.
5459
5460The --seasonals option, which may be combined with any of the other options,
5461specifies the inclusion of a set of centered seasonal dummy variables. This
5462option is available only for quarterly or monthly data.
5463
5464The first example above specifies a VECM with lag order 4 and a single
5465cointegrating vector. The endogenous variables are Y1, Y2 and Y3. The second
5466example uses the same variables but specifies a lag order of 3 and two
5467cointegrating vectors; it also specifies a "restricted constant", which is
5468appropriate if the cointegrating vectors may have a non-zero intercept but
5469the Y variables have no trend.
5470
5471Following estimation of a VECM some special accessors are available:
5472$jalpha, $jbeta and $jvbeta retrieve, respectively, the α and beta matrices
5473and the estimated variance of beta. For retrieval of a specified impulse
5474response function in matrix form, see the "irf" function.
5475
5476Caminho de Menu:    /Model/Time series/VECM
5477
5478# vif Tests
5479
5480Must follow the estimation of a model which includes at least two
5481independent variables. Calculates and displays the Variance Inflation
5482Factors (VIFs) for the regressors. The VIF for regressor j is defined as
5483
5484  1/(1 - Rj^2)
5485
5486where R_j is the coefficient of multiple correlation between regressor j and
5487the other regressors. The factor has a minimum value of 1.0 when the
5488variable in question is orthogonal to the other independent variables.
5489Neter, Wasserman, and Kutner (1990) suggest inspecting the largest VIF as a
5490diagnostic for collinearity; a value greater than 10 is sometimes taken as
5491indicating a problematic degree of collinearity.
5492
5493Caminho de Menu:    Model window, /Tests/Collinearity
5494
5495# wls Estimation
5496
5497Argumentos: wtvar depvar indepvars
5498Opções:     --vcv (print covariance matrix)
5499            --robust (robust standard errors)
5500            --quiet (suppress printing of results)
5501
5502Computes weighted least squares (WLS) estimates using wtvar as the weight,
5503depvar as the dependent variable, and indepvars as the list of independent
5504variables. Let w denote the positive square root of wtvar; then WLS is
5505basically equivalent to an OLS regression of w * depvar on w * indepvars.
5506The R-squared, however, is calculated in a special manner, namely as
5507
5508  R^2 = 1 - ESS / WTSS
5509
5510where ESS is the error sum of squares (sum of squared residuals) from the
5511weighted regression and WTSS denotes the "weighted total sum of squares",
5512which equals the sum of squared residuals from a regression of the weighted
5513dependent variable on the weighted constant alone.
5514
5515If wtvar is a dummy variable, WLS estimation is equivalent to eliminating
5516all observations with value zero for wtvar.
5517
5518Caminho de Menu:    /Model/Other linear models/Weighted Least Squares
5519
5520# xcorrgm Statistics
5521
5522Argumentos: series1 series2 [ order ]
5523Opção:      --plot=mode-or-filename (see below)
5524Exemplo:    xcorrgm x y 12
5525
5526Prints and graphs the cross-correlogram for series1 and series2, which may
5527be specified by name or number. The values are the sample correlation
5528coefficients between the current value of series1 and successive leads and
5529lags of series2.
5530
5531If an order value is specified the length of the cross-correlogram is
5532limited to at most that number of leads and lags, otherwise the length is
5533determined automatically, as a function of the frequency of the data and the
5534number of observations.
5535
5536By default, a plot of the cross-correlogram is produced: a gnuplot graph in
5537interactive mode or an ASCII graphic in batch mode. This can be adjusted via
5538the --plot option. The acceptable parameters to this option are none (to
5539suppress the plot); ascii (to produce a text graphic even when in
5540interactive mode); display (to produce a gnuplot graph even when in batch
5541mode); or a file name. The effect of providing a file name is as described
5542for the --output option of the "gnuplot" command.
5543
5544Caminho de Menu:    /View/Cross-correlogram
5545Acesso alternativo: Main window pop-up menu (multiple selection)
5546
5547# xtab Statistics
5548
5549Argumentos: ylist [ ; xlist ]
5550Opções:     --row (display row percentages)
5551            --column (display column percentages)
5552            --zeros (display zero entries)
5553            --matrix=matname (use frequencies from named matrix)
5554
5555Displays a contingency table or cross-tabulation for each combination of the
5556variables included in ylist; if a second list xlist is given, each variable
5557in ylist is cross-tabulated by row against each variable in xlist (by
5558column). Variables in these lists can be referenced by name or by number.
5559Note that all the variables must have been marked as discrete.
5560Alternatively, if the --matrix option is given, treat the named matrix as a
5561precomputed set of frequencies and display this as a cross-tabulation.
5562
5563By default the cell entries are given as frequency counts. The --row and
5564--column options (which are mutually exclusive), replace the counts with the
5565percentages for each row or column, respectively. By default, cells with a
5566zero count are left blank; the --zeros option, which has the effect of
5567showing zero counts explicitly, may be useful for importing the table into
5568another program, such as a spreadsheet.
5569
5570Pearson's chi-square test for independence is displayed if the expected
5571frequency under independence is at least 1.0e-7 for all cells. A common rule
5572of thumb for the validity of this statistic is that at least 80 percent of
5573cells should have expected frequencies of 5 or greater; if this criterion is
5574not met a warning is printed.
5575
5576If the contingency table is 2 by 2, Fisher's Exact Test for independence is
5577computed. Note that this test is based on the assumption that the row and
5578column totals are fixed, which may or may not be appropriate depending on
5579how the data were generated. The left p-value should be used when the
5580alternative to independence is negative association (values tend to cluster
5581in the lower left and upper right cells); the right p-value should be used
5582if the alternative is positive association. The two-tailed p-value for this
5583test is calculated by method (b) in section 2.1 of Agresti (1992): it is the
5584sum of the probabilities of all possible tables having the given row and
5585column totals and having a probability less than or equal to that of the
5586observed table.
5587
5588