• Nenhum resultado encontrado

Ox Workshop

N/A
N/A
Protected

Academic year: 2022

Share "Ox Workshop"

Copied!
54
0
0

Texto

(1)

Ox Workshop

Jurgen A. Doornik

Prepared for the 9th

Escola de S´eries Temporais e Econometria

Using Ox version 3

(2)

Contents

Preface iv

1 Introduction to the OxMetrics family 1

1.1 OxMetrics . . . 1

1.2 GiveWin . . . 1

1.3 Ox Professional . . . 2

1.4 Ox Packages . . . 2

1.5 PcGets . . . 3

1.6 PcGive . . . 3

1.7 PcNaive . . . 4

1.8 STAMP . . . 4

1.9 TSP/GiveWin . . . 5

2 Getting started with Ox 6 2.1 Ox versions . . . 6

2.2 Installation . . . 6

2.3 Testing the installation . . . 7

2.4 Data sets . . . 7

2.5 An Ox program to load the airline data . . . 8

2.6 Manipulating the airline data . . . 10

2.7 Using the database class . . . 11

3 Using Functions 13 3.1 Simple functions . . . 13

3.2 Function arguments . . . 14

3.3 Returning a value . . . 14

3.4 More database facilities . . . 15

3.5 Function declaration . . . 17

3.6 Returning values in an argument . . . 18

3.7 Multiple returns . . . 20

3.8 Using functions as arguments . . . 20 ii

(3)

CONTENTS iii

4 Ox Operators 23

4.1 Introduction . . . 23

4.2 Index operators . . . 23

4.3 Matrix operators . . . 24

4.4 Dot operators . . . 25

4.5 Relational and equality operators . . . 26

4.6 Logical operators . . . 26

4.7 Assignment operators . . . 28

4.8 Conditional operators . . . 28

4.9 And more operators . . . 29

4.10 Operator precedence . . . 29

5 Using Ox Packages 31 5.1 X12arima for GiveWin . . . 31

5.2 Arfima package . . . 33

5.2.1 Introduction . . . 33

5.2.2 Changing the example program for the airline data . . . 34

5.2.3 Interactive use with OxPack . . . 37

5.3 SsfPack . . . 38

5.3.1 State space form . . . 38

5.3.2 ARMA models in state space form . . . 39

5.3.3 Maximum likelihood estimation od airline model . . . 40

6 Object Oriented Programming 42 6.1 Introduction . . . 42

6.2 Using object oriented code . . . 42

6.3 Writing object-oriented code . . . 43

6.4 Inheritance . . . 45

References 48

Subject Index 49

(4)

Preface

This document was prepared for the Ox course at the 9th ESTE (Escola de S´eries Temporais e Econometria) in Belo Horizonte, August 7-10 2001. It draws heavily on material developed with various co-authors, in particular Siem Jan Koopman, Marius Ooms, and Neil Shephard.

The relevant references are Doornik and Ooms (2001), Doornik and Ooms (1999), Koopman, Shephard and Doornik (1999).

The Ox book (Doornik, 2001) contains the Ox reference documentation, a large part of which is also available in the online help.

c2001 J.A. Doornik

iv

(5)

Chapter 1

Introduction to the OxMetrics family

1.1 OxMetrics

OxMetrics (www.oxmetrics.com) is a family of of software packages providing an inte- grated solution for econometric modelling, econometric analysis of time series, forecasting, financial econometric modelling, or statistical analysis of cross-section and panel data.

The core packages of the family are GiveWin, which provides the user interface, data handling, and graphics, and Ox Professional, which provides the implementation language.

The other elements of the family are interactive, easy-to-use and powerful tools that can help solve your specific modelling and forecasting needs.

1.2 GiveWin

GiveWin (version 2) is the front-end for all the members of the OxMetrics family. GiveWin displays reports and graphics, which can be manipulated on screen, offers a calculator and algebraic language for transforming data, and enables the user to open multiple databases. A batch language allows for the automation of many of these tasks.

The edit window in GiveWin is based on OxEdit technology, allowing for unlimited undo/redo, column editing and sorting, and syntax highlighting for Ox, TSP and Gausstm; code. Users with the necessary programming skills can develop their own statistical modules for GiveWin (this is especially easy to do with Ox Professional).

GiveWin is interactive and graphics-oriented providing nearly 50 types of graphs, ranging from time-series plots to cross-plots, ACF, density, 3-D plots, automatic graphing of logs and growth rates, seasonal subplots, error fans and many others.

Facilities for publication quality graphics include LaTeX-style text to allow mathematics in a graph, as well as black and white mode; see for example 1.1.

1

(6)

2 Chapter 1 Introduction to the OxMetrics family

x−variable y−variable

z−variable

3−D graphs can be rotated, either one at a time or all together.

−2 −1 0 1 2

−2 0

2

0.51.0

1998 1999 2000

5.4 5.6 5.8

$(1 − \phi_1L − \phi_{12}L^{12}) (1 − L)^d (y_t − \mu) = \epsilon_t$

produces:

(1 − φ1L − φ12 12L ) (1 − L)d (ytµ) = εt

←

error fans Forecasts Ltotal

Figure 1.1 GiveWin graphics.

1.3 Ox Professional

Ox Professional (version 3) is an object-oriented programming system. At its core is a pow- erful matrix language, which is complemented by a comprehensive statistical library. Among the special features of Ox are its speed (several reviewers rated it much faster than other comparable systems), well-designed syntax and editor, and graphical facilities. Ox can read and write many data formats, including spreadsheets and GiveWin files; Ox can run many Gausstm; programs directly; if necessary, existing C or FORTRAN code can be added to Ox in the form of dynamic link libraries (DLLs); there is sufficient flexibility in the Ox system to allow it to be fully integrated in applications requiring an econometric or statistical en- gine; Ox is available on Windows, Linux, and several Unix platforms. There are many func- tions integral to Ox: ARMA, numerical optimisation and differentiation, probability (density, quantile, cumulative density and random generation of various probability functions), econo- metrics (e.g. VAR and cointegration), and Monte Carlo simulation. Additional packages are available and are described later in this brochure.

1.4 Ox Packages

Ox Packages extend the functionality of Ox in various ways. Once installed, they become an integrated part of Ox. Some packages just add a few useful functions, whereas others offer their functionality in an extensive class. A package is also a convenient way for communi-

(7)

1.5 PcGets 3 cating research. The following summary describes some of the currently available free Ox packages:

ARFIMA - estimation and forecasting of ARFIMA(p,d,q) and ARMA(p,q) models.

DPD - estimation of static and dynamic panel-data models.

EmmPack - estimation of univariate stochastic volatility models with the efficient method of moments.

Financial Numerical Recipes - advanced financial calculations.

G@RCH - estimation of ARCH model and many of its extensions (GARCH, IGARCH, FIGARCH, EGARCH, FIEGARCH, APARCH, FIAPARCH and GJR).

Lapack - solving linear equations, linear least squares problems, eigenvalue problems, and singular value problems.

Loess - smoothing of multivariate scattered data (LOESS), and decomposition of time series into trend + seasonal + remainder (STL).

MSVAR - estimation of Markov switching models.

Quantile regression - computation of quantile regression estimates.

SsfPack - analysis of univariate Gaussian and non-Gaussian time series which can be placed in the state-space form (SSF).

STR2 - estimation of smooth transition regression models.

SVPack - stochastic volatility: likelihood inference and comparison with ARCH mod- els.

1.5 PcGets

PcGets (version 1) is an automatic econometric model selection program. This package is designed for modelling economic data when the precise formulation of the equation under analysis is not known a priori. The current version is for models that are linear in variables.

PcGets is a revolutionary new approach to model building, based on recent advances in the understanding of model selection procedures. Experiments show that PcGets ‘outperforms’

even the most experienced econometrician. With PcGets all the drudgery has gone: you choose the variables, then PcGets selects sensible and statistically-valid model(s), allowing you to concentrate on the variable choice and interpretation of the model(s).

PcGets combines the user friendliness, powerful graphics and flexible data management of GiveWin with the latest methods for single-equation econometric model building provided by PcGive.

1.6 PcGive

PcGive (version 10) is an essential tool for modern econometric modelling. It provides the lat- est econometric techniques, from single equation methods to advanced cointegration, volatil- ity models (GARCH, EGARCH and many variations of these models), static and dynamic

(8)

4 Chapter 1 Introduction to the OxMetrics family

panel data models, and time-series models such as ARFIMA(p,d,q), and X-12-ARIMA for seasonal adjustment and ARIMA modelling. PcGive is easy to use and flexible, making it suitable both for teaching and research.

PcGive is distributed with 3 books. These books introduce the econometric methods of the program, emphasising empirical issues. The first two volumes contain an extensive econometric section, starting at a very elementary level and moving on to more advanced econometrics. In addition, there are many tutorial chapters, as well as detailed descriptions of the statistics that are computed. The volumes can be used as stand-alone textbooks, as well as providing a comprehensive reference for the PcGive system.

1.7 PcNaive

PcNaive (version 2) is an Ox Professional package for designing Monte Carlo experiments of dynamic econometric models. There is a set of interactive dialogs in which the data gen- eration process (DGP) and model are formulated, and the statistics of interest are selected.

PcNaive then generates and runs an Ox program. The output appears in GiveWin and can include:

theoretical analysis of the DGP,

live graphical output as the experiment progresses,

numerical output of final results.

PcNaive comes with a 200 page book, containing extensive tutorials introducing Monte Carlo analysis, and showing how the program can be used. A separate part discusses how PcNaive can be used in teaching econometrics, starting from the elementary through intermediate and finally advanced econometrics. The book concludes with a comprehensive introduction to the theory of Monte Carlo analysis, including asymptotic analysis and response surfaces. Many econometric examples are used throughout, and the book covers important material which is often missing from standard text books.

1.8 STAMP

STAMP (version 6) is a package designed to model and forecast time series, based on struc- tural time series models. These models use advanced techniques, such as Kalman filtering, but are set up so as to be easy to use – at the most basic level all that is required is some appreciation of the concepts of trend, seasonal and irregular. The hard work is done by the program, leaving the user free to concentrate on formulating models, then using them to make forecasts.

Structural time series modelling can be applied to a variety of problems in time series.

Macro-economic time series like gross national production, inflation and consumption can be handled effectively, but also financial time series, like interest rates and stock market volatil-

(9)

1.9 TSP/GiveWin 5 ity, can be modelled using STAMP. Further, STAMP is used for modelling and forecasting time series in medicine, biology, engineering, marketing and in many other areas.

1.9 TSP/GiveWin

TSP/GiveWin (version 4.5), by TSP International (founded in 1982 by Bronwyn H. Hall) is an econometric software package, with convenient input of commands and data, all the standard estimation methods (including non-linear), forecasting, and a flexible language for programming your own estimators. The philosophy behind TSP is that of a command-driven language tailored to econometric problems, whatever the platform used. For those working in a Windows environment, TSP can be installed as a module of GiveWin - TSP/GiveWin. This eases the use of the command-line environment by providing context sensitive help, syntax highlighting, and a dialog-driven command builder.

TSP offers a wide variety of facilities, such as: single-equation estimation (using a va- riety of techniques), non-linear 3SLS, GMM and FIML, time series methods (Box-Jenkins, Kalman-filter estimation, vector autoregressive models, etc.), financial econometrics (ARCH, GARCH, GARCH-M, including logarithmic versions), general maximum likelihood, quali- tative dependent variable estimation, and panel data estimation. Extensive libraries of TSP procedures are available free of charge.

A TSP companion book for the well-known econometrics text by Pindyck and Rubinfeld (McGraw-Hill & Co.), written by B. Hall and S. Schmukler is also available.

(10)

Chapter 2

Getting started with Ox

2.1 Ox versions

There are essentially two ‘versions’ of Ox:

(1) Ox Professional (with GiveWin) (2) Ox Console (with OxEdit)

The former provides a fully graphical environment, where GiveWin is used to receive both graphical and textual output from Ox Professional. Graphs can be edited interactively in GiveWin.

The latter is free for academic use and students. In this case the programming environ- ment is provided by OxEdit (a free editor, but others can be used). Programs are run from OxEdit, and output received in an OxEdit window. No direct graphical output is available.

Both operational modes provide syntax highlighting of Ox code, and extensive context sensitive help.

Ox versions for Linux and various Unix platforms are available.

Most of the material in the remainder can be followed with Ox Console.

2.2 Installation

(1) Download and install Ox Console fromwww.nuff.ox.ac.uk/users/doornik.

(2) Download and install OxEdit fromwww.oxedit.com.

(3) The first time you use OxEdit, execute the Add Predefined modules command View/Preferencesmenu, selectingOx. From then on you can run your Ox programs without leaving OxEdit, by selecting the Ox command from theModulesmenu.

A shortcut for this is the ‘running person’ button on the toolbar. The Run icon is on the toolbar entitled ‘Side bar’, which is not shown by default. You can switch this on from the View menu.

6

(11)

2.3 Testing the installation 7

2.3 Testing the installation

(1) Loadox/samples/myfirst.oxin OxEdit, as shown in Fig. 2.1.

(2) Run this file by clicking on the Run Default icon, or selecting Ox from the Modules menu, see Fig. 2.2.

(3) the output should appear in a separate window, as shown in Fig. 2.3.

(4) To test the online help, put the text cursor onunit, and press theF1key.

Figure 2.1 myfirst.oxprogram inside OxEdit.

Figure 2.2 Run Default icon.

2.4 Data sets

In this tutorial we shall use two data sets:

(1) airline.xls

International airline passengers: monthly totals (thousands of passengers) Jan-1969 to Dec-1960, from Box and Jenkins (1976).

(12)

8 Chapter 2 Getting started with Ox

Figure 2.3 Output frommyfirst.ox.

(2) exch debp.in7/exch debp.bn7

Deutschmark/British Pound exchange rate data from Bollerslev and Ghysels (1996).

The data are daily percentage nominal returns, from 3-Jan-1984 to 31-Dec-1991, con- taining1974observations, and constructed from US dollar rates published in Interna- tional Financial Statistics (by the International Monetary Fund).

These data are used to illustrate Ox programming, as well as various Ox packages. The airline data are in Excel format, while the exchange rate data are in GiveWin (also called PcGive) format. Both formats can be handled by Ox and GiveWin.

Using Ox Professional, the data sets can be loaded directly in GiveWin, and plotted. The result is in Fig.2.4.

2.5 An Ox program to load the airline data

An Ox program consists of one or more source code files. All source files have the.ox extension. Header files are used to communicate declarations from one source file to another.

Header files have the.hextension. Runningairline1.oxprogram in the lising below will print the data:

airline1.ox

#include <oxstd.h>

main() {

decl data; // declare a variable called data data = loadmat("airline.xls");

/* now print the data set */

print("airline data:", data);

}

(13)

2.5 An Ox program to load the airline data 9

1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 200

300 400 500

600 Airline

0 150 300 450 600 750 900 1050 1200 1350 1500 1650 1800 1950

−2 0 2

DLxrDEBP

Figure 2.4 Airline and exchange rate data.

Now we consider theairline1.oxprogram in more detail:

The first line includes theoxstd.hfile into the source code (literally: the contents of the file are inserted at that point). This file contains the function declarations of the standard library, so that the function calls can be checked for number of arguments. The file name is between< >, indicating that the header file came with the Ox program.

The functionmainis the starting point, and each program is only allowed one such function. Even thoughmainhas no arguments, it still requires().

Variables may be declared with thedeclstatement, and have no type until the pro- gram is actually run.

Ox has two types of comment:/*. . .*/for blocks of comment, and//for comment up to the end of a line.

loadmatis a standard library function, which can load various types of data files;

here it loadsairline.xls, which must be in the same folder as the Ox program.

The type ofdatahas become matrix, and until a reassignment is made (or it goes out of scope),datawill keep its type and value.

printis a library function, which can print any type of variable or constant to the standard output screen. It can take any number of arguments. Here it has two: a string constant and one variables (which is a matrix).

(14)

10 Chapter 2 Getting started with Ox

2.6 Manipulating the airline data

Once a matrix has been created, it can be manipulated as a whole (transposed, for exam- ple), by individual elements, or by a range of elements. The following program gives some examples:

airline2.ox

#include <oxstd.h>

main() {

decl data = loadmat("airline.xls");

println("rows: ", rows(data), " columns: ", columns(data));

println("first observation: ", data[0][0]);

println("first observation again: ", data[0]);

println("first year (transposed):", data[0:11]’);

println("first year (logs):", log(data[0:11])’);

}

Note that indexing starts at zero, so the top-left element ism1[0][0]: row 0, column 0. The first index is the row index: m1[1][2] is row 1, column 2. Ox has this convention in common with many other modern programming languages).

When a matrix is a vector (i.e. has one row or column), it is more convenient to just use a single index.

printlnis likeprint, but ensures that a new line is started afterwards.

As the last line shows, operations can be combined in a single statement.

The airline model has become synonymous with an ARIMA model that has a unit root and moving average at the annual and observation frequency:

(1−L)(1−L12) log(yt) = (1 +θ1L)(1 +θ12L12)εt, whereLis the lag-polynomial:Lyt=yt−1. To create the transformed variable

zt= (1−L)(1−L12) log(yt)12∆ log(yt),

use the Ox functionsloganddiff0. The program below createszt, and prints the first 32 sample autocorrelations.

Note that

calls todiff0can be nested;

the first 13 observations ofztare effectively lost;

displaying the sample ACF requires Ox Professional;

most drawing functions expect the data in rows;

LATEX-style text can be used in graphics, see the result in Fig. 2.5;

escape sequences are used inside strings:\\represents a single backslash. This is also relevant when using folder names in strings: either use one forward slash, or a double backward slash.

(15)

2.7 Using the database class 11

0 5 10 15 20 25

−0.5 0.0 0.5 1.0

ACF−12log(yt)

Figure 2.5 Sample ACF of airline data.

airline3.ox

#include <oxstd.h>

#include <oxdraw.h>

main() {

decl y = loadmat("airline.xls");

decl z = diff0(diff0(log(y), 1), 12);

z = z[13:];

println("ACF(z): ", acf(z, 24) );

DrawAcf(0, z’, "$\Delta _12\Delta\log(y_t)$", 24);

ShowDrawWindow();

}

2.7 Using the database class

Usually it is much more convenient if we can address variables in a data set by name, and, for time-series data especially, if we can use the sample period and frequency information.

This functionality is offered by the Database class. Using the database class takes us into object-oriented programming, although in this case we just wish to use the pre-programmed classes. Object-oriented programming is discussed in more detail later; at this stage it suffices to know:

An object of the class is created withnew.

A class combines data and functions. To call the functions in the object that was created, use the object name followed by a period and the function call.

The object is removed usingdelete. After that, the object cannot be used anymore.

(16)

12 Chapter 2 Getting started with Ox

airline4.ox

#include <oxstd.h>

#import <database>

main() {

decl db;

db = new Database();

db.Load("airline.xls");

print("Airline database:");

db.Info();

delete db;

}

Note that

The database code must be imported, so that it is available for use.

db is an object of typeDatabase, into which the airline data is loaded.

TheInfomember function prints information on the database. Consult the online help for documentation on the other function members.

The output is:

Airline database:

---- Database information ----

Sample: 1949 (1) - 1960 (12) (144 observations) Frequency: 12

Variables: 1

Variable #obs #miss min mean max std.dev

Airline 144 0 104 280.3 622 119.55

Exercises

I[2.1] Adjust theairline1.oxexample to load the exchange rate data set.

I[2.2] Use therows/columnsandsizer/sizecfunctions to print the dimensions of the exchange rate data set. Use the online help to determine the difference between these functions.

I[2.3] Adjust the call toDrawAcfinairline3.oxto include standard error bars.

I[2.4] Create a version ofairline4.oxthat loads the exchange rate data.

(17)

Chapter 3 Using Functions

The function is a fundamental building block when writing Ox programs. Functions allow for splitting complex tasks up in manageable bits. The best ones are those which only interact with the outside via the arguments (the inputs) and the return value (the outputs, if any). Then, when there are no external variables used inside the function, the function can be treated as a black box: the only thing which matters is the documentation of the function.

Up to this point, only one function has been written, themainfunction. Execution of an Ox program starts atmain, from which other functions are called; there is no action outside functions. Ox comes with a vast library of functions for your convenience. These are all documented in the help and the Ox book. Whether a function is written in C, and added to the Ox system (as for the standard library), or written in Ox itself (such as the maximization functions and the Database class), does not make any difference to the user of the function.

3.1 Simple functions

The most simple Ox function has no arguments, and returns no value. The syntax is:

function name() {

statements }

For example:

#include <oxstd.h>

sometext() {

print("Some text\n");

} main() {

sometext();

}

13

(18)

14 Chapter 3 Using Functions

We’ve created thesometextfunction, and call it from themainfunction. When the pro- gram is run, it just printsSome text. Note that, to call the function, the empty parentheses are required.

3.2 Function arguments

A function can take arguments. In the header of the function code, the arguments are listed, separated by comma’s. This example takes one argument:

oxtut2d.ox

#include <oxstd.h>

dimensions(const mX) {

println("the argument has ", rows(mX), " rows");

} main() {

dimensions( zeros(40, 5) );

}

Theconstwhich precedes each argument indicates the function is only accessing the value, not changing it. Although any change made tomYormXis only local to the function (once the function returns, both will have their old values back), it is very useful to useconst wherever possible: the compiler can then generate much faster code.

3.3 Returning a value

The returnstatement returns a value from the function, and also exits the function. So, when the program flow reaches areturnstatement, control returns to the caller, without executing the remainder of the function. The syntax of thereturnstatement is:

returnreturn value;

Or, to exit from a function which does not have a return value:

return;

For example:

MyOls1(const mY, const mX) {

return (mX’mX)ˆ-1 * (mX’mY);

}

Note that you should not implement OLS estimation this way. It is much better to use the library function olscas shown in the next example, which estimates and prints the coefficients of the linear regression model. The dependent variable is in theT ×1 vector

(19)

3.4 More database facilities 15 mY, and the regressors in theT×kmatrixmX. The&bpart is explained below. Any local variable (here:b) must be declared;bonly exists while the function is active. Withreturn the result is returned to the caller, and the function exited

airline5.ox

#include <oxstd.h>

#import <database>

MyOls(const mY, const mX) {

decl b;

olsc(mY, mX, &b);

print("in MyOls(): b=", b);

return b;

} main() {

decl db, b, z;

db = new Database();

db.Load("airline.xls");

// mY argument, mX argument, both just random z = diff0(diff0(log(db.GetVar("Airline")), 1), 12);

z = z[13:];

b = MyOls( z, ones(z) );

// b now holds the result print("in main(): b=", b);

}

Of course, this regression simply reports the mean ofzt: in MyOls(): b=

0.00029088 in main(): b=

0.00029088

3.4 More database facilities

The database class has facilites to create deterministic variables (Constant, Trend, and Sea- sonals), which we shall use next.

airline6.ox

#include <oxstd.h>

#import <database>

(20)

16 Chapter 3 Using Functions

airline6 (Continued) MyOls(const mY, const mX)

{

decl b;

olsc(mY, mX, &b);

print("in MyOls(): b=", b);

return b;

} main() {

decl db, b, z;

db = new Database();

db.Load("airline.xls");

// mY argument, mX argument, both just random z = diff0(diff0(log(db.GetVar("Airline")), 1), 12);

z[ : 12] = .NaN;

db.Append(z, "D12DLairline");

db.Deterministic(0);

db.Info();

db.Select(0, "D12DLairline", 0, 0 );

db.Select(1, "Constant", 0, 0, "Season", 0, 10 );

db.SetSelSample(-1, 1, -1, 1);

b = MyOls( db.GetGroup(0), db.GetGroup(1) );

}

The first thirteen observations ofzare set to the missing value, before the transformed variable is added to the database.

Then deterministic variables are created in the database.

The Database class has facilities to create a database selection. Here we select D12DLairlinefrom lag zero to zero into group zero, and the Constant and 11 sea- sonals (why not 12?) into group 1. Then, the selection sample is set to the maximum available, and group 0 used asY, and group 1 asXfor the regression.

The database information shows that all the seasonals have been created, and prints the regression results:

---- Database information ----

Sample: 1949 (1) - 1960 (12) (144 observations) Frequency: 12

Variables: 16

Variable #obs #miss min mean max std.dev

Airline 144 0 104 280.3 622 119.55

D12DLairline 131 13 -0.14134 0.00029088 0.14072 0.045673

Constant 144 0 1 1 1 0

Trend 144 0 1 72.5 144 41.568

Season 144 0 0 0.083333 1 0.27639

Season_1 144 0 0 0.083333 1 0.27639

Season_2 144 0 0 0.083333 1 0.27639

Season_3 144 0 0 0.083333 1 0.27639

Season_4 144 0 0 0.083333 1 0.27639

(21)

3.5 Function declaration 17

Season_5 144 0 0 0.083333 1 0.27639

Season_6 144 0 0 0.083333 1 0.27639

Season_7 144 0 0 0.083333 1 0.27639

Season_8 144 0 0 0.083333 1 0.27639

Season_9 144 0 0 0.083333 1 0.27639

Season_10 144 0 0 0.083333 1 0.27639

Season_11 144 0 0 0.083333 1 0.27639

b=

-0.0023691 -0.0059801 0.0056826 -0.00058715 0.00018593 0.0078643 -0.0082277 -0.0015358 0.013143 0.010333 0.0038058 0.0077087 T=131 k=12 sigma=

0.0022535

3.5 Function declaration

A function can only be called when the compiler knows about it. In the program listed above, theMyOls()function can be used insidemain, because the source code is already known at that stage. If MyOls()were to be moved belowmain it cannot be used any more: the compiler hasn’t yet encounteredMyOls(). However, there is a way to inform about the existence ofMyOls(), without yet giving the source code, namely by declaring the function. This amounts to copying the header only, terminated with a semicolon. To illustrate the principle:

#include <oxstd.h>

MyOls(const mY, const mX);// forward declaration of MyOls, // so that it can be used in main main()

{ // now MyOls may be used here }

MyOls(const mY, const mX) { // code of MyOls }

The header files (e.g. oxstd.h) mainly list all the function declarations together, whereas the source code resides elsewhere.

An option for small bits of code is to write the function to an.oxfile, and just include the whole file into the source file which needs it:

(22)

18 Chapter 3 Using Functions

#include <oxstd.h>

#include "myols.ox" // insert code from myols.ox file main()

{

// now MyOls may be used here }

Perhaps most convenient is to create a header fileMyOls.hwhich contains the function declaration:

MyOls.h MyOls(const mY, const mX);

Then use#importto import the code fromMyOls.ox:

#include <oxstd.h>

#import "myols" // insert MyOls.h; link MyOls.ox main()

{

// now MyOls may be used here }

3.6 Returning values in an argument

Often, a function needs to return more than one value. It was pointed out before that a function cannot make a permanent change to an argument. However, this can be changed using the ampersand (&). The following program illustrates the principle:

oxtut2g.ox

#include <oxstd.h>

test1(x) // no const, because x will be changed {

x = 1;

println("in test1: x=", x);

}

test2(const ax) {

// Note: indexing starts at 0 in Ox ax[0] = 2;

println("in test2: x=", ax[0]);

}

(23)

3.6 Returning values in an argument 19 oxtut2g.ox (Continued) main()

{

decl x = 10;

println("x = ", x);

test1(x); // pass x

println("x = ", x);

test2(&x); // pass address of x println("x = ", x);

}

The program prints:

x = 10

in test1: x=1 x = 10

in test2: x=2 x = 2

This is happening:

When callingtest2, it receives in&xthe address of the variablex, not its contents.

In other words, we are now working with a reference tox, rather than directly withx.

Insidetest2, the ax argument holds this address. To access the contents at that address, we use subscript 0:ax[0]is the contents of the address, which we can now change.

ax[0] = 2does precisely that: it changes x itself, because x resides at that address.

Consider the variable as a mailbox: a location at which a value can be stored. In the first case (test1), we just faxg the content of the box: the function can read or change the content, but we (the function caller) still have the original version. In the second case (test2), we pass the key to the mailbox (the ’address’): this allows the function to put something new in the box, which will then permanently replace the content once the function returns. Whether the variable is passed by value as intest1, or by reference as intest2 is determined by the author of the function. The function user must follow the conventions adopted by the function author.

Finally, Ox makes no distinction between functions which do return a value, and those that do not. If you wish, you may ignore the return value of a function altogether. (But, of course, if a function has no return value, it should not be used in an expression.) For example:

decl b0 = MyOls(my, mx)[0];

MyOls(my, mx);

print(MyOls(my, mx));

The first line directly indexes the returned vector.

(24)

20 Chapter 3 Using Functions

3.7 Multiple returns

Multiple values can be returned as an array:

func() {

return a, b, c;

}

which can then be assigned as follows:

[x, y, z] = func();

3.8 Using functions as arguments

Functions can be passed as arguments, by specifying the name without parentheses. These can then be used as any other function. An example is function maximization, where we pass the function to be maximized as an Ox function to the maximizer. Here we useMaxBFGS, which expects a specific syntax for the Ox function.

First the mathematics. We intend to estimate the airline model by non-linear least squares (also called conditional least squares, because we condition on the initial observations).

Rewrite

zt= (1 +θ1L)(1 +θ12L12)εt. as

zt=εt+θ1εt−1+θ12εt−12+θ1θ12εt−13.

We can use the arma0function to apply the ARMA filter for given values ofθ1 andθ12, and then minimize the residual sum of squares. This is somewhat inefficient, becausearma0 cannot handle a seasonal ARMA filter, so there will be quite a few zero coefficients (θ2 =

· · ·θ11= 0). The residuals are then a function ofθ1andθ12: ε1 = z1

ε2 = z2−θ1ε1

· · ·

εT = zT −θ1εT−1−θ12εT−12−θ1θ12εT−13

and we aim to solve the concentrated conditional log-likelihood:

maxθ1121 2log 1

T XT t=1

ε2t

! .

The library function MaxBFGS implements the BFGS (Broyden-Fletcher-Goldfarb- Shanno) method (other available unconstrained maximization methods are Newton’s method and the Nelder-Mead simplex method. Further information on all these functions is in the Ox manual and online help. Details of the procedures are beyond our current objectives, but there is a vast literature on non-linear optimization techniques to consult (see, among many others,

(25)

3.8 Using functions as arguments 21 Fletcher, 1987, Gill, Murray and Wright, 1981, Cramer, 1986 and Press, Flannery, Teukolsky and Vetterling, 1988). Note that many texts on optimization focus on minimization, rather than maximization, but of course that is just a matter of reversing the sign.

In order to use a function for maximization, it must have four arguments:

func(const vP, const adFunc, const avScore, const amHess);

obeying the following rules:

vPis a1matrix of parameter values at which the function is to be evaluated.

adFuncmust be the address of a variable on input. On output, the function value at the supplied parameters should be stored at the address.

avScoreholds either0on input, or the address of the score variable. If it was not 0on input, the first derivatives of the function (the scores, a1vector) should be stored at the address.

We ignore theamHessargument.

funcshould return 1 if it was successful, and 0 if it failed to evaluate the function at the supplied parameter values.

In the resulting program,airlineis the function to maximize:

airline7.ox

#include <oxstd.h>

#include <arma.h>

#import <database>

#import <maximize>

static decl s_mY;

airline(const vP, const adFunc, const avScore, const amHessian) {

decl vq = zeros(1, 13);

vq[0] = vP[0];

vq[11] = vP[1];

vq[12] = vq[0] * vq[11];

decl vres = arma0(s_mY, vq, 0, 13);

adFunc[0] = -0.5 * log( (vres’vres) / rows(s_mY) );

return 1;

} main() {

decl db, b, z;

db = new Database();

db.Load("airline.xls");

(26)

22 Chapter 3 Using Functions

airline7 (Continued) // mY argument, mX argument, both just random

z = diff0(diff0(log(db.GetVar("Airline")), 1), 12);

s_mY = z[13:];

decl vp = zeros(2,1), f;

MaxControl(-1, 1);

MaxBFGS(airline, &vp, &f, 0, TRUE);

decl hess, se;

Num2Derivative(airline, vp, &hess);

se = sqrt(diagonal(invertsym(-hess)) / rows(s_mY))’;

println("estimated parameters and standard errors:",

"%r", "theta1", "theta12", vp ˜ se);

}

Following successful estimation (which is not checked here!), we use the the inverse of (minus the) numerical second derivatives as an estimate of the variance-covariance matrix of the parameters.

Running this program gives (omitting the intermediate iteration output):

Starting values parameters

0.00000 0.00000 gradients

-0.34110 -0.38664 Initial function =

3.08622847503

Position after 5 BFGS iterations Status: Strong convergence parameters

-0.37717 -0.57236 gradients

6.6462e-007 -2.2893e-005 function value =

3.28967564324

estimated parameters and standard errors:

theta1 -0.37717 0.088292

theta12 -0.57236 0.070383

Exercises

I[3.1] Modify thedimensions function inoxtut2d.ox to give it two arguments, printing the number of rows in both arguments.

I[3.2] Verify the results of the regressions inairline5.oxandairline6.ox, for example with PcGive.

I[3.3] ModifyMyOlsto print out the coefficient standard errors.

I[3.4] Implement a similar regression for the exchange rate data.

(27)

Chapter 4 Ox Operators

This is a shortened version of Doornik and Ooms (2001, Chapter 3).

4.1 Introduction

A language like Ox needs at least three kinds of operators to work with matrices:

(1) index operators, to access elements in a matrix;

(2) matrix operators, for standard matrix operations such as matrix multiplication;

(3) dot operators, for element by element operations.

There are quite a few additional operators, for example to work with logical expressions – these are discussed later in this chapter.

4.2 Index operators

Ox has a flexible indexing syntax to extract single elements or specific rows or columns from a matrix. But remember:

Indexing in Ox starts at zero, not at one!

Initially you might forget this and make a few mistakes, but before too long it will become second nature. Ox has adopted this convention for compatibility with most modern languages, and because it leads to faster programs. There is an option to start at index one, which is explained in the Ox manual (and not really recommended). The available indexing options are:

Single element indexing

A matrix usually has two indices:[i][j]indexes element(i, j)of a matrix, where [0][0]is the first (top left) element.

Range indexing

Eitheriorjmay be replaced by a range, such asi1:i2. If the lower value of a range is missing, zero is assumed; if the upper value is missing, the upper bound is assumed.

23

(28)

24 Chapter 4 Ox Operators

Empty index

The empty index[]selects all rows (when it is the first index) or all columns (when it is the second). When there is only one index[]the result is a column vector, filled by taking the elements from the indexand row by row.

Indexing a vector (i.e. a matrix with one row or one column)

When a matrix is used with one index, it is treated as a vector. In that case it does not matter whether the vector is a row or a column vector.

Using a matrix as an index

In this case the matrix specifies which rows (if it is the first index) or columns (for the second index) to select. The elements in the indexing matrix must be integers (if not, they are truncated to integers by removing the fractional part).

Here are some examples:

x=

0 1 2 3 4 5

, y= 0 1 2 , z=

 0 3 6

.

x[0][0] = 0, x[ ][1 : ] =

1 2 4 5

, x[1][y] = 3 4 5 , y[ : 1] =y[0][ : 1] = 0 1

, z[ : 1] =z[ : 1][0] = 0

3

.

4.3 Matrix operators

All operators+ - * / work as expected when both operands are an integer or a double:

when both operands are an integer, the result is an integer, otherwise it will be a double. The exception is division of two integers: this will produce a double, so1/2equals 0.5 (C and C++programmers take note!).

When matrices are involved, things get more interesting. Obviously, when two matrices have the same size we can add them element by element (+), or subtract them element by element (-). Although not a standard matrix algebraic operation, adding a column vector to a row vector works is allowed in Ox (and at times very useful). It works like a table:

x0 x1 +

y0

y1

y2

=

x0+y0 x1+y0

x0+y1 x1+y1

x0+y2 x1+y2

.

For matrix multiplication use*, then elementi, jof the result is the inner product of row i(left operand) and columnj(right operand).

I[4.1] If you’re not so familiar with matrices, try the following on paper and then in Ox:

1 2 3 4

×

2 1 1 2

.

(29)

4.4 Dot operators 25 Division (/), when the right operand is a matrix, corresponds to post multiplication with the inverse. We’ve already used matrix transpose (’) and horizontal and vertical concatena- tion. We also saw one useful feature when creating the constant term for regression: when concatenating an integer (or double) and a matrix, the scalar is automatically replicated to get the same number of rows (˜) or columns (|). When concatenating two non-matching matrices, the shortest one is padded with zeros at the end. (So there is a difference between 1 ˜ <1;1> and<1> ˜ <1;1> ; a warning is printed for the latter.)

A square matrix may be raised to an integer power, usingˆ, for exampleAˆ2equalsA*A.

To summarize:

operator operation

’ transpose,X’yis short forX’*y ˆ (matrix) power

* (matrix) multiplication / (matrix) division + addition

- subtraction

˜ horizontal concatenation

| vertical concatenation

Some operations are illegal, resulting in an error message. Here is an example:

Runtime error: ’matrix[4][1] * matrix[3][4]’ bad operand Runtime error occurred in main(16), call trace:

C:\Program Files\Ox\tutorial\oxtut3a.ox (16): main

The first says that we cannot multiply a4×1matrix into a3×4matrix. The error occurred in themainfunction, at line 16. In OxEdit or GiveWin you can double click on the line with the error to jump directly to the problematic code.

4.4 Dot operators

Dot operators are element-by-element operators. For adding and subtracting matrices there is only the dot version, already used in the previous section (written as+and-).

Element-by-element multiplication is denoted by .* and./ is used for element-by- element division. As with addition and subtraction, dot conformity implies that either operand may be a row (or column) vector. This is then swept through the rows (columns) of the other operand. For example:

x0 x1 .*

y0 y1

y2 y3

y4 y5

=

x0y0 x1y1

x0y2 x1y3

x0y4 x1y5

. To summarize:

(30)

26 Chapter 4 Ox Operators operator operation

.ˆ element-by-element power .* element-by-element multiplication ./ element-by-element division

+ addition - subtraction

4.5 Relational and equality operators

Relational operators compare both operands, and exist in matrix version and in element by element (or ‘dot’) version. The first version always returns an integer, even when both argu- ments are matrices. The return value 0 stands for FALSE, and 1 for TRUE. When comparing a matrix to a scalar, the result is only 1 (TRUE) if it holds for each element of the matrix.

operator operation

< less than

> greater than

<= less than or equal to

=> equal or greater than

== is equal

!= is not equal

The second form of relational operator is the dotted version: this does an element by element comparison, and returns a matrix of 0’s and 1’s. The dotted versions are:

operator operation

.< element-by-element less than .> element-by-element greater than .<= element-by-element less than or equal to .=> element-by-element equal or greater than .== element-by-element is equal

.!= element-by-element is not equal

Often code is more readable when using the predefined constantTRUEandFALSE, in- stead of the numbers 1 and 0. These are defined in oxstd.h. Relational operators are especially important in conditional epressions and loops, and these are discussed in the next chapter.

4.6 Logical operators

These are closely related to the relational operators, and also have non-dotted and dotted versions. The first evaluate to either zero or one:

(31)

4.6 Logical operators 27 operator operation

&& logical-and

|| logical-or

If an expression involves several logical operators after each other, evaluation will stop as soon as the final result is known. For example in (1 || checkval(x))the function checkvalis never called, because the result will be true regardless of its outcome. This is called a boolean shortcut.

The dotted versions perform the logical expression for each element when matrices are involved (therefore they cannot have boolean shortcuts):

operator operation

.&& element-by-element logical-and .|| element-by-element logical-or

As a first example, we print a logical table. Print format options are used to label rows and columns.

oxtut3d

#include <oxstd.h>

main() {

decl a1 = <0,1>, a2 = <0,1>;

print("Truth table", "%7g ",

"%r", {"m=0:","m=1:"},

"%c", {" m || 0"," m || 1", " m && 0"," m && 1"}, (a1’ .|| a2) ˜ (a1’ .&& a2) );

}

Which prints the table:

Truth table

m || 0 m || 1 m && 0 m && 1

m=0: 0 1 0 0

m=1: 1 1 0 1

The next program uses some matrix comparisons, printing:

v ˜ (v .> 1 .&& v .< 3) ˜ (v .== <1:3>’)

1.0000 0.00000 1.0000

2.0000 1.0000 1.0000

3.0000 0.00000 1.0000

No dots: (v > 1 && v < 3) = 0, (v == <1:3>’) = 1

(32)

28 Chapter 4 Ox Operators

oxtut3e

#include <oxstd.h>

main() {

decl v = <1;2;3>;

print(" v ˜ (v .> 1 .&& v .< 3) ˜ (v .== <1:3>’)", v ˜ (v .> 1 .&& v .< 3) ˜ (v .== <1:3>’) );

println("No dots: ",

"(v > 1 && v < 3) = ", (v > 1 && v < 3),

", (v == <1:3>’) = ", v == <1:3>’);

}

Some procedures are available for selecting or dropping rows/columns based on a log- ical decision. These are selectifr, selectifc, deleteifr and deleteifc;

vecindexmay be used to translate the 0-1’s to indices. A very useful, but slightly more complex operator is the dot-conditional operator (see§4.8).

Here are some examples using these functions:

expression outcome

u 1 0 1 0 2

u .> 0 1 0 1 0 1

vecindex(u)’ 0 2 4

vecindex(u .> 1)’ 4 selectifc(u, u .> 0) 1 1 2 selectifc(u, u .> 1) 2

4.7 Assignment operators

It may surprise you, but assignment is an operator like any other, it just has very low prece- dence (only one operator is below it: the comma operator). As a result we may write

decl x1, x2, x3, x4;

x1 = 0; x2 = 0; x3 = 0; x4 = 0;

// or more concisely:

x1 = x2 = x3 = x4 = 0;

There are also compact assignment-and-other-operation-in-one operators:

+= -= *= /= ˜= |= .*= ./=.

4.8 Conditional operators

Both the conditional, and dot-conditional operators are a bit more advanced, because they have three components. The dot-conditional can be especially useful, because it is like a filter: a one in the filter will let the first value through, a zero the second. Consider for example:

(33)

4.9 And more operators 29

decl x = rann(2,2);

x = x .< 0 .? 0 .: x;

Initially, x is a matrix with standard normal random numbers. The next line checks for negative elements (x .< 0creates a 0-1 matrix, with 1 in the positions of negative numbers).

For all positions where the filter is not 0, the expression after the.? is used. For the zeros, the else expression (after.:) is applied.

I[4.2] Below is an example using theselectifcandvecindexfunctions. Adjust it to use the dot-conditional operator (use the help if necessary, see under conditional operator), to set all negative values ofuto zero. Note that dot operators tend to be much faster than using loops.

oxtut3f

#include <oxstd.h>

main() {

decl u = rann(6,1), v, w;

v = selectifr(u, u .< 0)’;

print(u’, v’);

w = u;

w[vecindex(u .< 0)][] = 0;

print(u ˜ w, v’ ˜ vecindex(u .< 0));

}

4.9 And more operators

We have not discussed all operators, see the Ox book for the full list. Some will be needed in the remaining chapters:

decl x1, x2;

x1 = x2 = 0;

print(x1, " ", ++x1, "\n"); // increment x1 by 1 print(x1, " ", --x1, "\n"); // decrement x1 by 1 x1 = <0,1,2>;

println(x1, " ", !x1, " ", !!x1); // ! is negation:

// 0 becomes 1, non-zero becomes 0

4.10 Operator precedence

Because operator precedence is so important, we replicate the table from the Ox book here.

Table 4.1 gives a summary if the operators available in Ox, together with their precedence.

The precedence is in decreasing order. Operators on the same line have the same precedence, in which case the associativity gives the order of the operators.

(34)

30 Chapter 4 Ox Operators Table 4.1 Ox operator precedence.

Category operators associativity

primary () :: left to right

postfix -> . () [] ++ -- ’ left to right

power ˆ .ˆ left to right

unary ++ -- + - ! & new delete right to left

multiplicative ** * .* / ./ left to right

additive + - left to right

horizontal concatenation ˜ left to right

vertical concatenation | left to right

relational < > <= >= .< .> .<= .>= left to right

equality == != .== .!= left to right

logical dot-and .&& left to right

logical-and && left to right

logical dot-or .|| left to right

logical-or || left to right

conditional ? : .? .: right to left

assignment = *= /= += -= ˜= |= right to left

comma , left to right

At first, it will be useful to keep Table 4.1 close at hand: we often use the precedence ordering in our statements to avoid using too many parentheses. But when in doubt, or when needing to override the default, you can always add parenthesis. For example, we can write:

mx = 1 ˜ x1 ˜ x1 .ˆ 2; // regressors

Using the precedence table we know that dot-power comes before concatenation. Also, con- catenation is evaluated left to right. So the expression is evaluated as:

mx = ((1 ˜ x1) ˜ (x1 .ˆ 2));

(35)

Chapter 5

Using Ox Packages

Although the objective of using the airline data is to explain how Ox works, there are several Ox packages which provide the required statistical methods.

5.1 X12arima for GiveWin

X12arima for GiveWin is not an Ox package, but instead part of PcGive Professional 10.

Despite that, we use it first to check the coefficient estimates ofairline7.ox, because it can easily handle seasonal ARIMA models.

The final X12arima specification looks like:

which involved the steps:

(1) Select series: Airline (2) Transform: log

31

(36)

32 Chapter 5 Using Ox Packages (3) FormulateARIMAerros as shown below:

(4) Sample: set 36 forecasts.

The resulting forecast graph is in Fig. 5.1, and the estimation results are (note that the sign of the MA coefficient is the opposite of our previous estimates; this is just a notational difference):

MODEL DEFINITION for Airline Transformation: Log(y)

ARIMA Model: (0 1 1)(0 1 1) regARIMA Model Span: 1949.Jan to 1960.Dec MODEL ESTIMATION/EVALUATION

Estimation converged in 6 ARMA iterations, 19 function evaluations.

ARIMA Model: (0 1 1)(0 1 1) Nonseasonal differences: 1 Seasonal differences: 1

Standard

Parameter Estimate Errors

--- Nonseasonal MA

Lag 1 0.3772 0.08136

Seasonal MA

(37)

5.2 Arfima package 33

Lag 12 0.5724 0.07742

Variance 0.13887E-02

--- Likelihood Statistics

---

Effective number of observations (nefobs) 131

Number of parameters estimated (np) 3

Log likelihood 245.0666

Transformation Adjustment -735.2943

Adjusted Log likelihood (L) -490.2277

1958 1959 1960 1961 1962 1963 1964

500 750 1000

Airline Forecasts

Figure 5.1 Forecasts from airline model, created with X12arima for GiveWin.

5.2 Arfima package

5.2.1 Introduction

A freely downloadable package that we use next is theArfimapackage for Ox by Doornik and Ooms (1999). An application and a more extensive discussion can be found in Ooms and Doornik (1999).

The fractionally-integrated autoregressive-moving average model, denoted ARFIMA(p, d, q) can be used for the statistical analysis of a univariate time series yt

with long memory. The more familiar ARMA (or ‘Box–Jenkins’) models (whend = 0) or ARIMA (when dis a positive integer) are special cases. The ARFIMA(p, d, q) model allows one to model the long-run behaviour of a time series in a flexible way. Empirical modelling involves identification, estimation and testing. In the identification stage of ARIMA-modelling one determines the integer part of the order of differencing,d, and the orders of the autoregressive and the moving-average parts of the model, p, and q. In the ARFIMA-model one can estimate d and compute a confidence interval. The ARFIMA model allows for likelihood ratio and Wald tests for the null of short-memory stationarity (d= 0), as well as for the null of unit-root non-stationarity (d= 1) against long memory and

(38)

34 Chapter 5 Using Ox Packages

intermediate memory alternatives. These tests are easy to apply since they have conventional chi-squared limit distributions.

From the early nineteen sixties onwards, when Mandelbrot suggested long-memory mod- els for economic time series, there has been a steady growth in the literature on the sub- ject. Robinson (1994) and Baillie (1996) provided useful surveys of the developments in the econometric modelling of long memory; Beran’s monograph, Beran (1994), discusses most of the central issues, including forecasting.

We write the ARFIMA(p, d, q) model as:

Φ (L) (1−L)d(yt−µt) = Θ (L)εt, t= 1, . . . , T. (5.1) whereΦ (L) = (1−φ1L−. . .−φpLp)is the autoregressive polynomial and Θ (L) = (1 +θ1L+. . .+θqLq)is the moving average polynomial in the lag operatorL;pandqare integers,dis real. For example, the ARFIMA(1, d,1) model is:

(1−L)dzt=φ1(1−L)dzt−1+εt+θ1εt−1, where

zt=yt−µt.

The notation in textbooks often differs in terms of the sign of the parameters: we follow the regression-model notation.

(1−L)d = ∆d is the fractional difference operator defined by the following binomial expansion:

(1−L)d=X

j=0

δjLj=X

j=0

d j

(−L)j.

We assumeεtNID[0, σε2], and writeµtfor the mean ofyt. The ARMA-part of the model is assumed invertible and stationary: all roots ofΘ(z) = 0andΦ(z) = 0are outside the unit circle. In addition,Θ(z) = 0andΦ(z) = 0do not have common roots. We say that zt = yt−µt is I(d), integrated of orderd. The zero mean ARFIMA(p, d, q) process zt

is covariance stationary ifd < 0.5, see Hosking (1981), with autocovariance function that decays hyperbolically. The process is long memory in the case0< d <0.5. For0.5< d <

0the process is called intermediate memory or ‘overdifferenced’. We assumed >−1, which makes the processzt invertible. The Arfima package provides three estimation methods, Exact Maximum Likelihood (EML), Modified Profile Likelihood (MPL) and nonlinear least squares (NLS). By definition, EML and MPL impose 1 < d < 0.5. MPL is preferred over EML if the model includes regressor variables and the sample is not very large. NLS allows ford >−0.5and can be used to estimate models for non-stationary processes directly, without a priori differencing. NLS estimation is usually fast.

5.2.2 Changing the example program for the airline data

Many aspects of the Arfimaexample programfracest1.oxshould already be familiar from airline6.ox. The reason is that theArfima package is a class that derives from theModelbaseclass, which in turn derives from theDatabaseclass. Arfimatherefore inherits all the functionality of these base classes:

(39)

5.2 Arfima package 35 packages/arfima/fracest1.ox

#include <oxstd.h>

#include <oxfloat.h> // required for M_NAN

#import <packages/arfima/arfima>

main() {

decl arfima, dly;

// create an object of class Arfima arfima = new Arfima();

// load the data file

arfima.LoadIn7("rpi_uk.in7");

// translate RPI into inflation (delta log RPI) // setting first value to missing value

dly = diff0(log(arfima.GetVar("RPI_UK")), 1, M_NAN);

// store in database

arfima.Append(dly, "Inflat", 0);

arfima.Info();

// formulate arfima model, select "Y" as Y_VAR // from lag 0 to lag 0 (i.e. current only) arfima.Select(Y_VAR, "Inflat", 0, 0 );

// specify an ARMA(0,d,0) model, estimate by exact ML arfima.ARMA(0,0);

arfima.SetMethod(M_MAXLIK);

arfima.UseSampleMean();

// select the maximum sample period arfima.SetSelSample(-1, 1, -1, 1);

// print compact iteration output every iteration MaxControl(-1,1,1);

// estimate, automatically prints the results arfima.Estimate();

// done with arfima: delete the object delete arfima;

}

To adapt the program for our situation, simply involves replacing some lines with the code fromairline6.ox. The main features are:

We do not wish to estimated, and hence fix it at zero withFixD(0);

TheArfimapackage does not allow for seasonal ARMA specification, so instead we estimate the unrestricted version:

zt=εt+θ1εt−1+θ12εt−12+θ13εt−13. The coefficientsθ2. . . θ11are set to zero withFixMA(<2:11>).

Finally, to mimic earlier results, estimation is by non-linear least squares.

(40)

36 Chapter 5 Using Ox Packages

airline8.ox

#include <oxstd.h>

#import <packages/arfima/arfima>

main() {

decl arfima, z;

arfima = new Arfima();

arfima.Load("airline.xls");

z = diff0(log(arfima.GetVar("Airline")), 1, .NaN);

z = diff0(z, 12, .NaN);

arfima.Append(z, "D12DLairline", 0);

// formulate arfima model, select "Y" as Y_VAR // from lag 0 to lag 0 (i.e. current only) arfima.Select(Y_VAR, "D12DLairline", 0, 0 );

// specify an ARMA(0,0,13) model, estimate by NLS arfima.ARMA(0,13);

arfima.SetMethod(M_NLS);

arfima.FixMA(<2:11>);

arfima.FixD(0);

// select the maximum sample period arfima.SetSelSample(-1, 1, -1, 1);

// print compact iteration output every iteration MaxControl(-1,1,1);

arfima.Estimate();

// done with arfima: delete the object delete arfima;

}

The outcome resembles the earlier results:

-- Non-linear least squares estimation of ARFIMA(0,0,13) model -- The estimation sample is: 1950 (2) - 1960 (12)

The dependent variable is: D12DLairline

Coefficient Std.Error t-value t-prob

MA-1 -0.380737 0.08555 -4.45 0.000

MA-12 -0.590740 0.07260 -8.14 0.000

MA-13 0.279090 0.1005 2.78 0.006

log-likelihood 245.333157

no. of observations 131 no. of parameters 4

AIC.T -482.666314 AIC -3.68447568

mean(D12DLairline) 0.00029088 var(D12DLairline 0.00208602

sigma 0.0371902 sigmaˆ2 0.00138311

BFGS using numerical derivatives (eps1=0.0001; eps2=0.005):

Strong convergence Used starting values:

-0.37743 -0.27572 0.083147

(41)

5.2 Arfima package 37 5.2.3 Interactive use with OxPack

Referências

Documentos relacionados

É importante destacar que as práticas de Gestão do Conhecimento (GC) precisam ser vistas pelos gestores como mecanismos para auxiliá-los a alcançar suas metas

Neste trabalho o objetivo central foi a ampliação e adequação do procedimento e programa computacional baseado no programa comercial MSC.PATRAN, para a geração automática de modelos

Therefore, both the additive variance and the deviations of dominance contribute to the estimated gains via selection indexes and for the gains expressed by the progenies

OsEREBP1 and OsEREBP2 function in abiotic stress responses were further analyzed in transgenic Arabidopsis plants over- expressing the rice TFs.. OsEREBP1-OX seeds

No caso e x p líc ito da Biblioteca Central da UFPb, ela já vem seguindo diretrizes para a seleção de periódicos desde 1978,, diretrizes essas que valem para os 7

COMPARAÇÃO ENTRE OS MÉTODOS DE REGULAÇÃO Nas tabelas 26 e 27 são apresentadas, respectivamente, a produção anual m3 e a área de corte anual ha, assim como o retorno líquido e

É um período de grandes mudanças na Ciência e tem as principais características na obra de Galileu, inspirado pelas idéias de Francis Bacon (falecido em 1626) e Descartes

In the opening, it mentions the 86 thousand new titles that will be available at the festival and, throughout the text, describes the event - the fourth organized by the newspaper