Intro EViews Programming
Intro to EViews Programming
EViews is designed to run in a Windows environment. It utilizes most of the features in Windows such as menus and on-line help. However, things can be done in different ways: 1) selecting commands from the menu ("Point and Click") or typing in the commands directly ("Command Window") or running an EViews program file ("Run Program"). These are different ways of doing the same things. Feel free to experiment, but remember that in many instances (i.e. empirical assignments in one of my own courses), you are required to write an EViews program in order to document your work. Below I will discuss the main EViews command and programming features. Of course, for full details see the EViews Command and Programming Guide.
The specific commands do change over time with new versions of EViews. Check your EViews guide.
COMMANDS AND PROGRAMMING
EVIEWS BASICS
The EViews window
You should see the EViews window when you launch the program. In the EViews Window, just below the title bar is the main menu. Below the menu bar is an area called the command window. EViews commands may be typed in this window. The command is executed as soon as you hit Enter. The contents of the command area may be saved directly into a text file for later use: make certain that the command window is active, and then select File/Save As… . Some important EViews Commands are discussed below.
The area in the middle of the window is the work area where EViews will display the workfile window the various other windows that it creates.
EViews objects
Information in EViews is stored in objects. Each object consists of a collection of information related to a particular area of analysis. For example, a series object is a collection of information related to a set of observations on a particular variable. An equation object is a collection of information related to the relationship between a collection of variables. Associated with each type of object is a set of views and procedures which can be used with the information contained in the object. This association of views and procedures with the type of data contained in the object is what we term the object oriented design of EViews.
There is more than one way to examine the data in an object. Views are tabular and graphical windows that provide various ways of looking at the data in an object. For example, a series object has a spreadsheet view, which shows the raw data, a line graph view, a bar graph view, a histogram-and-statistics view, and a correlogram view. Series views also allow you to compute simple hypothesis tests and statistics for various subgroups of your sample. An equation object has a representation view showing the equation specification, an output view containing estimation results, an actual-fitted-residual view containing plots of fitted values and residuals, a covariance view containing the estimated coefficient covariance matrix, and various views for specification and parameter tests. Views of an object are displayed in the object’s window. Only one window can be opened for each object and each window displays only a single view of the object at a time. You can change views of an object using the View menu located in the object window’s toolbar or the EViews main menu.
Objects may be named or unnamed. When you give an object a name, the name will appear in the directory of the workfile, and the object will be saved as part of the workfile when the workfile is saved. You must name an object if you wish to keep its results. If you do not name an object, it will be called “UNTITLED”. Unnamed objects are not saved with the workfile, so they are deleted when the workfile is closed and removed from memory.
Reference:
EViews Help Topics, Index: Objects.
EViews expressions
One of the most powerful features of EViews is the ability to use and to process mathematical expressions. An EViews expression is a combination of numbers, series names, functions, and mathematical and relational operators. You can use these expressions to calculate a new series from existing series, to describe a sample of observations, or to describe an equation for estimation or forecasting.
Reference:
EViews Help Topics, Index: Operator; Numeric Expressions
EViews Help Topics, Index: Operator; Operators. Provides a list of the operators used in expressions involving series and scalar values.
EViews commands
Below the menu bar is an area called the command window. EViews commands may be typed in this window. The command is executed as soon as you hit ENTER. As you enter commands, EViews will remember them. You can scroll up to an earlier command, edit it, and hit ENTER. The modified command will be executed. EViews commands are an alternative to point-and-click. Point-and-click will leave no explicit record of the various options you selected and makes it difficult to evaluate how you obtained certain results. The main use of commands will be as part of writing EViews programs. Besides being a record of your EViews sessions, a program allows you quickly change part(s) of your EViews session and repeat the whole process without having to go through all the steps manually using either point-and-click or individual command window statements.
Reference:
EViews Help: Command & Programming Reference (PDF file). Read chapters 1, 2, 6.
EViews Help Topics, Index: Commands; Object Declaration
EViews Help Topics, Index: Commands; Object Assignment
EViews Help Topics, Index: Commands; Object Commands
EViews Help Topics, Index: Commands; Basic Command Summary
EViews Help Topics, Contents: Command Reference. A complete alphabetical listing of the commands, views, and procedures in EViews.
EVIEWS PROGRAMS
Programs
A program is a file of EViews commands. The simplest program is just a list of commands. Execution of the program is equivalent to typing the commands one by one into the command window. Simple programs allow you to generate a record of your research project. All the commands you used to obtain a particular result are made explicit and can be saved/printed. You can create a program containing the commands that take you from the creation of a workfile and reading of raw data, through the calculation of your final results, and construction of presentation graphs and tables.
Loops and replacement variables
The real power of programs comes from their ability to execute commands more than once. For example, you can write a program with commands to deal with the data from one industry, country, sample period, and then have the program do the same operations for each of the other industries, countries, sample periods. Loops determine how many times the same operations are repeated. Replacement variables are used to give different names to variables and results in each loop.
Reference:
EViews Help Topics, Index: Program; Program basics
Create and Run a Program:
It is possible to write and edit a program file during an interactive EViews session. Use the mouse to click on File, New, Program. Enter your program statements. Click on SaveAs. Save as <<filename.prg>>.
The structure of a program will normally be as follows:
* create a new workfile (CREATE) or open an existing workfile (OPEN)
* import raw data from a datafile, either ASCII or Excel or some other format (READ)
* generate new time series by transforming the basic data that you started with (SERIES (new) or GENR (old))
* execute your econometric analysis by estimating equations, calculating test statistics, using control variables to perform repetitive tasks, give names to tables that you want to save, etc.
* end your program
For appropriate syntax, available options and other commands see the EViews Help function and Command & Programming Reference (PDF file).
Use text comments extensively to understand your program later. Comment lines begin with a '.
To run a program use the options from the EViews toolbar: File, Open, Program <<filename.prg>> Run
To stop a program, press the F1 key (or use the command STOP in the program).
After running a program you can continue in an interactive EViews session by entering commands in the command window. Make a note of all corrections (changes, additions) made during your interactive EViews sessions.
Rewrite the program file <<filename.prg>> to incorporate the corrections.
Check carefully whether running the new program file <<filename.prg>> really turns out the expected results, i.e. results that correspond to the tables and graphs presented in your final copy of the research paper.
Print the program file <<filename.prg>> and provide this as an appendix.
Programming Statements / Commands
For a more specific and exhaustive list of commands see the EViews Command and Programming Reference (PDF file).
General commands
create q 1946:1 1988:4
read(e,a1) data.xls cp div r
show x
plot x
freeze graph1
smpl 1 100
series y = x +1
creates a workfile for quarterly data from 1946Q1 to 1988Q4
imports 3 series named cp div and r from the Excel file data.xls, you have to indicate the Excel sheet name, starting cell, column or row organization of variables
shows object x (variables, tables, graphs)
plots series x (alternative is graph)
freezes output so that content does not change with subsequent changes in data etc.
restricts sample for series calculation (sample period) and estimations (estimation period)
create a time series variable y using value(s) of x and add value 1
Regression commands
ls(options) y x1 x2 x3
arch(p,q,options) y x1 x2 x3
tsls(options) y x1 x2 @ z1 z2 z3
resids
@coefs
@stderrs
@ssr
var var1.ls 1 1 y1 y2 c
var1.@residcov
equation eq1.ls gpa c income
basic OLS regression of y on x1, x2 and x3
ARCH(p,q) regression
Two stage least squares regression with instruments z1, z2, z3
display graph of residuals
access vector of estimated coefficients
access vector of estimated standard errors of coefficients
access value of squared residuals of OLS regression
create and estimate a VAR models with 1 lag for 2 variables
access the estimated residual covariance matrix of the VAR
define a named equation eq1 and estimate it using OLS
Graphic commands
Operators
bar ser1 ser2 ser3
xy
create bar graphs
create xy (scatter) graph
+, -, *, /, ^
>, <, =, <>
<=, >=
and, or
@abs(x)
@log(x)
add, subtract, multiply, divide, raise to the power
greater, less, equal, not equal
less than or equal, greater than or equal
logical and, logical or
absolute values of x
natural logarithm of x (ln)
Functions
Time series functions
@movav(X,n)
@movsum(X,n)
d(X)
dlog(X)
Statistical distribution functions
@cnorm(x)
@dnorm(x)
@qnorm(p)
Descriptive statistic functions
@sum(X)
@obs(X)
@stdev(X)
@cov(X,Y)
Matrix functions
n-period backward moving average of X: 1/n SUMj=0n-1 Xt-j
n-period backward moving sum of X: SUMj=0n-1 Xt-j
1st order difference of series X: Xt - Xt-1
1st order difference of log of series X: ln(Xt) - ln(Xt-1)
cumulative density function of normal distribution
density function of normal distribution
quantile of normal distribution
sum of all x in current sample period
number of valid observations on x in current sample period
standard deviation of series x in current sample period
covariance
Program Variables
The real power of EViews programs comes from their ability to execute commands more than once and the use of variables. There are 3 types of EViews program variables
- Control variables
- String variables
- Replacement variables
Control variables are variables that you can assign alternative values and use anywhere in a program that you would normally use a number. The name of a control variable starts with an ! mark. A string variable is a variable whose value is a string of text and string variable names start with a % symbol. Control and string variables are can be used as replacement variables in command lines. In the execution of the command the replacement variable is replaced by its content. Curly braces { } mark the replacement variables.
Reference:
EViews Help Index: Program; Program variables
Control Variables
Control variables are variables that you can use in place of numerical values in your EViews programs. Once a control variable is assigned a value, you can use it anywhere in a program that you would normally use a number. The name of a control variable starts with an ! mark. After the !, the name should have 1 to 15 letters or digits. Examples of control variable names are: !X, !1,
!COUNTER .
You need not declare control variables before your refer to them, though you must assign them a value before use. Control variables are assigned in the usual way, with the control variable name on the left of an = sign and a numerical value or expression on the right. Examples: !x=7, !12345=0, !COUNTER= 12, !PI=3.14159.
Once assigned a value, a control variable may appear on the right side of an expression. Examples: !counter = !counter + 1, genr dnorm=1/SQR(2*!pi) * exp(-1/2*epsilon^2), SCALAR STDX=X/SQR(!varX), smpl 1950:1+!I 1960:4+!I.
Control variables do not exist outside of your program and are automatically erased after a program finishes. As a result, control variables are not saved when you save the workfile. You can save the values of control variables by creating new EViews objects which contain the values of the control variable. Examples: SCALAR STDX=SQR(!VARX), SAMPLE YEARS 1960+!Z 1990
String Variables
A string is text enclosed in double quotes. Examples: "Gross Domestic Product", "3.14159", "ar(1) ar(2) MA(1) MA(2)". A string variable is a variable whose value is a string of text. The name of a string variable starts with a % symbol. String variables are assigned by putting the string variable name on the left of an = sign and a string expression on the right. Examples: %value="Value in Millions of U.S. dollars", %ARMAS="AR(1) AR(2) MA(1) MA(2)", %MYSAMPLE="83:1 96:12", %dep=" HS", %PI=" 3.14159".
Once assigned a value, a string variable may appear on the right side of an EViews expression. You can use strings to help you build up commands and variable names or as headings in tables. Examples: GNP.LABEL %VALUE, SMPL %mysample, equation eq1.ls %DEP C %DEP(-1),
EQUATION EQ2.LS %DEP c %Dep(-1) %ARMAS.
EViews has number of operators and functions for manipulating strings; a complete list is in Manipulating Strings. Here is a quick example: !JOE_AGE=50, %st1="His name is Joe", %st2="His age is 199", %st3=@RIGHT(%st1, 3) +"’s" + @MID(%st2, 4, 7) + @STR(!JOE_AGE). In this example %ST3 is set to "Joe’s age is 50".
String variables are like control variables in that they only exist during the time that your program is executing so they are not stored in the workfile. You can save string data in a cell of a TABLE, as described later in this chapter.
A string variable can contain a string which represents a number. If there is an assignment statement with a numeric variable on the left side of the equality and a string number on the right side, the string variable will be treated as though it were a number. Example: !CTRLVAR=.051072, scalar var1=!ctrlvar, %STRVAR=" .051072", SCALAR var2=%STRVAR will create identical scalar objects VAR1 and VAR2.
Replacement Variables
EViews allows you to construct command lines using the contents of string and control variables. For example if the string variable %X is given by %X = "GDP" then the program line, LS %X C %X(-1) would be interpreted as: LS GDP C GDP(-1). Changing the contents of %X to "M1" changes the interpretation of the line to: LS M1 C M1(-1)
In this context we refer to the string variable %X as a replacement variable because it is replaced in the command line by its contents.
Replacement variables may be combined with letter and digits or with other replacement variables to form longer words. When you do this, you should use curly braces to mark the replacement variables. Example: %TYPE= "Low", %VNAME=" Income", series inc1, INC1.LABEL {%TYPE}{%VNAME}, %TYPE= "High", series inc2, inc2.label {%TYPE}{%VNAME}. Here, the comment "Low Income" is put in the label for the series INC1 and "High Income" is put in the label for INC2. In these cases, the term {%TYPE}{%VNAME} is a replacement variable since the command is constructed by replacing the string variables with their contents.
Control variables may also be used as replacement variables. Consider the example, GENR Y{!X} = NRND where !X is a control variable. If !X=1, this line is interpreted as GENR Y1= NRND. If !X=99 then the command is interpreted as GENR Y99 =NRND.
An important use of replacement variables is in constructing object names. Examples: !A = 1, %b = 2, %C = "VAR", series X{!A}, matrix x{%B}, vector X_{%C}IABLE. Here we have declared a series named X1, a matrix named X2, and a vector named X_VARIABLE.
You need to use braces when you call a function with a replacement variable. EViews functions do type checking. Functions that take string arguments only allow string to be passed in and functions that take series arguments only accept series. To pass a series into a series function via a replacement variable you must enclose it in braces. For example when trying to find the number
of valid observations in a series named INCOME, you can use the @OBS function: @OBS(INCOME).
If you wish to use the string variable %VAR to refer to the INCOME series, the proper syntax is %VAR="INCOME", @obs({%VAR}). The function @OBS(%VAR) will return an error since the @OBS function requires a series, not a string as an argument.
When you pass series names to subroutines (discussed below) via replacement variables, you also need to use braces.
Using replacement variables gives you great flexibility in naming objects in your programs. You should, for clarity sake, take care to avoid using the same names to refer to different objects. Consider the following example which shows the potential for confusion. Example (AVOID): !A=1, series x{!a}, !A=2, matrix x{!a}. In this small snippet it might appear that we are giving the same name for a series and a matrix. Actually it is easy to see that X1 is the series and X2 is the matrix. But in a more complicated program, where the assignment of !A may be separated from the series declaration by many program lines, it may be difficult to tell at a glance what the name of the replacement variable X{!A} happens to be. A better approach is to use different names for different kinds of variables, !A=1, series X{!A}, !A=2, matrix Y{!A}, or even better, to use descriptive names which identify the objects.
Program Arguments
Program arguments are special string variables that are passed to your EViews program when you run the program. Arguments allow you to change the value of string variables every time you run the program. You may use them in any context where a string variable is appropriate. Any number of arguments may be included in a program; they will be named %0, %1, %2, and so on.
Reference:
When you run your program, you will also supply the values of the arguments. If you use the Run button or File/Run, you will see a dialog box where you can type in the values of the arguments. If you use the RUN command, you should list the arguments consecutively after the name of the program. For example suppose we have a program named REGPROG with the following command lines:
EQUATION EQ1
SMPL 80:3 94:1
EQ1.LS %0 C %1 %1(-1) TIME
To run REGPROG from the command line with %0=LGDP and %1=M1, we enter RUN REGPROG LGDP M1. This program performs a regression of the variable LGDP, on C, M1, M1(-1), and TIME, by executing the line, EQ1.LS LGDP C M1 M1(-1) TIME
To run this program using the buttons, click on the Run button on the program window, or File/Run. You will see a dialog box where you can type in the name of the program, and another box where you will enter the values of the arguments. Enter REGPROG for the name of the program, and type LGDP M1 in the Program Arguments box.
Any arguments in your program that are not initialized in the RUN command or RUN dialog are treated as blanks. For example, suppose you have a one-line program named REGRESS: LS Y C TIME %0 %1 %2 %3 %4 %5 %6 %7 %8. To run this program from the command line you can type, RUN REGRESS X X(-1) X(-2) which executes the command LS Y C TIME X X(-1) X(-2). If instead, you enter RUN REGRESS EViews will execute LS Y C TIME. In both cases, EViews ignores any arguments that are not included in your RUN command.
As a last example, we repeat our simple forecasting program from above, but using arguments to simplify our work. Suppose you have the program, MYPROG,
WORKFILE %0 M 68:3 97:6
FETCH %1
SMPL 68:5 92:12
EQUATION REG1.LS %1 C %1(-1)
REG1.MAKERESID {%1}res
REG1.FORECAST {%1}fit
smpl 93:1 97:6
FREEZE({%1}PLOT) {%1}res.LINE
SAVE
The results of running the two example programs at the start of this chapter can be duplicated by running MYPROG with arguments: RUN MYPROG MYHOUSE HSF, RUN MYPROG MYSP500 FSPCOM
Controlling programs with If statement, For loop, While loop
Controlling execution of a program means that you can selectively execute commands or repeat commands under changing conditions. The If command executes a set of commands if a certain condition is fulfilled. The For loop repeats a set of commands for a fixed number of times. The While loop repeats a set of commands as long as a certain condition is fulfilled.
Reference:
EViews Help Topics, Index: Program; Control of Execution
IF Statements
There are many situations where you may wish to execute commands only if some condition is satisfied. EViews uses IF/ENDIF statements to indicate the condition to be met and the commands to be executed.
The IF statement starts with IF, followed by an expression for the condition, and then the word THEN. You may use AND and OR statements in the condition, using parentheses to group parts of the statement as necessary. If the expression is TRUE, all of the commands until the next ENDIF are executed. If the expression is FALSE, all of the commands are skipped. The expression may also take a numerical value. In this case, zero is equivalent to a FALSE and any
non-zero value is considered to be a TRUE. Examples:
IF !STAND=1 OR (!RESCALE=1 AND !REDO=1) THEN
SERIES GNPSTD=GNP/SQR(GVAR)
SERIES CONSTD=CONS/SQR(CVAR)
ENDIF
IF !A>5 and !A<10 THEN
SMPL 1950:1 1970:1+!A
ENDIF
IF !SCALE THEN
GENR NEWAGE=AGE/!SCALE
ENDIF
Note, all indentation done here is for program clarity and has no effect on the execution of the program lines.
An IF statement can have an ELSE clause containing commands to be executed if the condition is FALSE. If the condition is TRUE, all of the commands up to the ELSE will be executed. If the condition is FALSE, all of the commands between the ELSE and the ENDIF will be executed. Example:
IF !SCALE>0 THEN
GENR NEWAGE=AGE/!SCALE
ELSE
GENR NEWAGE=AGE
ENDIF
IF statements can also be applied to string variables and can be nested:
IF %0="CA" OR %0="IN" THEN
GENR STATEID=1
ELSE
IF %0="MA" THEN
GENR STATEID=2
ELSE
IF %0="ID" THEN
GENR STATEID=3
ENDIF
ENDIF
ENDIF
Strings are all converted to upper case before comparison. Strings are considered equal if they are the same length, and every character matches. One string is less than another if the corresponding characters come earlier in the alphabet. A string is greater than another, if the corresponding characters come later in the alphabet. For example, suppose we assign the string values %1 = "a",
%2 = "B", then the following IF statements IF %1 = "A" THEN ..., IF %1 <= "ABC" THEN ..., IF %1 < "ABC" THEN ..., are TRUE, while the following statements, IF %1 = %2 THEN ..., IF %2 <= "ABC" THEN ..., IF %2 < "ABC" THEN ..., are FALSE. The string A is less than ABC since the first characters of the strings match; the remaining characters BC make the string greater. B is greater than ABC even though it is shorter, since the first character is greater.
In order to test whether a string contains any characters, test whether it is not equal to an empty string. We do allow a fast test for an empty string - the NOT function will return true of the string is empty. For example, suppose that we assign the string value %1 = "". Then, the comparison If %1 THEN ... generates an error since %1 is not compared with another string. To test for an empty string, use either IF %1 <> "" THEN ... or better yet, IF NOT %1 THEN ...
The FOR Loop
The FOR loop allows you to repeat a set of commands for different values of a control or string variable. The FOR loop begins with a FOR statement and ends with a NEXT statement. Any number of commands may appear between these two statements.
The syntax of the FOR statement differs depending upon whether it uses control variables or string variables.
FOR Loops with Control Variables or Scalars
When you wish to repeat statements for different values of a control variable, the FOR statement involves setting a control variable equal to an initial value, followed by the word TO, and then an ending value. After the ending value you may include the word STEP followed by a number indicating by how much to change the control variable each time the loop is executed. If you
don’t include STEP, it is taken as 1. Examples:
FOR !J=1 TO 10
SERIES DECILE{!J} = (INCOME<LEVEL{!J})
NEXT
In this example, STEP=1 and the variable !J is twice used as a replacement variable, first for the ten series declarations DECILE1 through DECILE10 and for the ten variables LEVEL1 through LEVEL10.
FOR !J=10 TO 1 STEP -1
GENR RESCALE{!J}=ORIGINAL/ !J
NEXT
In this example, STEP=-1 and !J is used as a replacement variable to name the ten constructed series RESCALE10 through RESCALE1, and as a scalar in dividing the series ORIGINAL.
The FOR loop is executed first for the initial value, unless that value already exceeds the upper limit. After it is executed for the initial value, the control variable is incremented by STEP and EViews checks to see if it has reached the limit; if it has, execution stops.
One important use of for loops with control variables is to change the SMPL. If you add a control variable to a date in a SMPL command, you will get a new date as many observations forward as the current value of the control variable. Here is a FOR loop that gradually increases the size of the sample and estimates a rolling regression:
FOR !HORIZON=10 to 72
SMPL 1970:1 1970:1+!HORIZON
EQUATION RES{!HORIZON}.LS SALES C ORDERS
NEXT
One other important case where you will use loops with control variables is in accessing a series of elements of a series or other object. Example:
!SUM=0
!NUM=100
VECTOR(!NUM) X
FOR !I=1 to !NUM
!SUM=!SUM+X(!I)
NEXT
SCALAR MEANVAL=!SUM/!NUM
computes the mean of the first 100 elements of the X series and saves it in a scalar object MEANVAL.
You can nest FOR loops to contain loops within loops. The entire inner FOR loop is executed for each successive value of the outer loop. Example:
MATRIX(25,10) XX
FOR !I=1 to 25
FOR !J=1 to 10
XX(!I,!J)=(!I-1)*10+!J
NEXT
NEXT
Never change the control variable within the loop. Example (AVOID):
For !I=1 TO 25
VECTOR A!I
!I=!I+10
NEXT
Here, both the FOR loop and the assignment statement within the loop change the value of the control variable !I. Loops of this type are notoriously difficult to follow and may produce unintended consequences. If you want to change the control variable inside the loop, use a WHILE loop.
You may execute FOR loops with scalars instead of control variables. However you must declare the scalar, and you may not use the scalar as a replacement variables. For example,
SCALAR I
SCALAR SUM=0
VECTOR (10) X
FOR I=1 TO 10
X(I)=I
SUM=SUM+I
NEXT
In this example, the scalars I and SUM remain in the workfile after the program is through running, unless they are explicitly deleted.
FOR Loops with String Variables
When you wish to repeat statements for different values of a string variable, you can use the FOR loop to let a string variable range over a list of string values. Give the name of the string variable followed by the list of values. Example:
FOR %y GDP GNP NDP NNP
EQUATION {%Y}trend.ls %y C {%Y}(-1) TIME
NEXT
executes the commands, EQUATION GDPTREND.LS GDP C GPD(-1) TIME, EQUATION GNPTREND.LS GNP C GNP(-1) TIME, EQUATION NDPTREND.LS NDP C NDP(-1) TIME, EQUATION NNPTREND.LS NNP C NNP(-1) TIME.
You can put multiple string variables in the same FOR statement. EViews will process them in groups. Example:
FOR %1 %2 %3 55:1 60:4 EARLY 70:2 80:3 MID
75:4 95:1 LATE
SMPL %1 %2
EQUATION {%3}EQ.ls sales c orders
NEXT
In this case, the elements of the list are taken in groups of three. The loop is executed three times for the different sample pairs and equation names. The following commands are executed.
SMPL 55:1 60:4
EQUATION EARLYEQ.LS SALES C ORDERS
SMPL 70:2 80:3
EQUATION MIDEQ.LS SALES C ORDERS
SMPL 75:4 95:1
EQUATION LATEEQ.LS SALES C ORDERS
Note the difference between this construction and nested FOR loops. Here, all string variables are advanced at the same time, whereas with nested loops, the inner variable is advanced over all choices while the outer variable is held constant. Example:
EQUATION EQ
!EQNO = 1
FOR %1 55:1 60:4
FOR %2 70:2 80:3 75:4
SMPL %1 %2
'Form equation name as EQ1 through EQ6
EQUATION EQ{!EQNO}.LS SALES C ORDERS
!EQNO=EQNO!+1
NEXT
NEXT
DELETE EQ
Here, the SMPL statements will be for the pairs (55:1 70:2), (55:1 80:3), (55:1 75:4) and (60:4 70:2), (60:4 80:3), (60:4 75:4).
The While Loop
In some cases, we wish to repeat a series of commands several times, but only while one or more conditions is satisfied. Like the FOR loop, the WHILE loop allows you to repeat commands, but WHILE provides greater flexibility in specifying the required conditions.
The WHILE loop begins with a WHILE statement and ends with a WEND statement. Any number of commands may appear between the two. WHILE loops can be nested.
The WHILE statement consists of the WHILE command followed by an expression involving a control variable. The expression should have a logical (TRUE/FALSE) value or a numerical value. In the latter case, zero is considered FALSE and any non-zero value is considered TRUE. If the expression is TRUE, the following statements down to the next WEND will be executed and then the loop will be repeated. If the condition is FALSE, EViews will skip the following commands and continue on with the rest of the program following the WEND statement. Example:
!VAL=1
!A=1
WHILE !VAL<10000 and !A<10 THEN
SMPL 1950:1 1970:1+!A
SERIES INC{!VAL}=INCOME/!VAL
!VAL=!VAL*10
!A=!A+1
WEND
There are four parts to this WHILE loop. The first part is the initialization of the control variables used in the test condition. The second part is the WHILE statement which includes the test condition and is terminated by the word THEN. The third part is the statement updating the control variable. Finally the end of the loop is marked by the word WEND. Unlike a FOR statement, the WHILE statement does not provide for the updating of the control variable used in the test condition. You need to include a statement in the loop that changes the control variable, or your loop will never terminate. Use the F1 key to stop a program which is in an infinite loop.
In the example above of a FOR loop that changed the control variable, a WHILE loop provides a much clearer program:
!I=1
WHILE !I<=25
VECTOR A{!I}
!I=!I+11
WEND
Other Flow of Control Tools
Occasionally, you will wish to stop a program or break out of a loop based on some conditions. To stop a program executing in EViews, use the STOP command. For example, the following program will calculate the sum of the logs of the first 10 elements of series X. Since the log function is not defined for a nonpositive number, the program immediately stops upon finding a negative value.
!SUM=0
FOR !1 = 1 to 10
IF X(!1) <= 0 THEN
STOP
ENDIF
!SUM=!SUM+LOG( x(!1) )
NEXT
Sometimes, you do not wish to stop the entire program when a condition is satisfied; you just wish to exit the current loop. The EXITLOOP command will exit the current FOR or WHILE statement and continue running the program. For example, the following program fills the first 5 elements of a vector V1 with the sum of the logs of ten elements of another vector X (V1(1) contains the sum of the logs of X(1)-X(10), V1(2) contains the sum of the logs of X(2)-X(11), and so on.)
VECTOR(10) V1
SCALAR SUM
FOR !1 = 0 to 4
SUM=0
FOR !2 = 1 to 10
IF X(!1+!2) <= 0 then
SUM=9999
EXITLOOP
ENDIF
SUM=SUM+LOG(X(!1+!2))
NEXT
V1(!1+1)=SUM
NEXT
SUM is set to 9999 if the loop fails so that when you look at the output, any entry which could not be computed will stand out.
In many cases, the same numerical result may be produced using SMPL statements with an IF condition and GENR commands. In most cases, avoiding loops will result in faster programs, but which technique you choose to use is a matter of taste.
Subroutines
A subroutine is a collection of commands that allows you to perform a given task repeatedly, with minor variations, without actually duplicating the commands. You can also use subroutines from one program to perform the same task in other programs.
Reference:
EViews Help Topics, Index: Program; Subroutines
Defining Subroutines
A subroutine starts with the word SUBROUTINE followed by the name of the routine and any arguments, and ends with ENDSUB. Any number of commands can appear in between. The simplest type of subroutine has this form:
SUBROUTINE Z_SQUARE
GENR X=Z^2
ENDSUB
where the SUBROUTINE keyword is followed only by the name of the routine. This subroutine has no arguments so that it will behave identically every time it is used. It forms the square of the existing series Z and stores it in the new series X.
You can use the RETURN command to force EViews to exit from the subroutine at any time. A common use of RETURN is to exit from the subroutine if an unanticipated error is detected:
SUBROUTINE REGRESS
EQUATION REG.LS CONS C CONS(-1) AR(1) AR(2)
REG.MAKERESID TESTRES
' calculate sum of squared residuals
SCALAR SSR=@SUM(TESTRES^2)
' an error is indicated by the SSR being not available
IF SSR=NA OR SSSR<0 THEN
RETURN ' on an error exit
ENDIF
EQUATION RES.LS TESTRES c TESTRES(-1 to -4)
ENDSUB
The subroutines so far have been written to work with a specific set of variables. More generally, subroutines will use arguments. If you are familiar with another programming language, you probably already know how arguments allow you to change the behavior of the group of commands each time the subroutine is used. Even if you haven’t encountered subroutines, you are probably familiar with similar concepts from mathematics. You can define a function, say [f(x) = [1+exp(x)]-1 where f depends upon the argument x. The argument x is merely a place holder--it’s there to define the function and it does not really stand for anything. Then if you want to evaluate the function at a particular numerical value, say .7839, you can write f(.7839). If you want to evaluate the function at a different value, say .50123, you merely write f(.50123). By defining the function, you save yourself from writing out the whole expression every time you wish to evaluate it for a different value.
To define a subroutine which has arguments, you start with SUBROUTINE, followed by the subroutine name, a left parenthesis, the arguments separated by commas, and finally a right parenthesis. Each argument is specified by listing a type of EViews object, followed by the name of the argument. Control variables may be passed by the SCALAR type and string
variables by the STRING type. Example:
SUBROUTINE PWR(SERIES V, SERIES Y, SCALAR PW)
V=Y^PW
ENDSUB
This subroutine generalizes the example above. Running PWR will fill the series given by the argument V with the power, PW, of the series specified by the argument Y. So if you set V equal to X, Y equal to Z, and PW equal to 2, you will get the equivalent of the subroutine Z_SQUARE above.
Subroutine Placement
Your subroutine definitions should be placed, in any order, at the beginning of your program. The subroutines will not be executed until they are executed by the program using a CALL statement. Example:
SUBROUTINE Z_SQUARE
GENR X=Z^2
ENDSUB
' Start of program execution
LOAD MYWRKFIL
FETCH Z
CALL Z_SQUARE
Execution of this program begins with the LOAD statement; the subroutine definition is skipped. The subroutine definitions must not overlap--after a SUBROUTINE, there should be an ENDSUB before the next SUBROUTINE. Subroutines may call each other, or even call themselves.
You may wish to place frequently used subroutines in a separate program file and use an INCLUDE statement to insert them at the beginning of your program.
Suppose, for example, that you have a program file named POWERS.PRG which contain the declarations of the Z_SQUARE and PWR subroutines above. Then you may put the line
INCLUDE POWERS.PRG
at the top of any other program that needs to call Z_SQUARE and PWR. You can use the routines in these programs as though they are built-in parts of the EViews programming language. INCLUDE also accepts a full path to the program file and you may have more than one INCLUDE statement in a program. Example:
INCLUDE c:\PROGRAMS\POWERS.PRG
INCLUDE REGRESS
LOAD MYWRKFIL
CALL OLS
FETCH Z
CALL Z_SQUARE
Calling Subroutines
Once a subroutine is defined in your program, you may execute the commands in the subroutine by using the CALL command. CALL should be followed by the name of the subroutine, and a list of any argument values you wish to use, enclosed in parentheses and separated by commas. If the subroutine takes arguments, they all must be provided in the same order as in the declaration statement. Examples:
INCLUDE POWERS
LOAD MYWORK
FETHCH Z GDP
SERIES X
SERIES GDP2
SERIES GDP3
CALL Z_SQUARE
CALL PWR(X,Z,2)
CALL PWR(GDP2,GPDP,2)
CALL PWR(GDP3,GDP,3)
The first two calls will fill the series X with the value of Z squared. The third example creates the series GDP2 which is GDP squared. The last call creates the series GDP3 as the cube of GDP.
When a subroutine’s argument is a SCALAR, the subroutine may be called with a scalar, a control variable, a simple number (such as 10 or 15.3), a matrix element (such as X(1,2)) or a scalar expression (such as !Y+25). Subroutines that take matrix and vector arguments can be called with a matrix name or a matrix expression. All other arguments must be passed to the subroutine with a simple object (or string) name referring to a single object of the correct type.
Global and Local Variables
Subroutines work with variables and objects that are either global or local. Global variables refer either to objects which existed in the workfile when the subroutine was called, or to the objects that are created by a subroutine and placed in the workfile. Global variables remain in the workfile when the subroutine finishes. A local variable is one that has meaning only within the subroutine. Local variables are deleted from the workfile once a subroutine finishes. The program that calls the subroutine will not know anything about a local variable since the local variable will disappear once the subroutine finishes and you return to the original program.
Global Subroutines
By default, subroutines in EViews are global. Any global subroutine may refer to any global object that exists in the workfile at the time the subroutine is called. Thus, if Z is a series in the workfile, the subroutine may refer to and, if desired, alter the series Z. Similarly, if Y is a global matrix that has been created by another subroutine, the current subroutine may use the matrix Y.
The rules for variables in global subroutines are: · Newly created objects are global and will be included in the workfile when the subroutine finishes. · Global objects may be used and updated directly from within the subroutine. If, however, a global object has the same name as an argument in a subroutine, the variable name will refer to the argument and not the global variable. · The global objects corresponding to arguments may be used and updated by referring to the arguments. Example:
SUBROUTINE Z_SQUARE
GENR X=Z^2
ENDSUB
LOAD MYWRKFIL
FETCH Z
CALL Z_SQUARE
Z_SQUARE is a global subroutine which has access to the global series Z. The new global series X contains the square of the series Z. Both X and Z will remain in the workfile when Z_SQUARE is finished.
If one of the arguments of the subroutine has the same name as a global variable, the argument name takes precedence. Any reference to the name in the subroutine will refer to the argument, not the global variable. Example:
SUBROUTINE SQSERIES(SERIES Z)
GENR X=Z^2
ENDSUB
LOAD MYWRKFIL
FETCH Z
FETCH Y
CALL SQSERIES(Y)
In this example, there is a series Z in the original workfile and Z is an argument of the subroutine. Calling SQSERIES with the argument set to Y tells EViews to use the argument rather than the global Z. Upon completion of the routine, X will contain the square of the series Y, not the square of the series Z.
Global subroutines may call global subroutines. You should make certain to pass along any required arguments when you call a subroutine from within a subroutine. Example:
SUBROUTINE WGTOLS(SERIES Y, SERIES WT)
EQUATION EQ1
CALL OLS(EQ1,Y)
EQUATION EQ2
GENR TEMP= Y/SQR(WTt)
CALL OLS(EQ,TEMP)
DELETE TEMP
ENDSUB
SUBROUTINE OLS(EQUATION EQ, SERIES Y)
EQ.LS Y C Y(-1) Y(-1)^2 Y(-1)^3
ENDSUB
which we can run by executing
LOAD MYWORK
FETCH CPI
FETCH CONS
CALL WGTOLS(CONS, CPI)
In this example, the subroutine WGTOLS explicitly passes along the arguments for Y and WT to OLS, otherwise those arguments would not be recognized by the OLS subroutine. If Y and EQ were not passed, OLS would try to find a global series named Y and a global equation named EQ, instead of using CONS and EQ1 or EQ2.
You cannot use a subroutine to change the object type of a global variable. Suppose that we wish to declare new matrices X and Y by using a subroutine NEWXY. In this example, the declaration of the matrix Y works, but the declaration of matrix X generates an error because a series named X already exists:
SUBROUTINE NEXY
MATRIX(2,2) X=0
MATRIX(2,2) Y=0
ENDSUB
LOAD MYWRK
SERIES X
CALL NEWXY
EViews will return an error indicating the global series X already exists and is of a different type than a MATRIX.
Local Subroutines
All objects created by a global subroutine will be global and will be in the workfile upon exit from the subroutine. If you include the word LOCAL in the definition of the subroutine, you create a local subroutine. All objects created by a local subroutine will be local and will be removed from the workfile upon exit from the subroutine. Local subroutines are most useful when you wish to write a subroutine which creates many objects that you do not wish to keep.
The rules for variables in local subroutines are: · You may not use or update global objects directly from within the subroutine. · The global objects corresponding to arguments may be used and updated by referring to the arguments. · All other objects in the subroutine are local, and will vanish when the subroutine finishes. Example:
SUBROUTINE LOCAL OLS(SERIES Y, SERIES R, SCALAR SSR)
EQUATION TEMP_EQ.LS Y C Y(-1) Y(-1)^2 Y(-1)^3
TEMP_EQ.MAKERESID RES
SSR=@SUM(RES^2)
ENDSUB
We can call this subroutine from the following program:
LOAD MYWRK
CFETCH HSFf
SERIES HRES
EQUATION EQ1.LS HSF C HSF(-1)
EQ1.MAKERESID RES
SCALAR SSRr=@SUM(RES^2)
SCALAR USSR
CALL OLS(HSF, HRESs, USSR)
In the subroutine, the equation object TEMP_EQ, and the scalar SSR are local. These objects will not be included in the workfile and will vanish when the subroutine is finished. The series object HRES is updated by the subroutine through the references to the argument R, while the scalar object USSR is updated through reference to SSR. The global series RES and global scalar SSR
will not be updated and will still be based upon EQ1.
Local subroutines can call global subroutines and vice versa. The global subroutine will only have access to the global variables, and the local subroutine will only have access to the local variables, unless information is passed between the routines via arguments. Example:
SUBROUTINE NEWOLS(SERIES Y, SERIES RES)
EQUATION EQ1.LS Y C Y(-1)
EQ1.MAKERESID RES
SCALAR SSR=@SUM(RES^2)
SCALAR USSRr
CALL OLS(Y, RES, USSR)
ENDSUB
Then calling this routine with
LOAD MYWRK
CFETCH HSF
SERIES HRES
CALL NEWOLS(HSF, HRES)
produces equivalent results. Note that the subroutine NEWOLS still does not have access to any of the temporary variables in OLS, even though OLS is called from within NEWOLS.
Manipulating Strings
Reference:
EViews Help Topics, Index:
Strings and string variables may be combined with the + operator. For example:
%ST1="The name"
%ST2="X"
%ST3=%ST1 + "is " + %ST2
would leave the string "The name is X" in the string variable %ST3.
In addition, EViews provides a number of functions that operate on strings:
@LEFT: returns a string containing a requested number of characters at the left end of a string. Put the string and the number of characters in parentheses. Example: @LEFT("I didn't do it",5). This function has the value "I did".
@MID: returns a requested number of characters starting from a specified location in the string and going to the right. Example: @mid("I doubt I did it",9,5). This function has the value "I did".
If you omit the number of characters from @MID, it will return all of the characters after the specified one. Example: @mid("I doubt I did it",9). This function has the value "I did it".
@RIGHT: returns a string containing a requested number of characters at the right end of a string. Put the string and the number of characters in parentheses. Example: @right("I doubt I did it",8). This function has the value "I did it".
@STR: returns a string representing the given number. Example:
!x=15
@STR(!x)
returns a string containing "15".
@VAL: returns a number when applied to a string representing a number. Example:
%X="17.4648"
@VAL(%X)
This function has the numerical value 17.4648. If the string has any non-digits, they are considered to terminate the number. If the first character is not a digit, the function returns zero.
@OTOD: (Obs to Date) returns a string representing the date given by the offset from the start of the workfile. The first observation in the workfile has an offset of 1. Example:
CREATE Q 50:1 90:4
!x=16
%DATE =@OTOD(!x)
returns a string containing "1953:4".
@DTOO: returns a scalar offset from the beginning of the workfile of the string date. Example:
CREATE A 1945 1999
%DATE=1960
!T=@OTOD(%DATE)
returns a scalar containing 16.
Combining the string functions and the + operator allows you to build up strings with different meanings. To repeat the example from above,
!JOE_AGE=50
%ST1="His name is Joe"
%ST2="His age is 199"
%ST3=@RIGHT(%ST1,3) + "’s" + @MID(%ST2,4,7) + @STR(!JOE_AGE)
%ST3 is set to "Joe’s age is 50".
Here is an example of building up a string in a loop:
FOR %1 AGE EDUC IQ
FOR %2 _OWN _FATHER _MOTHER
%REG = %REG + " " +%1 + %2
NEXT
NEXT
LS INCOME C %REG
This example runs the regression:
LS INCOME C AGE_OWN AGE_FATHER AGE_MOTHER EDUC_OWN EDUC_FATHER EDUC_MOTHER IQ_OWN
IQ_FATHER IQ_MOTHER
Tables
You can use EViews commands to generate custom tables of output from your programs. A table is an object made up of rows and columns of string values. Once you declare a table, each of its cells, defined by row and column pairs, is available for you to fill with strings. You can put a string directly into a cell, you can move the contents of a string variable into a cell, or you can put a number into a cell, in which case it is converted automatically into a string.
After you have filled up all of the cells of a table, you can PRINT the table object using the PRINT command or by pressing the Print button on the table menu.
Reference:
EViews Help Topics, Index: Table
Declaring a Table
To declare a table, indicate the number of rows and columns and provide a valid name. Example: TABLE(10,20) BESTRES creates a table with 10 rows and 20 columns called BESTRES. You can change the size of a table by declaring it again. Re-declaring a table does not destroy the contents of the table. Any cells in the new table that existed in the original table will
contain the original data.
Tables are automatically resized when you attempt to fill a table cell outside its current dimension. This behavior is different than for matrices which give an error when an out of range element is accessed.
Controlling Appearance
Each row of the table can hold a single line of text. Initially, each column is wide enough to hold about 10 characters, but you can change the width of a column with the SETCOLWIDTH command. To change the width of a column enter the keyword SETCOLWIDTH, followed by the name of the table, the number of the column you wish to resize, and the approximate number
of characters, all enclosed in parentheses. EViews measures units in terms of the width of a numeric character. Because different characters have different widths, the actual number of characters that will fit may differ somewhat from the number you specify. Example: SETCOLWIDTH(BESTRES,2,12).
You can use the SETLINE command to place a horizontal separator line in a table. Put the name of the table and the row number that you would like to have appear as a line in parentheses. Example: SETLINE(BESTRES,8) puts a separator line in the eighth row of the table BESTRES.
Filling Cells
You can put a value into a cell of a table with regular assignment statements. Enter the table name and the row and column positions in parentheses, followed by an assignment statement. The assignment statement may use any object, function, or control variable that has a scalar numerical value or a string.
You can put text into a cell with a regular assignment statement. Examples:
BESTRES(1,6) = "Convergence criterion"
%STRVAR = "LM Test"
BESTRES(2,6) = %STRVAR
BESTRES(2,6) = BESTRES(2,6)+" with 5 DF"
Numbers may be entered directly into cells, or using special functions to convert numbers to strings. If entered directly, the number will automatically be converted into a string with as many digits as will fit in the cell. If the number is too big to fit in the cell, scientific notation will be used. Alternatively, you can convert a number into a string by using the @STR function; the string
will contain the fewest decimal places required to represent the number. Examples:
TAB(3,4)=15
TAB(4,2)="R-Squared = "+@STR( EQ1.@R2)
!EV=10
TAB(3,4) = "There are "+@STR(!EV)+" events"
The first example will be printed as 15.000000 under the default format. More generally, the SETCELL command will fill a cell and format it according to your specification. Put the following
information in parentheses: the name of the table, the row and column of the cell, the number or string to be put into the cell, and, optionally, a justification code or a decimal format code, or both. The justification codes are "C" for centered, "R" for right-justified, "L" for left-justified.
The decimal format code is a number. If the number is positive, the cell will use a fixed format. A positive decimal format code should be a decimal number whose value to the left of the decimal point determines the total number of characters used to represent the number, while the value to the right of the decimal point indicates how many digits should be to the right of the decimal in representing the data. For example, a decimal format code of 10.4 means use 10 characters to represent the data, with 4 digits to the right of the decimal.
If you wish to let EViews choose the format for numerical data, use a negative number for the format code. The data will be represented by the specified number of characters, with one space reserved for the sign of the number, one space reserved for a decimal point, and the remainder used for digits. If necessary, the number will be represented using scientific notation. Examples:
SETCELL(RESULTS,9,11,%LABEL)
This puts the contents of %LABEL into row 9, column 11 of RESULTS.
SETCELL(BIG_TABl,1,1,%INFO,"C")
This inserts the contents of %INFO, centered.
SETCELL(REGRESS,5,5,!DATA)
This put the number in !DATA into REGRES, with standard numerical formatting.
SETCELL(REGRESS,5,6,!DATAa,8.4)
This puts the number in !DATA into REGRES, with 8 total digits and 4 digits to the right of the decimal.
SETCELL(REGRESS,3,11,!DATTA,"R",8.3)
This puts the number in !DATA into REGRES, right-justified, with 8 total digits and 3 digits to the right of the decimal.
SETCELL(REGRESS,4,2,!DATA,-7)
This puts the number in !DATA into REGRES, with 7 total digits.
Table Program Example
Here is a program that demonstrates the use of subroutines and tables. Suppose you wish to construct various tables describing a series. All of the tables are designed to have a header at the top that gives the series name and its mean, but will have different information below. The first two lines of each table will look like:
SERIES: UNEMPLOYMENT
MEAN: 6.756566
The subroutine fills out this header in the table.
SUBROUTINE HEADER1(SERIES IN, string %1, TABLE out)
!OBS=@OBS(IN)
!COUNT=0
!T=0
!SUM=0
WHILE !COUNT<!OBS THEN
!T=!T+1 'increment index
IF IN(!T)<>NA THEN 'do not include NA's
!SUM=!SUM+IN(!T) 'accumulate sum
!COUNT=!COUNT+1 'count included obs
ENDIF
WEND
!MEAN=!SUM/!OBS
OUT( 1,1)= "series:"
OUT( 2, 1)= "Mean:"
OUT( 1, 2)= %1
OUT( 2, 2)= !MEAN
ENDSUB
If UNEMPLOYMENT is series and TAB1 is a table in the current workfile,
CALL HEADER1(UNEMPLOYMENT, "UNEMPLOYMENT", TAB1)
will call this subroutine. Since you pass the string label and the variable separately, you could also use this function to put any label in the table.
CALL HEADER1(UNEMPLOYMENT, "Civilian Unemployment", TAB1)
You could also use this to put the wrong label in the table.
CALL HEADER1(UNEMPLOYMENT, "X", TAB1)
To prevent this kind of mislabeling, rewrite the HEADER1 program using the string replacement feature. You give up the ability to put in a more descriptive label than the series name, but you gain confidence that when your output table says it for the series UNEMPLOYMENT, it really is.
There is also a problem with the calculation of the mean in HEADER1. @OBS(IN) returns the number of valid observations within the current workfile sample. Yet you start the accumulation of the !SUM at the first observation, which may not be included in the workfile sample. While you are accurately calculating a mean, it may not be over the expected sample range. The revised program simplifies the calculation of the mean and guarantees that it is calculated over the workfile sample.
The following also generalizes the program to place the header at a row other than row one, and provide formatting for the cells.
SUBROUTINE HEADER2(string %1, TABLE out, SCALAR firstrow)
!MEAN=@MEAN( {%1})
SETCELL(OUT, FIRSTROW, 1, "series:", "L")
SETCELL(OUT, FIRSTROW+1, 1, "Mean:", "L")
SETCELL(OUT, FIRSTROW, 2, %1, "R")
SETCELL(OUT, FIRSTROW+1, 2, !MEAN, "R", -6)
ENDSUB
Now, if UNEMPLOYMENT is a series and TAB2 a table in the current workfile, we may call HEADER2 with, CALL HEADER2("UNEMPLOYMENT", TAB2,1)
We have used braces ({}) a number of times to tell EViews that we are referring to the object named by the string variable %1, rather than the string variable itself. These were not needed in the SETCELL command, as we did want to use the string there.